From 4cb0e28a3f23c7f53750307d9bff61e6aea089f2 Mon Sep 17 00:00:00 2001 From: Misha Skvortsov Date: Tue, 1 Dec 2026 13:19:18 +0300 Subject: [PATCH 1/2] Import local LoRA weights for installed base models --- docs/contracts.md | 4 + .../2026-12-01-import-local-lora-weights.md | 5 + docs/decisions/INDEX.md | 1 + src/core/create.ts | 27 ++- src/drafters/lora-import.test.ts | 19 ++ src/drafters/lora-import.ts | 130 +++++++++++++ src/drafters/lora-service.test.ts | 96 +++++++++- src/drafters/lora-service.ts | 179 +++++++++++++----- src/server/control/routes/loras.test.ts | 2 + src/server/control/routes/loras.ts | 12 ++ src/server/control/types.ts | 5 +- test/app-e2e/README.md | 4 + test/e2e/lora-import.test.ts | 55 ++++++ 13 files changed, 480 insertions(+), 59 deletions(-) create mode 100644 docs/decisions/2026-12-01-import-local-lora-weights.md create mode 100644 src/drafters/lora-import.test.ts create mode 100644 src/drafters/lora-import.ts create mode 100644 test/e2e/lora-import.test.ts diff --git a/docs/contracts.md b/docs/contracts.md index 3a1814d2..3887755a 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -415,3 +415,7 @@ The authenticated control API serves upstream GGUF drafters independently of cha | GET /models/llamacpp-upstream/*modelId/drafter/selection | Read just the selected ID for chat routing. | The data folder holds `llamacpp/drafters/.gguf` and its inventory in `llamacpp/drafters/index.json`. Each model installation can contain `upstream-drafter.json` with its selected content ID and target-file identity. Legacy installations default to no DSpark selection. + +### Local LoRA import + +On the loopback control listener, `GET /atomic/v1/loras/import-models?format=gguf|safetensors` returns installed candidates as `{ mode, model }[]`. `POST /atomic/v1/loras/import` accepts `{ path, mode, model }` and returns the installed artifact. A local artifact has `source: "local"`, a filename, size, SHA-256, mode and target. Import does not select it. Clients use the existing choices API to activate an adapter. diff --git a/docs/decisions/2026-12-01-import-local-lora-weights.md b/docs/decisions/2026-12-01-import-local-lora-weights.md new file mode 100644 index 00000000..bfad72fe --- /dev/null +++ b/docs/decisions/2026-12-01-import-local-lora-weights.md @@ -0,0 +1,5 @@ +# Import local LoRA weights into Core storage + +The desktop file picker passes an absolute path and an installed base model to the loopback control API. Core inspects a staged copy, compares declared checkpoint metadata when available, and registers the validated weights by SHA-256. A local inventory entry stores its filename and source. Existing Hugging Face records keep their published provenance. When the checkpoint has no identifiable repository, local compatibility is scoped to the selected installation and its signature. + +Import and selection are distinct operations. Import never reloads a session. Removing an imported adapter removes the managed copy and clears its selections. The user owns the original. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index 5bc5036d..7822b993 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -297,3 +297,4 @@ add a new one that says which record it supersedes. - [2026-11-23 — Compact overflowing chat history on every engine](2026-11-23-compact-overflowing-chat-history-on-every-engine.md) - [2026-11-23 — Map every engine's context overflow to one error](2026-11-23-map-every-engines-context-overflow-to-one-error.md) - [2026-11-23 — Default every engine to the largest window that fits](2026-11-23-default-every-engine-to-the-largest-window-that-fits.md) +- [2026-12-01 — Import local LoRA weights into Core storage](2026-12-01-import-local-lora-weights.md) diff --git a/src/core/create.ts b/src/core/create.ts index 1446a0e9..89962e19 100644 --- a/src/core/create.ts +++ b/src/core/create.ts @@ -1,14 +1,15 @@ -import type { AtomicCatalogEntry } from '../client/model-catalog.js' +import type { AtomicModelCatalog } from '../client/model-catalog.js' /** * The dependency wiring behind `AtomicCore.create()`: take the instance lock, open every store, build * the runtimes and backend services, start the control listener, construct the facade, reap what a * previous owner left running and only then publish the endpoint. */ -import { lstat } from 'node:fs/promises' +import { lstat, stat } from 'node:fs/promises' import catalogBaseline from '../client/model-catalog-baseline.json' with { type: 'json' } import { FifoLock } from '../runtime/shared/fifo-lock.js' import { LoraService } from '../drafters/lora-service.js' +import { installedMediaBases } from '../drafters/lora-import.js' import { catalogLoras } from '../drafters/lora-catalog.js' import { DrafterDiscovery, repoId } from '../drafters/catalog.js' import { @@ -316,6 +317,7 @@ export async function createAtomicCore( attachmentMutations ) const mediaCheckpoints = new DrafterDiscovery(options.fetch ?? fetch) + let loraModels: Pick = catalogBaseline const loras: LoraService = new LoraService( layout.root, downloader, @@ -323,16 +325,29 @@ export async function createAtomicCore( catalogLoras(catalogBaseline), (model, previous) => drafters.checkpoint(model, previous), (model, rollback) => upstreamRuntime.recreateSession(model, rollback), - async () => catalogLoras(await loadHostModelCatalog(options.env, options.fetch)), + async () => { + loraModels = await loadHostModelCatalog(options.env, options.fetch) + return catalogLoras(loraModels) + }, async (mode, model) => { - const entry = (catalogBaseline.models as Record)[ - 'diffusion:' + model.split(':')[0] - ] + const entry = loraModels.models['diffusion:' + model.split(':')[0]] if (entry?.kind !== 'diffusion' || entry.definition.modality !== mode) return const transformer = entry.definition.transformer as { repo?: string } | undefined if (repoId(transformer?.repo)) return mediaCheckpoints.checkpoint(transformer.repo).catch(() => undefined) }, + async (format) => { + if (format === 'safetensors') return installedMediaBases(loraModels, await diffusion.listModelFiles()) + const registry = registries.get(LOCAL_PROVIDER) as ModelRegistry + const rows = await registry.listChatModels() + const installed = await Promise.all( + rows.map(async ({ id, yml }) => { + const info = await stat(registry.resolvePaths(yml).modelPath).catch(() => undefined) + return info?.isFile() ? [{ model: id, mode: 'chat' as const }] : [] + }) + ) + return installed.flat() + }, attachmentMutations ) const llamacppRuntime = (provider: LlamacppProviderId) => diff --git a/src/drafters/lora-import.test.ts b/src/drafters/lora-import.test.ts new file mode 100644 index 00000000..16483b71 --- /dev/null +++ b/src/drafters/lora-import.test.ts @@ -0,0 +1,19 @@ +import { expect, it } from 'vitest' +import { installedMediaBases } from './lora-import.js' + +it('offers a diffusion base only when the quant and all required companions are present', () => { + const definition = { + id: 'frames', + modality: 'video', + transformer: { quants: [{ id: 'q4', filename: 'quants/base.gguf', bytes: 5 }] }, + vae: { repo: 'org/vae', filename: 'files/vae.bin', bytes: 3 }, + text_encoders: [{ field: 'llm_vision', repo: 'org/optional', filename: 'clip.gguf', bytes: 10 }], + } + const catalog = { models: { frames: { kind: 'diffusion', format: 'diffusion', variants: {}, definition } } } + const files = [ + { relativePath: 'frames/base.gguf', bytes: 5 }, + { relativePath: 'shared/org--vae/vae.bin', bytes: 3 }, + ] + expect(installedMediaBases(catalog, files)).toEqual([{ model: 'frames:q4', mode: 'video' }]) + expect(installedMediaBases(catalog, files.slice(0, 1))).toEqual([]) +}) diff --git a/src/drafters/lora-import.ts b/src/drafters/lora-import.ts new file mode 100644 index 00000000..1c145036 --- /dev/null +++ b/src/drafters/lora-import.ts @@ -0,0 +1,130 @@ +import { open } from 'node:fs/promises' +import { basename } from 'node:path' +import type { AtomicModelCatalog } from '../client/index.js' +import { AtomicCoreError } from '../contracts/index.js' +import { readGgufTensorSummaryChunked } from '../models/index.js' +import { repoId } from './catalog.js' +import { hasLoraTensors, type LoraMode } from './lora-catalog.js' + +export interface LoraImportModel { + mode: LoraMode + model: string +} + +interface MediaFile { + repo: string + filename: string + bytes: number + field?: string +} + +/** Use the transformer's quant and the required companions of the default generation workflow. */ +export function installedMediaBases( + catalog: Pick, + files: { relativePath: string; bytes: number }[] +): LoraImportModel[] { + const sizes = new Map(files.map((file) => [file.relativePath, file.bytes])) + const models: LoraImportModel[] = [] + for (const { kind, definition } of Object.values(catalog.models)) { + const { id, modality, vae, audio_vae, text_encoders } = definition + if (kind !== 'diffusion' || typeof id !== 'string' || (modality !== 'image' && modality !== 'video')) + continue + const transformer = definition.transformer as { quants?: (MediaFile & { id: string })[] } | undefined + const companions = [vae, audio_vae, ...(Array.isArray(text_encoders) ? text_encoders : [])].filter( + Boolean + ) as MediaFile[] + if ( + !companions.every( + (f) => + f.field === 'llm_vision' || + sizes.get('shared/' + f.repo.replaceAll('/', '--') + '/' + basename(f.filename)) === f.bytes + ) + ) + continue + for (const q of transformer?.quants ?? []) { + if (sizes.get(id + '/' + basename(q.filename)) === q.bytes) + models.push({ mode: modality, model: id + ':' + q.id }) + } + } + return models +} + +function baseRepo(value: unknown) { + if (typeof value !== 'string') return + const repo = value.replace(/^https:\/\/huggingface\.co\//i, '').replace(/\/$/, '') + return repoId(repo) ? repo : undefined +} + +const corrupt = () => + new AtomicCoreError('MODEL_FILE_CORRUPT', 'The file does not contain complete, supported LoRA weights.') + +export async function inspectAdapter(path: string, mode: LoraMode) { + const handle = await open(path, 'r') + try { + const { size } = await handle.stat() + const prefix = async (count: number) => { + const buffer = Buffer.alloc(Math.min(size, count)) + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0) + return buffer.subarray(0, bytesRead) + } + if (mode === 'chat') { + const info = await readGgufTensorSummaryChunked(prefix, { + fileSize: size, + chunkSize: 65536, + growth: 'doubling', + }) + if ( + info.metadata['general.type'] !== 'adapter' || + info.metadata['adapter.type'] !== 'lora' || + !info.tensorCount || + info.dataOffset >= size || + info.types.some( + (t) => + !t.bytes || + t.elements !== t.sizedElements || + (t.type === 0 && t.bytes < 4 * t.elements) || + (t.type === 1 && t.bytes < 2 * t.elements) + ) + ) + throw corrupt() + return baseRepo(info.metadata['general.base_model.0.repo_url']) + } + const first = await prefix(8) + if (first.length !== 8) throw corrupt() + const length = Number(first.readBigUInt64LE()) + if (length <= 0 || length > 8 * 1024 * 1024 || length + 8 >= size) throw corrupt() + const header = JSON.parse((await prefix(length + 8)).subarray(8).toString('utf8')) + if (!hasLoraTensors(header)) throw corrupt() + const tensors = Object.entries(header).filter(([key]) => key !== '__metadata__') + const ranges = tensors + .map(([, value]) => { + const tensor = value as { data_offsets?: unknown; shape?: unknown; dtype?: unknown } + const offsets = tensor?.data_offsets + if ( + !Array.isArray(tensor?.shape) || + !tensor.shape.every((dim) => Number.isSafeInteger(dim) && dim >= 0) || + typeof tensor.dtype !== 'string' || + !Array.isArray(offsets) || + offsets.length !== 2 || + !offsets.every(Number.isSafeInteger) || + offsets[0] < 0 || + offsets[1] < offsets[0] + ) + throw corrupt() + return offsets as [number, number] + }) + .sort((a, b) => a[0] - b[0] || a[1] - b[1]) + let end = 0 + for (const [start, next] of ranges) { + if (start !== end) throw corrupt() + end = next + } + if (end !== size - length - 8) throw corrupt() + return baseRepo(header.__metadata__?.['modelspec.base_model'] ?? header.__metadata__?.ss_sd_model_name) + } catch (e) { + if (e instanceof Error && 'code' in e) throw e + throw corrupt() + } finally { + await handle.close() + } +} diff --git a/src/drafters/lora-service.test.ts b/src/drafters/lora-service.test.ts index 93e6135a..57be798b 100644 --- a/src/drafters/lora-service.test.ts +++ b/src/drafters/lora-service.test.ts @@ -1,6 +1,6 @@ import { it, expect, vi } from 'vitest' import { createHash } from 'node:crypto' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { tmpdir } from 'node:os' import { buildGguf } from '../../test/helpers/gguf-builder.js' @@ -10,7 +10,10 @@ import type { LoraArtifact } from './lora-catalog.js' it('restores a failed reload, persists one binding per installation and clears it on removal', async () => { const root = await mkdtemp(join(tmpdir(), 'atomic-chat-lora-')) try { - const bytes = buildGguf({ metadata: { 'general.type': 'adapter', 'adapter.type': 'lora' }, tensors: [] }) + const bytes = buildGguf({ + metadata: { 'general.type': 'adapter', 'adapter.type': 'lora' }, + tensors: [{ name: 'q.weight.lora_a', dims: [4, 4], type: 1, bitsPerWeight: 16 }], + }) const row: LoraArtifact = { mode: 'chat', repo: 'author/adapter', @@ -46,7 +49,8 @@ it('restores a failed reload, persists one binding per installation and clears i async (model) => ({ target: model === 'B' ? 'other/base' : row.target, signature: model }), restart, async () => catalog, - async () => undefined + async () => undefined, + async () => [] ) const first = service() expect(await first.search('', undefined, false, 'Quant/Base-GGUF')).toMatchObject({ @@ -77,3 +81,89 @@ it('restores a failed reload, persists one binding per installation and clears i await rm(root, { recursive: true, force: true }) } }) + +it.each(['chat', 'image', 'video'] as const)( + 'imports %s weights without activating them and preserves the source', + async (mode) => { + const root = await mkdtemp(join(tmpdir(), 'atomic-import-')) + try { + const target = 'author/base' + const catalog = { + files: [], + families: new Map(), + familyRepos: new Map(), + sources: new Map(), + } + const downloader = new Downloader({ + dataFolder: root, + platform: 'darwin', + emit: () => {}, + fetch, + sleep: async () => {}, + }) + const restart = vi.fn() + const base = (model: string) => (model === 'one' ? target : 'author/other') + const make = () => + new LoraService( + root, + downloader, + fetch, + catalog, + async (model) => ({ signature: model, target: base(model) }), + restart, + async () => catalog, + async (_, model) => base(model), + async () => ['one', 'two'].map((model) => ({ model, mode })) + ) + const service = make() + const path = join(root, mode === 'chat' ? 'patch.gguf' : 'patch.safetensors') + const gguf = buildGguf({ + metadata: { + 'general.type': 'adapter', + 'adapter.type': 'lora', + 'general.base_model.0.repo_url': 'https://huggingface.co/' + target, + }, + tensors: [{ name: 'q.weight.lora_a', dims: [4, 4], type: 1, bitsPerWeight: 16 }], + }) + const header = Buffer.from( + JSON.stringify({ 'blk.lora_A.weight': { shape: [1, 1], dtype: 'F32', data_offsets: [0, 4] } }) + ) + const prefix = Buffer.alloc(8) + prefix.writeBigUInt64LE(BigInt(header.length)) + const bytes = mode === 'chat' ? gguf : Buffer.concat([prefix, header, Buffer.alloc(4)]) + await writeFile(path, bytes) + await expect(service.importFile(path, mode, 'missing')).rejects.toThrow('installed') + if (mode === 'chat') + await expect(service.importFile(path, mode, 'two')).rejects.toThrow('different base') + const [row, duplicate] = await Promise.all([ + service.importFile(path, mode, 'one'), + service.importFile(path, mode, 'one'), + ]) + expect(duplicate).toEqual(row) + expect(row).toMatchObject({ + source: 'local', + mode, + target, + sha256: createHash('sha256').update(bytes).digest('hex'), + }) + expect(await make().choices(mode, 'one')).toMatchObject({ adapterId: null, files: [row] }) + expect(restart).not.toHaveBeenCalled() + await expect(service.importFile(path, mode, 'two')).rejects.toThrow('different base') + await make().select(mode, 'one', row.sha256) + expect(await make().resolve(mode, 'one')).toContain(row.sha256) + await service.remove(row.sha256) + expect((await service.search('patch')).results).toEqual([]) + expect(await readFile(path)).toEqual(bytes) + await writeFile(path, bytes.subarray(0, bytes.length - 1)) + await expect(service.importFile(path, mode, 'one')).rejects.toThrow() + if (mode === 'chat') { + await writeFile(path, buildGguf({ metadata: { 'general.type': 'model' }, tensors: [] })) + await expect(service.importFile(path, mode, 'one')).rejects.toThrow() + } + await expect(service.importFile(join(root, 'missing.gguf'), mode, 'one')).rejects.toThrow() + expect((await service.list()).files).toEqual([]) + } finally { + await rm(root, { recursive: true, force: true }) + } + } +) diff --git a/src/drafters/lora-service.ts b/src/drafters/lora-service.ts index 61443097..8a0d4b9c 100644 --- a/src/drafters/lora-service.ts +++ b/src/drafters/lora-service.ts @@ -1,13 +1,14 @@ import { FifoLock } from '../runtime/shared/fifo-lock.js' -import { open, rm, stat } from 'node:fs/promises' -import { basename, join } from 'node:path' +import { copyFile, mkdir, realpath, rename, rm, stat } from 'node:fs/promises' +import { basename, extname, isAbsolute, join } from 'node:path' import { AtomicCoreError } from '../contracts/index.js' -import { sha256File, type Downloader } from '../downloads/index.js' -import { hfResolveUrl, readGgufMetadataFromFile } from '../models/index.js' +import { diskWriteErrToString, sha256File, type Downloader } from '../downloads/index.js' +import { hfResolveUrl } from '../models/index.js' +import { randomUUID, createHash } from 'node:crypto' +import { inspectAdapter, type LoraImportModel } from './lora-import.js' import { fileId } from './catalog.js' import { optionalJson, save } from './storage.js' import { - hasLoraTensors, discoverLoras, bundledLoras, type LoraArtifact, @@ -16,8 +17,15 @@ import { } from './lora-catalog.js' type Catalog = ReturnType +type InstalledLora = + | LoraArtifact + | (Omit & { + source: 'local' + repo?: never + installation?: string + }) interface Inventory { - files: LoraArtifact[] + files: InstalledLora[] selections: Record } interface Identity { @@ -29,30 +37,15 @@ export interface LoraLease { file: string release: () => void } -async function validateAdapter(path: string, mode: LoraMode) { - if (mode === 'chat') { - const { metadata } = await readGgufMetadataFromFile(path) - if (metadata['adapter.type'] === 'lora' && metadata['general.type'] === 'adapter') return - } else { - const handle = await open(path, 'r') - try { - const prefix = Buffer.alloc(8) - if ((await handle.read(prefix)).bytesRead === 8) { - const length = Number(prefix.readBigUInt64LE()) - if (length > 0 && length <= 8 * 1024 * 1024) { - const bytes = Buffer.alloc(length) - if ( - (await handle.read(bytes)).bytesRead === length && - hasLoraTensors(JSON.parse(bytes.toString('utf8'))) - ) - return - } - } - } finally { - await handle.close() - } - } - throw new AtomicCoreError('MODEL_FILE_CORRUPT', 'The file does not contain supported LoRA adapter weights.') +function installationKey(model: string, identity: Identity) { + return createHash('sha256') + .update(JSON.stringify([model, identity.signature])) + .digest('hex') +} +function matches(row: InstalledLora, mode: LoraMode, model: string, identity: Identity) { + if (row.mode !== mode) return false + if ('installation' in row && row.installation) return row.installation === installationKey(model, identity) + return row.target.toLowerCase() === identity.target?.toLowerCase() } export class LoraService { @@ -76,6 +69,7 @@ export class LoraService { private restart: (model: string, rollback: () => Promise) => Promise, private refresh: () => Promise, private mediaIdentity: (mode: LoraMode, model: string) => Promise, + readonly importModels: (format: 'gguf' | 'safetensors') => Promise, private mutations = new FifoLock() ) { this.remember(catalog.files) @@ -89,7 +83,7 @@ export class LoraService { private async state(): Promise { return (await optionalJson(this.index)) ?? { files: [], selections: {} } } - private path(row: LoraArtifact) { + private path(row: InstalledLora) { if (!fileId(row.sha256)) throw new AtomicCoreError('INVALID_ARGUMENT', 'Invalid LoRA file ID.') return row.mode === 'chat' ? join('loras', 'chat', row.sha256 + '.gguf') @@ -147,12 +141,16 @@ export class LoraService { partial = true } } - this.remember((await this.state()).files) + const installed = (await this.state()).files + this.remember(installed.filter((row): row is LoraArtifact => !('source' in row))) const words = q.toLowerCase().trim().split(/\s+/) const bundled = snapshot?.published.results ?? [] - const matchesQuery = (row: LoraArtifact) => + const matchesQuery = (row: InstalledLora) => words.every((w) => [row.repo, row.file, row.target, row.mode].join(' ').toLowerCase().includes(w)) const rows = [ + ...installed.filter( + (row) => 'source' in row && (!target || target.toLowerCase() === row.target.toLowerCase()) + ), ...bundled.filter( (r) => !target || target.toLowerCase() === repoKey || r.target.toLowerCase() === target.toLowerCase() ), @@ -160,7 +158,7 @@ export class LoraService { .filter((row) => !target || target.toLowerCase() === row.target.toLowerCase()) .sort((a, b) => Number(b.repo.toLowerCase() === repoKey) - Number(a.repo.toLowerCase() === repoKey)), ] - const unique = new Map() + const unique = new Map() for (const row of rows) if (matchesQuery(row) && !unique.has(row.sha256)) unique.set(row.sha256, row) return { partial, target, results: [...unique.values()] } } @@ -174,6 +172,16 @@ export class LoraService { return task } private async download(row: LoraArtifact) { + const existing = (await this.state()).files.find((file) => file.sha256 === row.sha256) + if (existing && 'source' in existing) { + if (existing.mode !== row.mode || existing.target.toLowerCase() !== row.target.toLowerCase()) + throw new AtomicCoreError( + 'MODEL_INCOMPATIBLE', + 'These weights are installed for a different base model.' + ) + await this.verify(existing) + return + } const relative = this.path(row) await this.downloader.download( 'lora:' + row.sha256, @@ -190,13 +198,88 @@ export class LoraService { ) const path = join(this.root, relative) await this.verify(row) - await validateAdapter(path, row.mode) + await inspectAdapter(path, row.mode) await this.mutations.run(async () => { const state = await this.state() - state.files = state.files.filter((r) => r.sha256 !== row.sha256).concat(row) + const existing = state.files.find((r) => r.sha256 === row.sha256) + if (existing) { + if (existing.mode !== row.mode || existing.target.toLowerCase() !== row.target.toLowerCase()) + throw new AtomicCoreError( + 'MODEL_INCOMPATIBLE', + 'These weights are installed for a different base model.' + ) + return + } + state.files.push(row) await save(this.index, state) }) } + async importFile(path: string, mode: LoraMode, model: string) { + const format = mode === 'chat' ? 'gguf' : 'safetensors' + if (!isAbsolute(path) || extname(path).toLowerCase() !== '.' + format || !(await stat(path)).isFile()) + throw new AtomicCoreError('INVALID_ARGUMENT', 'Choose a local .' + format + ' file.') + const models = await this.importModels(format) + if (!models.some((m) => m.mode === mode && m.model === model)) + throw new AtomicCoreError('INVALID_ARGUMENT', 'Choose an installed base model.') + const dir = join(this.root, mode === 'chat' ? 'loras/chat' : 'diffusion/loras') + await mkdir(dir, { recursive: true }) + const staged = join(dir, '.' + randomUUID() + '.tmp') + try { + await copyFile(path, staged).catch((error: unknown) => { + throw new AtomicCoreError('IO_ERROR', diskWriteErrToString(error, 0, 0)) + }) + const base = await inspectAdapter(staged, mode) + const sha256 = await sha256File(staged) + const size = (await stat(staged)).size + return await this.mutations.run(async () => { + const ctx = await this.identity(mode, model) + if (ctx.target && base && ctx.target.toLowerCase() !== base.toLowerCase()) + throw new AtomicCoreError( + 'MODEL_INCOMPATIBLE', + 'This adapter declares a different base model: ' + base + ) + const state = await this.state() + const previous = state.files.find((row) => row.sha256 === sha256) + if (previous) { + if (!matches(previous, mode, model, ctx)) + throw new AtomicCoreError( + 'MODEL_INCOMPATIBLE', + 'These weights are installed for a different base model.' + ) + await this.verify(previous) + return previous + } + if (this.transfers.has(sha256)) + throw new AtomicCoreError('JOB_BUSY', 'These weights are being downloaded.') + const row: InstalledLora = { + source: 'local', + sha256, + file: basename(path), + target: ctx.target ?? base ?? model, + mode, + size, + ...(!ctx.target ? { installation: installationKey(model, ctx) } : {}), + } + const dest = join(this.root, this.path(row)) + if ((await realpath(path)) === (await realpath(dest).catch(() => undefined))) + throw new AtomicCoreError( + 'INVALID_ARGUMENT', + 'Choose a source file outside the managed adapter store.' + ) + await rename(staged, dest) + try { + state.files.push(row) + await save(this.index, state) + } catch (e) { + await rm(dest, { force: true }) + throw e + } + return row + }) + } finally { + await rm(staged, { force: true }) + } + } cancel(id: string) { return this.downloader.cancel('lora:' + id) } @@ -220,10 +303,9 @@ export class LoraService { async choices(mode: LoraMode, model: string) { const state = await this.state() const binding = state.selections[mode + ':' + model] - const { target, source, signature } = await this.identity(mode, model) - const files = state.files.filter( - (row) => row.mode === mode && row.target.toLowerCase() === target?.toLowerCase() - ) + const ctx = await this.identity(mode, model) + const { target, source, signature } = ctx + const files = state.files.filter((row) => matches(row, mode, model, ctx)) return { target, ...(source ? { source } : {}), @@ -232,7 +314,7 @@ export class LoraService { files, } } - private async verify(row: LoraArtifact) { + private async verify(row: InstalledLora) { const path = join(this.root, this.path(row)) const info = await stat(path) const signature = [info.size, info.mtimeMs, info.ctimeMs].join(':') @@ -249,10 +331,7 @@ export class LoraService { if (!binding) return const ctx = await this.identity(mode, model, binding) if (ctx.signature !== binding.signature) return - const row = state.files.find( - (r) => - r.sha256 === binding.id && r.mode === mode && r.target.toLowerCase() === ctx.target?.toLowerCase() - ) + const row = state.files.find((r) => r.sha256 === binding.id && matches(r, mode, model, ctx)) if (!row) throw new AtomicCoreError('MODEL_INCOMPATIBLE', 'The selected adapter no longer matches this model.') return this.verify(row) @@ -279,14 +358,16 @@ export class LoraService { const key = mode + ':' + model const ctx = await this.identity(mode, model, state.selections[key]) if (id !== null) { - const row = state.files.find( - (r) => r.sha256 === id && r.mode === mode && r.target.toLowerCase() === ctx.target?.toLowerCase() - ) + const row = state.files.find((r) => r.sha256 === id && matches(r, mode, model, ctx)) if (!row) throw new AtomicCoreError('INVALID_ARGUMENT', 'Choose an installed adapter for this checkpoint.') await this.verify(row) } - await this.change(state, key, id ? { id, signature: ctx.signature, target: ctx.target! } : undefined) + await this.change( + state, + key, + id ? { id, signature: ctx.signature, target: ctx.target ?? model } : undefined + ) }) } private async change(state: Inventory, key: string, next: Inventory['selections'][string] | undefined) { diff --git a/src/server/control/routes/loras.test.ts b/src/server/control/routes/loras.test.ts index a948d351..5f6f426b 100644 --- a/src/server/control/routes/loras.test.ts +++ b/src/server/control/routes/loras.test.ts @@ -5,6 +5,8 @@ it('round-trips a nested model selection and rejects invalid modes and IDs', asy const server = await startControlHarness({ loras: { list: vi.fn(), + importFile: vi.fn(), + importModels: vi.fn(), search: vi.fn(), install: vi.fn(), remove: vi.fn(), diff --git a/src/server/control/routes/loras.ts b/src/server/control/routes/loras.ts index 3b333dc9..af6b7902 100644 --- a/src/server/control/routes/loras.ts +++ b/src/server/control/routes/loras.ts @@ -7,6 +7,18 @@ export function registerLoraRoutes(router: Router, deps: ControlServerDeps, { p const service = deps.loras if (!service) return router.get(p('/loras'), async (_req, res) => sendJson(res, 200, await service.list())) + router.get(p('/loras/import-models'), async (req, res) => { + const format = queryOf(req).get('format') + if (format !== 'gguf' && format !== 'safetensors') + throw new AtomicCoreError('INVALID_ARGUMENT', 'Choose a supported adapter format.') + sendJson(res, 200, await service.importModels(format)) + }) + router.post(p('/loras/import'), async (req, res) => { + const body = await readJsonBody<{ path?: unknown; mode?: unknown; model?: unknown }>(req) + if (!isLoraMode(body?.mode) || typeof body.path !== 'string' || typeof body.model !== 'string') + throw new AtomicCoreError('INVALID_ARGUMENT', 'Provide a local file, mode and installed model ID.') + sendJson(res, 200, await service.importFile(body.path, body.mode, body.model)) + }) router.get(p('/loras/search'), async (req, res) => { const params = queryOf(req) const target = params.get('target') ?? undefined diff --git a/src/server/control/types.ts b/src/server/control/types.ts index 89fcb858..05c0b87e 100644 --- a/src/server/control/types.ts +++ b/src/server/control/types.ts @@ -498,7 +498,10 @@ export interface ModelCompatibilityControl { } export interface ControlServerDeps { - loras?: Pick + loras?: Pick< + LoraService, + 'importModels' | 'importFile' | 'list' | 'search' | 'choices' | 'select' | 'install' | 'cancel' | 'remove' + > drafters?: Pick< DrafterService, 'list' | 'search' | 'variants' | 'install' | 'cancel' | 'remove' | 'selection' | 'choices' | 'select' diff --git a/test/app-e2e/README.md b/test/app-e2e/README.md index 112cdc8f..147ecf28 100644 --- a/test/app-e2e/README.md +++ b/test/app-e2e/README.md @@ -62,3 +62,7 @@ For FastFlowLM on Ubuntu, replay the Linux preparation request through the deskt ## FastFlowLM prepared operation, chat and maintenance With the two staging binaries and the same Qwen3 fixture, dismiss and reopen preparation before and after consent. Cancel before a launcher claims the step and check that a new operation can start. Once claimed, reconnect without starting a second installer. Verify the displayed identity after activation. After installation, send a streaming request, stop it, send an ordinary request, then replace and remove the variant. Restart the owner while the maintenance guard is held and verify that the model cannot be loaded until installer recovery completes. Record Windows and Linux outcomes separately. + +## Local LoRA import + +During desktop release verification, open Hub → LoRA from the settings of an installed upstream chat model. Pick a GGUF adapter, confirm the preselected installation, and verify that the adapter appears in its choices while the existing session continues. Select it explicitly and send a message. Repeat with a diffusion safetensors adapter for an installed image or video base. Restart the app, remove the adapter from Downloads, and verify that the original file is still present. diff --git a/test/e2e/lora-import.test.ts b/test/e2e/lora-import.test.ts new file mode 100644 index 00000000..9f9b7d7d --- /dev/null +++ b/test/e2e/lora-import.test.ts @@ -0,0 +1,55 @@ +import { once } from 'node:events' +import { it, expect } from 'vitest' +import type { ChildProcess } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { BIN, control, startDaemon, writeModel } from '../helpers/compiled-core.js' +import { buildGguf } from '../helpers/gguf-builder.js' + +it.skipIf(!existsSync(BIN))( + 'imports an adapter for an installed GGUF through the desktop control contract', + async () => { + const root = await mkdtemp(join(tmpdir(), 'atomic-lora-contract-')) + const daemons: ChildProcess[] = [] + try { + await writeModel(root, 'personal') + await writeFile( + join(root, 'llamacpp/models/personal/model.gguf'), + buildGguf({ metadata: { 'general.type': 'model' }, tensors: [] }) + ) + const bytes = buildGguf({ + metadata: { 'general.type': 'adapter', 'adapter.type': 'lora' }, + tensors: [{ name: 'q.weight.lora_a', dims: [4, 4], type: 1, bitsPerWeight: 16 }], + }) + const path = join(root, 'My adapter.gguf') + await writeFile(path, bytes) + const { ready } = await startDaemon(root, daemons) + const models = await control(root, ready, '/loras/import-models?format=gguf') + expect(await models.json()).toContainEqual({ mode: 'chat', model: 'personal' }) + const response = await control(root, ready, '/loras/import', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ path, mode: 'chat', model: 'personal' }), + }) + expect(response.status, await response.clone().text()).toBe(200) + const row = (await response.json()) as { sha256: string } + const choices = await control(root, ready, '/loras/choices/chat/personal') + expect(await choices.json()).toMatchObject({ + adapterId: null, + files: [{ file: 'My adapter.gguf', source: 'local', sha256: row.sha256 }], + }) + expect((await control(root, ready, '/loras/' + row.sha256, { method: 'DELETE' })).status).toBe(200) + expect(await readFile(path)).toEqual(bytes) + } finally { + for (const daemon of daemons) { + if (daemon.exitCode !== null || daemon.signalCode) continue + const stopped = once(daemon, 'exit') + daemon.kill() + await stopped + } + await rm(root, { recursive: true, force: true }) + } + } +) From 95ab276f82e9994e59c7110441a5536fca01a6d2 Mon Sep 17 00:00:00 2001 From: Misha Skvortsov Date: Tue, 1 Dec 2026 13:22:37 +0300 Subject: [PATCH 2/2] Cover installed base discovery through the control listener --- src/core/create.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/core/create.test.ts b/src/core/create.test.ts index 20e82ec7..6330e113 100644 --- a/src/core/create.test.ts +++ b/src/core/create.test.ts @@ -1487,6 +1487,21 @@ describe('LoRA checkpoint discovery through the owner', () => { expect(await cached.json()).toMatchObject({ target, results: result.results }) }) + it('offers only installed chat and media bases to the LoRA import dialog', async () => { + await data.writeModel('my-chat') + await data.writeModel('embed', { embedding: true }) + const incomplete = await data.writeModel('partial') + await rm(join(incomplete, 'model.gguf')) + const core = await createCore() + const bases = (format: string) => + fetch(core.control.url + '/atomic/v1/loras/import-models?format=' + format, { + headers: { authorization: 'Bearer ' + core.controlToken }, + }) + expect(await (await bases('gguf')).json()).toEqual([{ model: 'my-chat', mode: 'chat' }]) + expect(await (await bases('safetensors')).json()).toEqual([]) + expect((await bases('zip')).status).toBe(400) + }) + it('derives the base of a quantized media model from its declared provenance and respects the mode', async () => { const core = await createCore({ fetch: async () => Response.json({ tags: ['base_model:quantized:black-forest-labs/FLUX.1-schnell'] }),