Delete, verify/deep verify, repair and update checks

- Delete any model (incl. failed ones); the worker removes the repo's
  files (keeps foreign files and empty-folder cleanup), then the rows.
- Verify (existence, size, hf metadata) and deep verify (SHA-256 /
  git blob SHA-1 against the Hub) with missing/mismatch/extra report.
- Repair = download of the selection; broken files are deleted first
  because hf skips files whose metadata matches without checking them.
- Hub check resolves the tracked revision and stores which selected
  files a newer commit changes/adds/removes; Update pins it (old commit
  kept in model_revisions), downloads, then removes dropped files.
- Worker runs verify/delete jobs next to downloads (2 local slots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 01:00:55 +02:00
1 parent c2c239bf16
commit 7864a492c9
37 files changed
+2365 -191

No files matched your search

+28 -1
View File
@@ -50,6 +50,30 @@ export type ModelStatus = (typeof MODEL_STATUSES)[number];
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
export type HubState = (typeof HUB_STATES)[number];
export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
export type UpdateDiff = {
/** Commit the diff was computed against (the tracked revision's head on the Hub). */
sha: string;
changed: UpdateDiffFile[];
added: UpdateDiffFile[];
removed: UpdateDiffFile[];
checkedAt: string;
};
/** Outcome of a verify job, or extra instructions for a job (`removePaths` after an update). */
export type JobResult = {
checked?: number;
missing?: string[];
sizeMismatch?: string[];
hashMismatch?: string[];
/** Files in the model folder that aren't selected repo files. */
extra?: { path: string; size: number; inRepo: boolean }[];
/** Update jobs: files of the old revision to delete once the download succeeded. */
removePaths?: string[];
/** Delete jobs: files that were kept because they don't belong to the repo. */
kept?: string[];
};
export const models = sqliteTable(
"models",
{
@@ -81,6 +105,8 @@ export const models = sqliteTable(
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"),
/** What updating to `remoteSha` would change in the selection; null when up to date. */
updateDiff: text("update_diff", { mode: "json" }).$type<UpdateDiff>(),
lastVerifiedAt: ts("last_verified_at"),
downloadedAt: ts("downloaded_at"),
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
@@ -190,7 +216,7 @@ export const modelFiles = sqliteTable(
// Jobs (executed by the worker)
// ---------------------------------------------------------------------------
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
@@ -239,6 +265,7 @@ export const jobs = sqliteTable(
exitCode: integer("exit_code"),
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
errorMessage: text("error_message"),
result: text("result", { mode: "json" }).$type<JobResult>(),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
+90 -24
View File
@@ -1,9 +1,28 @@
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";
// Hub checks per model: is the repo (and the pinned commit) still there, and is there a newer
// commit on the tracked revision? Run periodically by the worker and on "Check now". Results are
// stored on the model; nothing local is ever changed by a check.
type CheckedModel = Pick<typeof models.$inferSelect, "id" | "repoId" | "pinnedSha" | "hubMissingSince">;
import { and, asc, eq, isNull, lt, or } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema";
import { computeUpdateDiff } from "@/lib/update-diff";
import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client";
type CheckedModel = Pick<
typeof models.$inferSelect,
"id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns"
>;
const CHECKED_COLUMNS = {
id: models.id,
repoId: models.repoId,
pinnedSha: models.pinnedSha,
trackedRevision: models.trackedRevision,
hubMissingSince: models.hubMissingSince,
updateDiff: models.updateDiff,
includePatterns: models.includePatterns,
excludePatterns: models.excludePatterns,
};
/** 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 {
@@ -16,25 +35,73 @@ export function hubMissingMessage(model: { repoId: string; hubState: HubState |
return null;
}
export type HubCheckResult = { state: HubState } | { state: null; error: string };
export type HubCheckResult =
| { state: HubState; remoteSha: string | null; update: UpdateDiff | null; warning: string | null }
| { state: null; error: string };
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
const isGated = (err: unknown) => err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access");
/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */
async function resolve(repoId: string, revision: string): Promise<string | null> {
try {
return (await getRepoInfo(repoId, revision)).sha;
} catch (err) {
if (err instanceof HubError && err.code === "revision_not_found") return null;
throw err;
}
}
async function run(model: CheckedModel): Promise<HubCheckResult> {
// 1. Head of the tracked revision (a full SHA as revision means "pinned for good").
let remoteSha: string | null;
let warning: string | null = null;
if (SHA_RE.test(model.trackedRevision)) {
remoteSha = model.trackedRevision;
} else {
remoteSha = await resolve(model.repoId, model.trackedRevision);
if (!remoteSha) warning = `Revision "${model.trackedRevision}" no longer exists on the Hub; can't check for updates.`;
}
// 2. Is the pinned commit still there? (Known if it's the head.)
const pinnedExists = remoteSha === model.pinnedSha || (await resolve(model.repoId, model.pinnedSha)) !== null;
const state: HubState = pinnedExists ? "available" : "commit_missing";
// 3. Newer commit: what would change in the selection? Only recomputed when the head moved.
let update: UpdateDiff | null = null;
if (remoteSha && remoteSha !== model.pinnedSha) {
update = model.updateDiff?.sha === remoteSha ? model.updateDiff : null;
if (!update) {
const [next, current] = await Promise.all([
listFiles(model.repoId, remoteSha),
db()
.select({ path: modelFiles.path, size: modelFiles.size, blobOid: modelFiles.blobOid, lfsSha256: modelFiles.lfsSha256 })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, model.id), eq(modelFiles.selected, true))),
]);
update = computeUpdateDiff(remoteSha, current, next, { include: model.includePatterns, exclude: model.excludePatterns });
}
}
return { state, remoteSha, update, warning };
}
/**
* 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.
* Check one model against the Hub and store the result. Only a definite answer changes the stored
* state; network errors, rate limits or a bad token are kept as `lastCheckError`.
*/
export async function checkHubAvailability(model: CheckedModel): Promise<HubCheckResult> {
export async function checkHub(model: CheckedModel): Promise<HubCheckResult> {
let result: HubCheckResult;
try {
await getRepoInfo(model.repoId, model.pinnedSha);
result = { state: "available" };
result = await run(model);
} 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) };
if (err instanceof HubError && err.code === "repo_not_found") {
result = { state: "repo_missing", remoteSha: null, update: null, warning: null };
} else if (isGated(err)) {
// Gated repos exist; access is a download concern.
result = { state: "available", remoteSha: null, update: model.updateDiff ?? null, warning: message(err) };
} else {
result = { state: null, error: message(err) };
}
}
const now = new Date();
@@ -45,9 +112,10 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
? { lastCheckedAt: now, lastCheckError: result.error }
: {
lastCheckedAt: now,
lastCheckError: null,
lastCheckError: result.warning,
hubState: result.state,
hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now),
...(result.state === "repo_missing" ? {} : { remoteSha: result.remoteSha, updateDiff: result.update }),
},
)
.where(eq(models.id, model.id));
@@ -58,7 +126,7 @@ export async function checkHubAvailability(model: CheckedModel): Promise<HubChec
export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Promise<CheckedModel[]> {
const cutoff = new Date(Date.now() - intervalMs);
return db()
.select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince })
.select(CHECKED_COLUMNS)
.from(models)
.where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff)))
.orderBy(asc(models.lastCheckedAt))
@@ -66,8 +134,6 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom
}
export async function getCheckedModel(id: string): Promise<CheckedModel | undefined> {
return db().query.models.findFirst({
columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true },
where: eq(models.id, id),
});
const [row] = await db().select(CHECKED_COLUMNS).from(models).where(eq(models.id, id));
return row;
}
+16
View File
@@ -0,0 +1,16 @@
// Human-readable job names (shared by UI components).
const DOWNLOAD_PURPOSE: Record<string, string> = {
initial: "Download",
add: "Download more",
import: "Import",
repair: "Repair",
update: "Update",
};
const KIND: Record<string, string> = { download: "Download", verify: "Verify", deep_verify: "Deep verify", delete: "Delete" };
export function jobLabel(job: { kind: string; purpose: string | null }): string {
if (job.kind === "download") return DOWNLOAD_PURPOSE[job.purpose ?? "initial"] ?? "Download";
return KIND[job.kind] ?? job.kind;
}
+54 -8
View File
@@ -6,6 +6,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
import {
ACTIVE_JOB_STATES,
type JobPurpose,
type JobResult,
jobFiles,
jobLogs,
jobs,
@@ -26,19 +27,31 @@ export class JobError extends Error {
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
const INSERT_CHUNK = 500;
/** Queue a download of all selected files of a model at its pinned SHA. */
export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> {
/** True if the model has a queued or running job (only one job per model at a time). */
export async function hasOpenJob(modelId: string): Promise<boolean> {
const open = await db().query.jobs.findFirst({
columns: { id: true },
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
});
return !!open;
}
/**
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
* revision to delete once the download succeeded (updates).
*/
export async function queueDownload(
modelId: string,
purpose: JobPurpose = "initial",
options: { removePaths?: string[] } = {},
): Promise<{ jobId: string }> {
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 },
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])),
});
if (open) throw new JobError("busy", "This model already has a queued or running job.", 409);
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
const files = await d
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
@@ -57,6 +70,7 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
purpose,
targetSha: model.pinnedSha,
totalBytes: files.reduce((s, f) => s + f.size, 0),
result: options.removePaths?.length ? { removePaths: options.removePaths } : null,
}),
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
@@ -64,6 +78,36 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init
return { jobId };
}
/** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */
export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> {
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);
if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409);
const files = await d
.select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true)))
.orderBy(asc(modelFiles.path));
if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400);
const jobId = ulid();
await d.batch([
d.insert(jobs).values({
id: jobId,
modelId,
kind: deep ? "deep_verify" : "verify",
targetSha: model.pinnedSha,
totalBytes: files.reduce((s, f) => s + f.size, 0),
}),
...chunk(
files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })),
INSERT_CHUNK,
).map((c) => d.insert(jobFiles).values(c)),
]);
return { jobId };
}
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
export async function requestCancel(jobId: string): Promise<void> {
const res = await db()
@@ -97,6 +141,7 @@ export type JobSnapshot = {
exitCode: number | null;
errorCode: string | null;
errorMessage: string | null;
result: JobResult | null;
cancelRequested: boolean;
createdAt: number;
startedAt: number | null;
@@ -128,6 +173,7 @@ const jobColumns = {
exitCode: jobs.exitCode,
errorCode: jobs.errorCode,
errorMessage: jobs.errorMessage,
result: jobs.result,
cancelRequestedAt: jobs.cancelRequestedAt,
createdAt: jobs.createdAt,
startedAt: jobs.startedAt,
+3 -1
View File
@@ -21,6 +21,7 @@ export async function listLibrary() {
remoteSha: models.remoteSha,
status: models.status,
hubState: models.hubState,
updateDiff: models.updateDiff,
createdAt: models.createdAt,
downloadedAt: models.downloadedAt,
baseModels: models.baseModels,
@@ -51,8 +52,9 @@ export async function listLibrary() {
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
return rows.map((r) => ({
return rows.map(({ updateDiff, ...r }) => ({
...r,
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
author: r.repoId.split("/")[0],
families: modelFamilies(r.repoId, r.baseModels),
baseModels: r.baseModels ?? [],
+20
View File
@@ -0,0 +1,20 @@
// Remove a model and everything that references it from the database (not its files).
// Shared by the web app and the worker, so no "server-only" import here.
import { eq, inArray } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { jobFiles, jobLogs, jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
export async function purgeModelRows(modelId: string): Promise<void> {
const d = db();
const jobIds = d.select({ id: jobs.id }).from(jobs).where(eq(jobs.modelId, modelId));
await d.batch([
d.delete(jobLogs).where(inArray(jobLogs.jobId, jobIds)),
d.delete(jobFiles).where(inArray(jobFiles.jobId, jobIds)),
d.delete(jobs).where(eq(jobs.modelId, modelId)),
d.delete(modelTags).where(eq(modelTags.modelId, modelId)),
d.delete(modelFiles).where(eq(modelFiles.modelId, modelId)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, modelId)),
d.delete(models).where(eq(models.id, modelId)),
]);
}
+97 -22
View File
@@ -1,18 +1,20 @@
import "server-only";
import { and, eq, inArray, sql } from "drizzle-orm";
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } 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 { getLocalFolder } from "@/lib/local-folders";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
import { contentId } from "@/lib/update-diff";
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
export class ModelError extends Error {
constructor(
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy" | "hub_missing",
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
message: string,
public status: number,
) {
@@ -88,28 +90,100 @@ export async function addModel(input: {
return { id: modelId };
}
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
export async function removeModel(id: string): Promise<void> {
/**
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
* files that aren't part of the repo are kept); without, only the library entry goes and the
* folder shows up under "Found in the models folder" again.
*/
export async function deleteModel(id: string, options: { deleteFiles: boolean }): Promise<{ queued: boolean }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const [{ n }] = await d
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(eq(jobs.modelId, id));
if (model.status !== "pending" || n > 0) {
throw new ModelError(
"not_removable",
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
409,
);
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
}
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
const neverDownloaded = model.status === "pending" && n === 0;
if (!options.deleteFiles || neverDownloaded) {
await purgeModelRows(id);
if (!neverDownloaded) await requestFolderScan();
return { queued: false };
}
await d.batch([
d.delete(modelTags).where(eq(modelTags.modelId, id)),
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
d.delete(models).where(eq(models.id, id)),
d.insert(jobs).values({ id: ulid(), modelId: id, kind: "delete", targetSha: model.pinnedSha }),
d.update(models).set({ status: "deleting" }).where(eq(models.id, id)),
]);
return { queued: true };
}
/**
* Update a model to the newer commit found by the last Hub check: pin it (the old commit stays in
* the revision history), refresh the file list, re-apply the selection rule and queue a download.
* Unchanged files are kept; changed ones are downloaded again; files that are no longer selected are
* deleted after the download succeeded.
*/
export async function applyUpdate(id: string): Promise<{ jobId: string; sha: string }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const missing = hubMissingMessage(model);
if (missing) throw new ModelError("hub_missing", missing, 409);
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Try again when it has finished.", 409);
}
const target = model.updateDiff?.sha;
if (!target || target !== model.remoteSha || target === model.pinnedSha) {
throw new ModelError("no_update", "No update available. Check the Hub again.", 409);
}
const info = await getRepoInfo(model.repoId, target);
const files = await listFiles(model.repoId, info.sha);
const rule: SelectionRule = { include: model.includePatterns, exclude: model.excludePatterns };
const existing = await d.select().from(modelFiles).where(eq(modelFiles.modelId, id));
const byPath = new Map(existing.map((f) => [f.path, f]));
const next = new Set(files.map((f) => f.path));
const now = new Date();
const writes = [];
for (const f of files) {
const selected = isSelected(f.path, rule);
const old = byPath.get(f.path);
if (!old) {
writes.push(d.insert(modelFiles).values({ modelId: id, path: f.path, size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected }));
continue;
}
const same = contentId(old) === contentId(f);
if (same && old.selected === selected) continue;
writes.push(
d
.update(modelFiles)
.set({ size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected, state: same ? old.state : "pending" })
.where(eq(modelFiles.id, old.id)),
);
}
// Files gone at the new commit: drop them (and their rows in old jobs' file lists).
const gone = existing.filter((f) => !next.has(f.path));
if (gone.length > 0) {
const ids = gone.map((f) => f.id);
writes.push(d.delete(jobFiles).where(inArray(jobFiles.modelFileId, ids)), d.delete(modelFiles).where(inArray(modelFiles.id, ids)));
}
// Selected before, not anymore (removed from the repo or no longer matching): delete after the download.
const removePaths = existing.filter((f) => f.selected && (!next.has(f.path) || !isSelected(f.path, rule))).map((f) => f.path);
await d.batch([
d
.update(models)
.set({ pinnedSha: info.sha, updateDiff: null, ...metadataColumns(info.metadata, model.authorAvatarUrl) })
.where(eq(models.id, id)),
d
.update(modelRevisions)
.set({ supersededAt: now })
.where(and(eq(modelRevisions.modelId, id), isNull(modelRevisions.supersededAt))),
d.insert(modelRevisions).values({ modelId: id, sha: info.sha }),
...writes,
]);
const { jobId } = await queueDownload(id, "update", { removePaths });
return { jobId, sha: info.sha };
}
function chunk<T>(items: T[], size: number): T[][] {
@@ -148,7 +222,8 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
await d.batch([
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
...changed.map((f) =>
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
),
+34
View File
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { computeUpdateDiff, diffHasChanges } from "./update-diff";
const f = (path: string, oid: string, size = 10, lfs = true) => ({
path,
size,
blobOid: `blob-${oid}`,
lfsSha256: lfs ? `sha-${oid}` : null,
});
describe("computeUpdateDiff", () => {
const current = [f("Q4_K_M.gguf", "a"), f("mmproj-F16.gguf", "b"), f("config.json", "c", 1, false)];
const rule = { include: ["Q4_K_M.gguf", "mmproj-F16.gguf", "*.json"], exclude: [] };
it("finds changed, added and removed selected files", () => {
const next = [
f("Q4_K_M.gguf", "a2", 12), // re-quantized
f("config.json", "c", 1, false), // unchanged
f("generation_config.json", "d", 1, false), // new, matches *.json
f("Q8_0.gguf", "e"), // new, not selected
];
const d = computeUpdateDiff("new", current, next, rule, new Date(0));
assert.deepEqual(d.changed, [{ path: "Q4_K_M.gguf", size: 12, oldSize: 10 }]);
assert.deepEqual(d.added, [{ path: "generation_config.json", size: 1 }]);
assert.deepEqual(d.removed, [{ path: "mmproj-F16.gguf", size: 10 }]);
assert.ok(diffHasChanges(d));
});
it("reports nothing when the selected files are identical", () => {
const d = computeUpdateDiff("new", current, [...current, f("README.md", "r", 1, false)], rule);
assert.ok(!diffHasChanges(d));
});
});
+34
View File
@@ -0,0 +1,34 @@
// What updating a model to a newer commit would change in its selection. Pure; used by the worker
// (update checks) and the web app (applying an update).
import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema";
import { isSelected, type SelectionRule } from "@/lib/selection";
type RepoFile = { path: string; size: number; blobOid: string | null; lfsSha256: string | null };
/** Content identity of a file: the LFS SHA-256, else the git blob SHA-1. */
export const contentId = (f: { blobOid: string | null; lfsSha256: string | null }) => f.lfsSha256 ?? f.blobOid ?? "";
/**
* Compare the currently selected files with the files the same selection rule picks at the new
* commit: changed content, newly matching files, and selected files that are gone.
*/
export function computeUpdateDiff(sha: string, current: RepoFile[], next: RepoFile[], rule: SelectionRule, now = new Date()): UpdateDiff {
const before = new Map(current.map((f) => [f.path, f]));
const after = new Map(next.filter((f) => isSelected(f.path, rule)).map((f) => [f.path, f]));
const changed: UpdateDiffFile[] = [];
const added: UpdateDiffFile[] = [];
const removed: UpdateDiffFile[] = [];
for (const [path, f] of after) {
const old = before.get(path);
if (!old) added.push({ path, size: f.size });
else if (contentId(old) !== contentId(f)) changed.push({ path, size: f.size, oldSize: old.size });
}
for (const [path, f] of before) if (!after.has(path)) removed.push({ path, size: f.size });
const byPath = (a: UpdateDiffFile, b: UpdateDiffFile) => a.path.localeCompare(b.path);
return { sha, changed: changed.sort(byPath), added: added.sort(byPath), removed: removed.sort(byPath), checkedAt: now.toISOString() };
}
/** True if updating would change anything in the selection. */
export const diffHasChanges = (d: UpdateDiff | null | undefined) =>
!!d && d.changed.length + d.added.length + d.removed.length > 0;