diff --git a/CHANGELOG.md b/CHANGELOG.md index b6771a1..95d5059 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ 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. +## [0.15.1] - 2026-10-27 + +### Added + +- Settings → Downloads → **Models folder scan**: choose when Kaname looks for importable folders + in the models folder: every 2 minutes (as before, the default), hourly, daily, weekly or monthly + at a time you pick (in your browser's time zone), or only manually. **Scan now** starts one right + away; the card shows the last scan, what it found and when the next one is due. A scan missed + while the worker was down runs when it is back; a restart no longer scans by itself unless one + is due. + ## [0.15.0] - 2026-10-26 Kaname is back to two jobs: downloading models, and benchmarking the servers that run them. It no diff --git a/drizzle/0023_scan_schedule.sql b/drizzle/0023_scan_schedule.sql new file mode 100644 index 0000000..18965d8 --- /dev/null +++ b/drizzle/0023_scan_schedule.sql @@ -0,0 +1,2 @@ +ALTER TABLE `worker_state` ADD `last_scan_at` integer;--> statement-breakpoint +ALTER TABLE `worker_state` ADD `last_scan_found` integer; \ No newline at end of file diff --git a/drizzle/meta/0023_snapshot.json b/drizzle/meta/0023_snapshot.json new file mode 100644 index 0000000..a7740f0 --- /dev/null +++ b/drizzle/meta/0023_snapshot.json @@ -0,0 +1,1512 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "75e38798-32b6-4da5-8108-8e64bcc41065", + "prevId": "67d09da3-db4d-4665-95a9-3fb44079e886", + "tables": { + "benchmark_logs": { + "name": "benchmark_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "run_id": { + "name": "run_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": { + "benchmark_logs_idx": { + "name": "benchmark_logs_idx", + "columns": [ + "run_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_publications": { + "name": "benchmark_publications", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'preview'" + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'bench.betterbench.v1'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_bytes": { + "name": "payload_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "previewed_at": { + "name": "previewed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_by": { + "name": "confirmed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_at": { + "name": "confirmed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "guid": { + "name": "guid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_publications_run_idx": { + "name": "benchmark_publications_run_idx", + "columns": [ + "run_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_runs": { + "name": "benchmark_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "endpoint_b_id": { + "name": "endpoint_b_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'betterbench'" + }, + "settings": { + "name": "settings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snapshot": { + "name": "snapshot", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "phase": { + "name": "phase", + "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 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "has_report": { + "name": "has_report", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'run'" + }, + "snapshot_b": { + "name": "snapshot_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ab": { + "name": "ab", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quality": { + "name": "quality", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta": { + "name": "meta", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta_b": { + "name": "meta_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "system": { + "name": "system", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_runs_created_idx": { + "name": "benchmark_runs_created_idx", + "columns": [ + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoints": { + "name": "endpoints", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_key": { + "name": "api_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "engine": { + "name": "engine", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hardware": { + "name": "hardware", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "probe": { + "name": "probe", + "type": "text", + "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": { + "endpoints_name_uq": { + "name": "endpoints_name_uq", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "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 + }, + "result": { + "name": "result", + "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": {} + }, + "local_folders": { + "name": "local_folders", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_count": { + "name": "file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit": { + "name": "commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scanned_at": { + "name": "scanned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "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 + }, + "update_diff": { + "name": "update_diff", + "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 + }, + "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 + }, + "scan_requested_at": { + "name": "scan_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_scan_at": { + "name": "last_scan_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_scan_found": { + "name": "last_scan_found", + "type": "integer", + "primaryKey": false, + "notNull": false, + "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 674dc10..2204274 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -162,6 +162,13 @@ "when": 1793045228739, "tag": "0022_endpoints", "breakpoints": true + }, + { + "idx": 23, + "version": "6", + "when": 1793115558680, + "tag": "0023_scan_schedule", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 9c2825d..44231b3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaname", - "version": "0.15.0", + "version": "0.15.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaname", - "version": "0.15.0", + "version": "0.15.1", "dependencies": { "@base-ui/react": "^1.8.0", "@libsql/client": "^0.18.0", diff --git a/package.json b/package.json index fff0fcb..b88eca5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kaname", - "version": "0.15.0", + "version": "0.15.1", "private": true, "scripts": { "dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"", diff --git a/src/app/(app)/settings/downloads/page.tsx b/src/app/(app)/settings/downloads/page.tsx index 6dc0852..62cd858 100644 --- a/src/app/(app)/settings/downloads/page.tsx +++ b/src/app/(app)/settings/downloads/page.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next"; -import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings"; +import { getDownloadSpeedLimit, getRecommendedRoles, getScanStatus } from "@/lib/settings"; import { RecommendedSettings } from "./recommended-settings"; +import { ScanSettings } from "./scan-settings"; import { SpeedLimit } from "./speed-limit"; export const dynamic = "force-dynamic"; @@ -11,6 +12,7 @@ export default async function DownloadSettingsPage() {
+
); } diff --git a/src/app/(app)/settings/downloads/scan-settings.tsx b/src/app/(app)/settings/downloads/scan-settings.tsx new file mode 100644 index 0000000..fb6a9bf --- /dev/null +++ b/src/app/(app)/settings/downloads/scan-settings.tsx @@ -0,0 +1,156 @@ +"use client"; + +import { Loader2Icon, ScanSearchIcon } from "lucide-react"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import { toast } from "sonner"; +import { LocalTime } from "@/components/local-time"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { NativeSelect } from "@/components/ui/native-select"; +import { FREQUENCY_LABEL, SCAN_FREQUENCIES, type ScanFrequency } from "@/lib/folder-scan"; +import type { ScanStatus } from "@/lib/settings"; + +const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; +const browserTz = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; +const noSubscribe = () => () => {}; + +/** When the worker looks for importable folders in the models folder, plus "Scan now". */ +export function ScanSettings({ initial }: { initial: ScanStatus }) { + const [status, setStatus] = useState(initial); + const [every, setEvery] = useState(initial.schedule.every); + const [time, setTime] = useState(initial.schedule.time); + const [weekday, setWeekday] = useState(initial.schedule.weekday); + const [monthDay, setMonthDay] = useState(initial.schedule.monthDay); + const [busy, setBusy] = useState(false); + // The browser's zone; the server renders the stored one. + const tz = useSyncExternalStore(noSubscribe, browserTz, () => initial.schedule.tz); + + const s = status.schedule; + const dirty = every !== s.every || time !== s.time || weekday !== s.weekday || monthDay !== s.monthDay || (every !== "2min" && every !== "manual" && tz !== s.tz); + const timed = every === "daily" || every === "weekly" || every === "monthly"; + + // While a requested scan hasn't run yet, refresh until it has. + useEffect(() => { + if (!status.requested) return; + const t = setInterval(async () => { + const res = await fetch("/api/settings/downloads", { cache: "no-store" }).catch(() => null); + if (res?.ok) setStatus((await res.json()).scan); + }, 2_000); + return () => clearInterval(t); + }, [status.requested]); + + async function save() { + setBusy(true); + try { + const res = await fetch("/api/settings/downloads", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ scanSchedule: { every, time, weekday, monthDay, tz } }), + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`); + setStatus(body.scan); + toast.success("Scan schedule saved"); + } finally { + setBusy(false); + } + } + + async function scanNow() { + const res = await fetch("/api/local-folders/scan", { method: "POST" }); + if (!res.ok) return toast.error(`Could not start a scan (${res.status})`); + setStatus((cur) => ({ ...cur, requested: true })); + } + + return ( + + + Models folder scan + + Kaname looks through the models folder for folders that aren't in the library yet, so you can import them. It only lists files and their sizes (no + hashing) and skips the models you already have; on a NAS, a rarer schedule lets the disks sleep. + + + +
+
+ + setEvery(e.target.value as ScanFrequency)} className="w-64"> + {SCAN_FREQUENCIES.map((f) => ( + + ))} + +
+ {every === "weekly" && ( +
+ + setWeekday(Number(e.target.value))} className="w-36"> + {WEEKDAYS.map((d, i) => ( + + ))} + +
+ )} + {every === "monthly" && ( +
+ + setMonthDay(Number(e.target.value))} className="w-24"> + {Array.from({ length: 28 }, (_, i) => i + 1).map((d) => ( + + ))} + +
+ )} + {timed && ( +
+ + setTime(e.target.value || "03:00")} className="w-32" /> +
+ )} + {every === "hourly" && ( +
+ + setTime(`${time.slice(0, 2)}:${e.target.value}`)} className="w-24"> + {Array.from({ length: 12 }, (_, i) => String(i * 5).padStart(2, "0")).map((m) => ( + + ))} + +
+ )} + + +
+ {timed &&

Times are in your time zone ({tz}).

} +
+
Last scan
+
+ {status.lastScanAt ? ( + <> + · {status.lastScanFound ?? 0} folder{status.lastScanFound === 1 ? "" : "s"} to import + + ) : ( + "not yet" + )} +
+
Next scan
+
{status.nextScanAt ? : "only when you click Scan now"}
+
+
+
+ ); +} diff --git a/src/app/api/settings/downloads/route.ts b/src/app/api/settings/downloads/route.ts index df69727..69c5133 100644 --- a/src/app/api/settings/downloads/route.ts +++ b/src/app/api/settings/downloads/route.ts @@ -2,20 +2,21 @@ import { NextResponse } from "next/server"; import { z } from "zod"; import { withAuth } from "@/lib/api-auth"; import { apiError, handleApiError } from "@/lib/api-errors"; -import { getDownloadSpeedLimit, getRecommendedRoles, saveDownloadSpeedLimit, saveRecommendedRoles, SettingsError } from "@/lib/settings"; +import { getDownloadSpeedLimit, getRecommendedRoles, getScanStatus, saveDownloadSpeedLimit, saveRecommendedRoles, saveScanSchedule, SettingsError } from "@/lib/settings"; export const dynamic = "force-dynamic"; async function current() { - return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit() }; + return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit(), scan: await getScanStatus() }; } -/** Download settings: which file kinds are picked along with model weights, and the speed limit. */ +/** Download settings: which file kinds are picked along with model weights, the speed limit, and the models folder scan. */ export const GET = withAuth(async () => NextResponse.json(await current())); const Body = z.object({ recommendedRoles: z.array(z.string()).max(32).optional(), maxBytesPerSecond: z.number().nullable().optional(), + scanSchedule: z.unknown().optional(), }); export const PUT = withAuth(async (req) => { @@ -23,6 +24,7 @@ export const PUT = withAuth(async (req) => { const body = Body.parse(await req.json()); if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles); if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond); + if (body.scanSchedule !== undefined) await saveScanSchedule(body.scanSchedule); return NextResponse.json(await current()); } catch (err) { if (err instanceof SettingsError) return apiError(err.status, err.code, err.message); diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 6940c3f..e1e9c3c 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -342,6 +342,9 @@ export const workerState = sqliteTable("worker_state", { heartbeatAt: ts("heartbeat_at").notNull(), /** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */ scanRequestedAt: ts("scan_requested_at"), + /** The last scan of MODELS_DIR (scheduled, requested or at startup) and how many importable folders it found. */ + lastScanAt: ts("last_scan_at"), + lastScanFound: integer("last_scan_found"), }); /** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */ diff --git a/src/lib/folder-scan.test.ts b/src/lib/folder-scan.test.ts new file mode 100644 index 0000000..2dba751 --- /dev/null +++ b/src/lib/folder-scan.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { DEFAULT_SCAN_SCHEDULE, nextScanAt, parseScanSchedule, type ScanSchedule, scanDue, validateScanSchedule } from "./folder-scan"; + +const at = (iso: string) => new Date(iso); +const s = (o: Partial): ScanSchedule => ({ ...DEFAULT_SCAN_SCHEDULE, tz: "Europe/Berlin", ...o }); + +describe("folder scan schedule", () => { + it("keeps the old every-2-minutes default and never schedules manual-only", () => { + assert.equal(nextScanAt(DEFAULT_SCAN_SCHEDULE, at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-10-27T10:02:00.000Z"); + assert.equal(nextScanAt(s({ every: "manual" }), at("2026-10-27T10:00:00Z")), null); + assert.equal(scanDue(s({ every: "manual" }), null, at("2026-10-27T10:00:00Z")), false); + }); + + it("runs daily at the local time, across a DST change", () => { + const daily = s({ every: "daily", time: "03:00" }); + // Berlin is UTC+1 after the switch on 25 Oct 2026. + assert.equal(nextScanAt(daily, at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-10-28T02:00:00.000Z"); + assert.equal(nextScanAt(daily, at("2026-10-27T01:00:00Z"))!.toISOString(), "2026-10-27T02:00:00.000Z"); + // Still summer time (UTC+2) before the switch. + assert.equal(nextScanAt(daily, at("2026-10-23T12:00:00Z"))!.toISOString(), "2026-10-24T01:00:00.000Z"); + }); + + it("runs hourly at the given minute, weekly on the weekday, monthly on the day", () => { + assert.equal(nextScanAt(s({ every: "hourly", time: "00:15" }), at("2026-10-27T10:20:00Z"))!.toISOString(), "2026-10-27T11:15:00.000Z"); + // 27 Oct 2026 is a Tuesday; next Sunday is 1 Nov. + assert.equal(nextScanAt(s({ every: "weekly", weekday: 0, time: "04:30" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-01T03:30:00.000Z"); + assert.equal(nextScanAt(s({ every: "monthly", monthDay: 1, time: "03:00" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-01T02:00:00.000Z"); + assert.equal(nextScanAt(s({ every: "monthly", monthDay: 27, time: "03:00" }), at("2026-10-27T10:00:00Z"))!.toISOString(), "2026-11-27T02:00:00.000Z"); + }); + + it("is due once the next slot after the last scan has passed (also after downtime)", () => { + const daily = s({ every: "daily", time: "03:00" }); + assert.equal(scanDue(daily, null, at("2026-10-27T10:00:00Z")), true, "never scanned"); + assert.equal(scanDue(daily, at("2026-10-27T02:00:30Z"), at("2026-10-27T10:00:00Z")), false); + assert.equal(scanDue(daily, at("2026-10-27T02:00:30Z"), at("2026-10-28T02:00:00Z")), true); + assert.equal(scanDue(daily, at("2026-10-25T02:00:30Z"), at("2026-10-27T10:00:00Z")), true, "missed while the worker was down"); + }); + + it("validates input and falls back to the default for broken stored values", () => { + assert.deepEqual(validateScanSchedule({ every: "weekly", time: "23:59", weekday: 6, monthDay: 1, tz: "America/New_York" }), { + every: "weekly", + time: "23:59", + weekday: 6, + monthDay: 1, + tz: "America/New_York", + }); + assert.throws(() => validateScanSchedule({ every: "yearly", time: "03:00" }), /Frequency/); + assert.throws(() => validateScanSchedule({ every: "daily", time: "24:00" }), /HH:MM/); + assert.throws(() => validateScanSchedule({ every: "monthly", time: "03:00", monthDay: 31 }), /1–28/); + assert.throws(() => validateScanSchedule({ every: "daily", time: "03:00", tz: "Mars/Base" }), /time zone/); + assert.deepEqual(parseScanSchedule({ every: "nope" }), DEFAULT_SCAN_SCHEDULE); + }); +}); diff --git a/src/lib/folder-scan.ts b/src/lib/folder-scan.ts new file mode 100644 index 0000000..ab13dbc --- /dev/null +++ b/src/lib/folder-scan.ts @@ -0,0 +1,121 @@ +// When the worker scans the models folder for importable folders (Settings → Downloads). Pure; +// shared by the settings API, the settings page and the worker. Times are wall-clock times in the +// time zone the schedule was saved in (the browser's), so "03:00" means 03:00 for the user. + +export const SCAN_SCHEDULE_KEY = "scan.schedule"; + +export const SCAN_FREQUENCIES = ["2min", "hourly", "daily", "weekly", "monthly", "manual"] as const; +export type ScanFrequency = (typeof SCAN_FREQUENCIES)[number]; + +export type ScanSchedule = { + every: ScanFrequency; + /** "HH:MM"; hourly uses only the minutes. */ + time: string; + /** weekly: 0 = Sunday … 6 = Saturday. */ + weekday: number; + /** monthly: 1–28 (every month has those). */ + monthDay: number; + /** IANA time zone, e.g. "Europe/Berlin". */ + tz: string; +}; + +/** Before this setting existed the worker scanned every 2 minutes; that stays the default. */ +export const DEFAULT_SCAN_SCHEDULE: ScanSchedule = { every: "2min", time: "03:00", weekday: 1, monthDay: 1, tz: "UTC" }; + +export const FREQUENCY_LABEL: Record = { + "2min": "Every 2 minutes", + hourly: "Hourly", + daily: "Daily", + weekly: "Weekly", + monthly: "Monthly", + manual: "Only when I click Scan now", +}; + +export class ScanScheduleError extends Error {} + +export function validTimeZone(tz: string): boolean { + try { + new Intl.DateTimeFormat("en-US", { timeZone: tz }); + return true; + } catch { + return false; + } +} + +/** Validate input from the settings form; throws ScanScheduleError. */ +export function validateScanSchedule(input: unknown): ScanSchedule { + const o = (input ?? {}) as Record; + const every = o.every as ScanFrequency; + if (!SCAN_FREQUENCIES.includes(every)) throw new ScanScheduleError(`Frequency must be one of: ${SCAN_FREQUENCIES.join(", ")}.`); + const time = typeof o.time === "string" ? o.time.trim() : ""; + const m = time.match(/^([01]\d|2[0-3]):([0-5]\d)$/); + if (!m) throw new ScanScheduleError('Time must be "HH:MM" (24 hours).'); + const weekday = Number(o.weekday ?? 1); + if (!Number.isInteger(weekday) || weekday < 0 || weekday > 6) throw new ScanScheduleError("Weekday must be 0 (Sunday) to 6 (Saturday)."); + const monthDay = Number(o.monthDay ?? 1); + if (!Number.isInteger(monthDay) || monthDay < 1 || monthDay > 28) throw new ScanScheduleError("Day of the month must be 1–28."); + const tz = typeof o.tz === "string" && o.tz ? o.tz : "UTC"; + if (!validTimeZone(tz)) throw new ScanScheduleError(`Unknown time zone "${tz}".`); + return { every, time, weekday, monthDay, tz }; +} + +/** The stored schedule; anything invalid falls back to the default rather than stopping scans. */ +export function parseScanSchedule(stored: unknown): ScanSchedule { + try { + return validateScanSchedule(stored); + } catch { + return DEFAULT_SCAN_SCHEDULE; + } +} + +type Parts = { y: number; mo: number; d: number; h: number; mi: number; wd: number }; +const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + +/** Wall-clock date and time of `t` in `tz`. */ +function partsIn(t: number, tz: string): Parts { + const f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", weekday: "short" }); + const p = Object.fromEntries(f.formatToParts(new Date(t)).map((x) => [x.type, x.value])); + return { y: Number(p.year), mo: Number(p.month), d: Number(p.day), h: Number(p.hour), mi: Number(p.minute), wd: WEEKDAYS.indexOf(p.weekday) }; +} + +/** The instant a wall-clock time in `tz` happens (in a DST gap: shortly after). */ +function zonedToUtc(y: number, mo: number, d: number, h: number, mi: number, tz: string): number { + const wall = Date.UTC(y, mo - 1, d, h, mi); + const offsetAt = (t: number) => { + const p = partsIn(t, tz); + return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi) - Math.floor(t / 60_000) * 60_000; + }; + let t = wall - offsetAt(wall); + t = wall - offsetAt(t); + return t; +} + +/** The first scheduled scan strictly after `after`; null for manual-only. */ +export function nextScanAt(s: ScanSchedule, after: Date): Date | null { + const from = after.getTime(); + if (s.every === "manual") return null; + if (s.every === "2min") return new Date(from + 2 * 60_000); + const [hh, mm] = s.time.split(":").map(Number); + const start = partsIn(from, s.tz); + // Walk local calendar days from `after`'s day on; 62 covers a month plus DST and edge cases. + for (let i = 0; i <= 62; i++) { + const day = new Date(Date.UTC(start.y, start.mo - 1, start.d + i)); + const [y, mo, d, wd] = [day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), day.getUTCDay()]; + if (s.every === "weekly" && wd !== s.weekday) continue; + if (s.every === "monthly" && d !== s.monthDay) continue; + const hours = s.every === "hourly" ? Array.from({ length: 24 }, (_, h) => h) : [hh]; + for (const h of hours) { + const t = zonedToUtc(y, mo, d, h, mm, s.tz); + if (t > from) return new Date(t); + } + } + return null; +} + +/** Is a scheduled scan due? Never scanned: yes (the import list would stay empty otherwise). */ +export function scanDue(s: ScanSchedule, lastScanAt: Date | null, now: Date): boolean { + if (s.every === "manual") return false; + if (!lastScanAt) return true; + const next = nextScanAt(s, lastScanAt); + return !!next && next.getTime() <= now.getTime(); +} diff --git a/src/lib/settings.ts b/src/lib/settings.ts index 2d0b362..c21cbb5 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -1,10 +1,11 @@ import "server-only"; import { eq } from "drizzle-orm"; import { db } from "@/lib/db/client"; -import { settings } from "@/lib/db/schema"; +import { settings, workerState } from "@/lib/db/schema"; import { isLabelColor } from "@/lib/colors"; import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles"; import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit"; +import { nextScanAt, parseScanSchedule, SCAN_SCHEDULE_KEY, type ScanSchedule, ScanScheduleError, validateScanSchedule } from "@/lib/folder-scan"; import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend"; const FILE_ROLES_KEY = "labels.fileRoles"; @@ -99,3 +100,43 @@ export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Pro else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond)); return getDownloadSpeedLimit(); } + +/** When the worker scans the models folder for importable folders (Settings → Downloads). */ +export async function getScanSchedule(): Promise { + return parseScanSchedule(await read(SCAN_SCHEDULE_KEY)); +} + +export async function saveScanSchedule(input: unknown): Promise { + try { + await write(SCAN_SCHEDULE_KEY, validateScanSchedule(input)); + } catch (err) { + if (err instanceof ScanScheduleError) throw new SettingsError(err.message); + throw err; + } + return getScanSchedule(); +} + +export type ScanStatus = { + schedule: ScanSchedule; + lastScanAt: number | null; + lastScanFound: number | null; + /** A "Scan now" the worker hasn't started yet. */ + requested: boolean; + nextScanAt: number | null; +}; + +export async function getScanStatus(): Promise { + const [schedule, ws] = await Promise.all([ + getScanSchedule(), + db().query.workerState.findFirst({ columns: { lastScanAt: true, lastScanFound: true, scanRequestedAt: true }, where: eq(workerState.id, "worker") }), + ]); + const last = ws?.lastScanAt ?? null; + const next = schedule.every === "manual" ? null : last ? nextScanAt(schedule, last) : new Date(); + return { + schedule, + lastScanAt: last?.getTime() ?? null, + lastScanFound: ws?.lastScanFound ?? null, + requested: !!ws?.scanRequestedAt && (!last || ws.scanRequestedAt > last), + nextScanAt: next?.getTime() ?? null, + }; +} diff --git a/src/worker/index.ts b/src/worker/index.ts index 481aa8e..2be4602 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -7,8 +7,9 @@ import { promisify } from "node:util"; import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { runMigrations } from "@/lib/db/migrate"; -import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema"; +import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, settings, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; +import { parseScanSchedule, SCAN_SCHEDULE_KEY, scanDue } from "@/lib/folder-scan"; import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability"; import { backfillMetadata } from "@/lib/hub/refresh"; import { DeleteRunner } from "./delete"; @@ -29,7 +30,8 @@ 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; /** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */ -const FOLDER_SCAN_MS = 2 * 60_000; +/** How often the worker checks whether a scheduled scan of MODELS_DIR is due (Settings → Downloads). */ +const FOLDER_SCAN_CHECK_MS = 30_000; const LOG_FLUSH_INTERVAL_MS = 1_000; const BENCHMARK_TICK_MS = 2_000; /** Touched on every heartbeat; the Docker healthcheck checks its age. */ @@ -282,6 +284,7 @@ async function scanFolders() { lastScanStartedAt = Date.now(); try { const n = await scanModelsDir(coreEnv().MODELS_DIR); + await db().update(workerState).set({ lastScanAt: new Date(), lastScanFound: n }).where(eq(workerState.id, "worker")); if (n > 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`); } catch (err) { log.error("models dir scan failed", err); @@ -290,6 +293,20 @@ async function scanFolders() { } } +/** Scan when the schedule says so; the last scan is stored, so a restart doesn't scan again early. */ +async function scanIfDue() { + if (scanning || stopping) return; + try { + const [row, ws] = await Promise.all([ + db().query.settings.findFirst({ where: eq(settings.key, SCAN_SCHEDULE_KEY) }), + db().query.workerState.findFirst({ columns: { lastScanAt: true }, where: eq(workerState.id, "worker") }), + ]); + if (scanDue(parseScanSchedule(row?.value), ws?.lastScanAt ?? null, new Date())) await scanFolders(); + } catch (err) { + log.error("scan schedule check failed", err); + } +} + let checkingHub = false; async function checkHubDue() { const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS; @@ -382,7 +399,7 @@ async function main() { 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)); - timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS)); + timers.push(setInterval(() => void scanIfDue(), FOLDER_SCAN_CHECK_MS)); // Benchmarks: one run at a time against an endpoint. await recoverBenchmarks(); @@ -391,7 +408,7 @@ async function main() { timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS)); - void scanFolders(); + void scanIfDue(); void tick(); setTimeout(() => void checkHubDue(), 15_000); }