Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: LM Studio model deletion (lms CLI has no rm command)

Adam Eivy753dbfd880c0
diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.js
index 101cdbc691..c013e5bc3e 100644
--- a/server/services/lmStudioManager.js
+++ b/server/services/lmStudioManager.js
@@ -6,9 +6,9 @@
*/
import { homedir } from 'os'
-import { join, basename } from 'path'
+import { join, basename, resolve, relative, isAbsolute, sep } from 'path'
import { existsSync } from 'fs'
-import { readdir, stat, mkdir, copyFile, link } from 'fs/promises'
+import { readdir, stat, mkdir, copyFile, link, rm, rmdir } from 'fs/promises'
import { cosEvents } from './cosEvents.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import {
@@ -539,6 +539,84 @@ async function resolveLocalModel(modelId) {
}
}
+/**
+ * Resolve which on-disk folder(s) a delete request maps to. Unlike
+ * resolveLocalModel (a best-effort fuzzy first-match for READS), deletion is
+ * destructive (`rm -rf`), so this is deliberately stricter: it only ever returns
+ * concrete `<publisher>/<repo>` folders (LM Studio's invariant layout), rejects
+ * `.`/`..` traversal segments, and returns ALL normalized-scan matches so an
+ * ambiguous id (e.g. a `-GGUF` and a `-MLX-*` variant that normalize to the same
+ * key) can refuse instead of guessing the wrong one.
+ * @returns {Promise<string[]|null>} matched dirs, or null for an invalid id
+ */
+async function findDeletableModelDirs(modelsDir, modelId) {
+ const segments = String(modelId || '').split('/').map((s) => s.trim()).filter(Boolean)
+ if (segments.some((s) => s === '.' || s === '..')) return null
+ // Exact `<publisher>/<repo>` match takes precedence over the fuzzy scan.
+ if (segments.length === 2) {
+ const direct = join(modelsDir, segments[0], segments[1])
+ if (await dirExists(direct)) return [direct]
+ }
+ const wanted = normalizeRepoKey(modelId)
+ if (!wanted) return []
+ const matches = []
+ const publishers = await readdir(modelsDir).catch(() => [])
+ for (const publisher of publishers) {
+ const publisherDir = join(modelsDir, publisher)
+ if (!(await dirExists(publisherDir))) continue
+ const repos = await readdir(publisherDir).catch(() => [])
+ for (const name of repos) {
+ const repoDir = join(publisherDir, name)
+ if (normalizeRepoKey(name) === wanted && await dirExists(repoDir)) matches.push(repoDir)
+ }
+ }
+ return matches
+}
+
+/** True only when `dir` is a `<publisher>/<repo>` folder strictly under modelsDir. */
+function isModelLeafDir(modelsDir, dir) {
+ const rel = relative(resolve(modelsDir), resolve(dir))
+ if (!rel || rel.startsWith('..') || isAbsolute(rel)) return false
+ return rel.split(sep).length === 2
+}
+
+/**
+ * Delete an installed LM Studio model. The `lms` CLI has no remove command, and
+ * LM Studio's REST API exposes no delete — so we remove the model's on-disk
+ * `<publisher>/<repo>/` folder directly and prune the publisher dir if empty.
+ * Best-effort unloads the model first so the running app isn't left serving
+ * files that no longer exist.
+ * @returns {Promise<{ success: boolean, modelId: string, error?: string }>}
+ */
+async function deleteModel(modelId) {
+ const modelsDir = await getModelsDir()
+ const matches = await findDeletableModelDirs(modelsDir, modelId)
+ if (matches === null) return { success: false, error: `Invalid model id "${modelId}".`, modelId }
+ if (matches.length === 0) {
+ return { success: false, error: `Model files not found on disk for "${modelId}".`, modelId }
+ }
+ if (matches.length > 1) {
+ return { success: false, error: `Ambiguous model id "${modelId}" matches ${matches.length} folders — delete by exact "publisher/repo".`, modelId }
+ }
+ const dir = matches[0]
+ // Defense-in-depth: never rm the models root, a publisher dir, or anything
+ // outside modelsDir — only a concrete `<publisher>/<repo>` leaf.
+ if (!isModelLeafDir(modelsDir, dir)) {
+ return { success: false, error: `Refusing to delete "${dir}" — not a model folder under ${modelsDir}.`, modelId }
+ }
+ // Unload first if the app is up and holding it (no-op/harmless otherwise).
+ if (await checkLMStudioAvailable()) await unloadModel(modelId).catch(() => {})
+ const removed = await rm(dir, { recursive: true, force: true })
+ .then(() => ({ ok: true })).catch((err) => ({ _err: err.message }))
+ resetCache() // disk may have changed even on a partial failure — re-list fresh
+ if (removed._err) return { success: false, error: removed._err, modelId }
+ // Prune the now-empty publisher dir (rmdir fails harmlessly if not empty).
+ await rmdir(join(dir, '..')).catch(() => {})
+ console.log(`🗑️ LM Studio deleted: ${modelId} (${dir})`)
+ cosEvents.emit('lmstudio:modelDeleted', { modelId })
+ return { success: true, modelId }
+}
+
/**
* Place a local GGUF into LM Studio's model tree (no download). LM Studio indexes
* loose GGUF files dropped under `<publisher>/<repo>/` on its next scan. In `link`
@@ -598,5 +676,6 @@ export {
getLastListError,
resolveLocalModel,
importModelFromGguf,
+ deleteModel,
DEFAULT_CONFIG
}
diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.js
index 4a2f349b2e..ad393e82f1 100644
--- a/server/services/lmStudioManager.test.js
+++ b/server/services/lmStudioManager.test.js
@@ -5,17 +5,25 @@ import fs from 'fs';
let tempDir;
let originalModelsDir;
+let originalUrl;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'portos-lms-models-'));
originalModelsDir = process.env.LM_STUDIO_MODELS_DIR;
process.env.LM_STUDIO_MODELS_DIR = tempDir;
+ // Point LM Studio at a closed port so deleteModel's best-effort
+ // availability probe + unload fail fast (ECONNREFUSED) and the tests stay
+ // network-free and deterministic regardless of whether LM Studio is running.
+ originalUrl = process.env.LM_STUDIO_URL;
+ process.env.LM_STUDIO_URL = 'http://127.0.0.1:1';
vi.resetModules();
});
afterEach(() => {
if (originalModelsDir === undefined) delete process.env.LM_STUDIO_MODELS_DIR;
else process.env.LM_STUDIO_MODELS_DIR = originalModelsDir;
+ if (originalUrl === undefined) delete process.env.LM_STUDIO_URL;
+ else process.env.LM_STUDIO_URL = originalUrl;
fs.rmSync(tempDir, { recursive: true, force: true });
});
@@ -55,3 +63,86 @@ describe('lmStudioManager local model resolution', () => {
});
});
});
+
+describe('lmStudioManager deleteModel', () => {
+ it('removes the model folder on disk and prunes the empty publisher dir', async () => {
+ writeFile('nomic-ai/nomic-embed-text-v1.5-GGUF/model-Q4_K_M.gguf');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ const result = await deleteModel('nomic-ai/nomic-embed-text-v1.5-GGUF');
+
+ expect(result).toMatchObject({ success: true, modelId: 'nomic-ai/nomic-embed-text-v1.5-GGUF' });
+ expect(fs.existsSync(path.join(tempDir, 'nomic-ai', 'nomic-embed-text-v1.5-GGUF'))).toBe(false);
+ // Publisher dir had only the one repo, so it's pruned too.
+ expect(fs.existsSync(path.join(tempDir, 'nomic-ai'))).toBe(false);
+ });
+
+ it('resolves the on-disk folder via the normalized repo scan when given a differing API id', async () => {
+ writeFile('lmstudio-community/gpt-oss-20b-GGUF/gpt-oss-20b-MXFP4.gguf');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ const result = await deleteModel('openai/gpt-oss-20b');
+
+ expect(result.success).toBe(true);
+ expect(fs.existsSync(path.join(tempDir, 'lmstudio-community', 'gpt-oss-20b-GGUF'))).toBe(false);
+ });
+
+ it('keeps the publisher dir when other repos remain', async () => {
+ writeFile('nomic-ai/nomic-embed-text-v1.5-GGUF/model-Q4_K_M.gguf');
+ writeFile('nomic-ai/nomic-embed-text-v2-GGUF/model-Q4_K_M.gguf');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ await deleteModel('nomic-ai/nomic-embed-text-v1.5-GGUF');
+
+ expect(fs.existsSync(path.join(tempDir, 'nomic-ai', 'nomic-embed-text-v1.5-GGUF'))).toBe(false);
+ expect(fs.existsSync(path.join(tempDir, 'nomic-ai', 'nomic-embed-text-v2-GGUF'))).toBe(true);
+ });
+
+ it('returns success:false when the model is not found on disk', async () => {
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ const result = await deleteModel('nonexistent/model');
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/not found/i);
+ });
+
+ it('refuses traversal / root ids and deletes nothing', async () => {
+ writeFile('nomic-ai/nomic-embed-text-v1.5-GGUF/model-Q4_K_M.gguf');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ for (const badId of ['.', '/', '..', 'nomic-ai/..', '../../etc']) {
+ const result = await deleteModel(badId);
+ expect(result.success).toBe(false);
+ }
+ // The real model and the models root are untouched.
+ expect(fs.existsSync(path.join(tempDir, 'nomic-ai', 'nomic-embed-text-v1.5-GGUF'))).toBe(true);
+ expect(fs.existsSync(tempDir)).toBe(true);
+ });
+
+ it('refuses an ambiguous id that matches multiple variants and deletes neither', async () => {
+ // GGUF and MLX variants both normalize to the same repo key (qwen3-4b).
+ writeFile('lmstudio-community/qwen3-4b-GGUF/qwen3-4b-Q4_K_M.gguf');
+ writeFile('lmstudio-community/qwen3-4b-MLX-4bit/model.safetensors');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ const result = await deleteModel('qwen/qwen3-4b'); // non-exact id → fuzzy scan
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/ambiguous/i);
+ expect(fs.existsSync(path.join(tempDir, 'lmstudio-community', 'qwen3-4b-GGUF'))).toBe(true);
+ expect(fs.existsSync(path.join(tempDir, 'lmstudio-community', 'qwen3-4b-MLX-4bit'))).toBe(true);
+ });
+
+ it('still deletes by exact publisher/repo even when an ambiguous sibling exists', async () => {
+ writeFile('lmstudio-community/qwen3-4b-GGUF/qwen3-4b-Q4_K_M.gguf');
+ writeFile('lmstudio-community/qwen3-4b-MLX-4bit/model.safetensors');
+ const { deleteModel } = await import('./lmStudioManager.js');
+
+ const result = await deleteModel('lmstudio-community/qwen3-4b-GGUF'); // exact match wins
+
+ expect(result.success).toBe(true);
+ expect(fs.existsSync(path.join(tempDir, 'lmstudio-community', 'qwen3-4b-GGUF'))).toBe(false);
+ expect(fs.existsSync(path.join(tempDir, 'lmstudio-community', 'qwen3-4b-MLX-4bit'))).toBe(true);
+ });
+});
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index ef32c2f091..c7b7e87688 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -361,15 +361,9 @@ export async function deleteModel(backend, modelId) {
if (backend === 'ollama') {
return ollamaManager.deleteModel(modelId)
}
- // LM Studio has no delete in its REST API — use the `lms` CLI if present.
- if (await commandExists('lms', ['version'])) {
- const r = await execFileAsync('lms', ['rm', modelId, '-y'], { timeout: 30_000 })
- .then(() => ({ ok: true })).catch((err) => ({ _err: err.stderr || err.message }))
- if (r._err) return { success: false, error: r._err, modelId }
- lmStudioManager.resetCache()
- return { success: true, modelId }
- }
- return { success: false, error: 'Deleting LM Studio models requires the `lms` CLI. Remove it from the LM Studio app instead.', modelId }
+ // LM Studio has no delete in its REST API and the `lms` CLI has no `rm`
+ // command — deleteModel removes the model's on-disk folder directly.
+ return lmStudioManager.deleteModel(modelId)
}
// ---- switch / migrate --------------------------------------------------------