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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: reclaim duplicate Pinokio model weights with verified hardlinks (#6344)
[._.]/ Adam Eivy2053db0ac1d4
diff --git a/client/src/components/models/DuplicateModelWeights.jsx b/client/src/components/models/DuplicateModelWeights.jsxnew file mode 100644index 0000000000..be00faf2d3--- /dev/null+++ b/client/src/components/models/DuplicateModelWeights.jsx@@ -0,0 +1,63 @@+import { useRef, useState } from 'react';+import { rectifyModelDuplicates } from '../../services/apiSystem.js';+import { formatBytes } from '../../utils/formatters.js';+import toast from '../ui/Toast';++export default function DuplicateModelWeights({ duplicates, locked, onRefresh }) {+ const [pending, setPending] = useState(null);+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const [completed, setCompleted] = useState(new Set());+ if (!duplicates) return null;+ if (duplicates.error) return <p role="status" className="text-sm text-port-warning">{duplicates.error}. Refresh to retry.</p>;+ const items = duplicates.items || [];+ if (!items.length) return null;+ const eligible = items.filter((item) => item.canLink && !completed.has(item.targetPath));+ const link = async () => {+ if (busyRef.current || !pending) return;+ busyRef.current = true;+ setBusy(true);+ const pairs = pending.map(({ sourcePath, targetPath }) => ({ sourcePath, targetPath }));+ const outcome = await rectifyModelDuplicates({ pairs, mode: 'hardlink' }, { silent: true })+ .then((value) => ({ value }), (error) => ({ error }));+ setPending(null);+ if (outcome.error) toast.error(outcome.error.message || 'Could not link model weights');+ else {+ setCompleted((previous) => new Set([...previous, ...pairs.map((pair) => pair.targetPath)]));+ toast.success(`Linked model weights · ${formatBytes(outcome.value.reclaimedBytes)} reclaimed`);+ }+ // Refresh even on failure: a batch may have completed earlier replacements.+ await onRefresh();+ busyRef.current = false;+ setBusy(false);+ };+ return (+ <section className="rounded-2xl border border-port-border bg-port-card p-4 space-y-3">+ <h3 className="font-semibold text-white">Duplicate Model Weights</h3>+ <p className="text-sm text-gray-400">+ {items.length} duplicate weight files found in Pinokio · {formatBytes(eligible.reduce((sum, item) => sum + item.reclaimableBytes, 0))} potentially reclaimable+ </p>+ <button type="button" disabled={locked || busy || !eligible.length} onClick={() => setPending(eligible)}+ className="rounded-lg border border-port-border px-3 py-2 text-sm disabled:opacity-50">Link All</button>+ {items.map((item) => (+ <div key={item.targetPath} className="rounded-lg bg-port-bg/40 p-3 space-y-1">+ <p className="text-sm font-medium">{item.model} · {formatBytes(item.sizeBytes)}</p>+ <p className="break-all text-xs text-gray-400">Keep: {item.sourcePath}</p>+ <p className="break-all text-xs text-gray-400">Link: {item.targetPath}</p>+ {item.alreadyLinked || completed.has(item.targetPath) ? <p className="text-xs text-gray-400">Already sharing storage</p> : (+ <button type="button" disabled={locked || busy || !item.canLink} onClick={() => setPending([item])}+ className="rounded-lg border border-port-border px-3 py-2 text-sm disabled:opacity-50">+ Link & Reclaim {formatBytes(item.reclaimableBytes)}+ </button>+ )}+ {!item.alreadyLinked && !item.canLink && <p className="text-xs text-gray-400">Cannot reclaim with a single hardlink: different filesystem, file permissions, or additional file aliases.</p>}+ </div>+ ))}+ {pending && <div role="alert" className="rounded-lg border border-port-border p-3 space-y-2">+ <p className="text-sm">Link {pending.length} weight files? Both paths will share the same physical data. In-place edits affect both applications; use this only for finished, immutable weights. Both paths remain readable. Filesystem snapshots or clones may reduce actual space recovered.</p>+ <button type="button" onClick={link} disabled={busy || locked} className="rounded-lg bg-port-accent px-3 py-2 text-sm disabled:opacity-50">{busy ? 'Linking…' : 'Confirm linking'}</button>+ <button type="button" onClick={() => setPending(null)} disabled={busy} className="px-3 py-2 text-sm">Cancel</button>+ </div>}+ </section>+ );+}diff --git a/client/src/components/models/ModelsPanel.jsx b/client/src/components/models/ModelsPanel.jsxindex ce516b2bb5..1d20415bae 100644--- a/client/src/components/models/ModelsPanel.jsx+++ b/client/src/components/models/ModelsPanel.jsx@@ -1,6 +1,7 @@import { useMemo, useState } from 'react';import { AlertTriangle, Box, Download, HardDrive, RefreshCw } from 'lucide-react';import { Link } from 'react-router';+import DuplicateModelWeights from './DuplicateModelWeights.jsx';import MemoryManagement from '../settings/MemoryManagement.jsx';import Banner from '../ui/Banner.jsx';import CleanupControl from '../system-resources/CleanupControl.jsx';@@ -61,6 +62,8 @@ export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {<div className="space-y-4"><MemoryManagement onLoadedModelsChange={setResidency} />+ <DuplicateModelWeights key={report?.generatedAt} duplicates={report?.modelDuplicates} locked={loading || cleanup.locked} onRefresh={onRunReport} />+{!report ? <InventoryEmpty loading={loading} onRun={onRunReport} /> : (<section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5"><div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">diff --git a/client/src/components/models/ModelsPanel.test.jsx b/client/src/components/models/ModelsPanel.test.jsxindex 334c6af59c..e0c1324092 100644--- a/client/src/components/models/ModelsPanel.test.jsx+++ b/client/src/components/models/ModelsPanel.test.jsx@@ -1,7 +1,10 @@import { describe, expect, it, vi } from 'vitest';-import { act, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';+vi.mock('../../services/apiSystem.js', () => ({ rectifyModelDuplicates: vi.fn(async () => ({ reclaimedBytes: 1024 })) }));+const { rectifyModelDuplicates } = await import('../../services/apiSystem.js');+const memory = vi.hoisted(() => ({ publish: null }));vi.mock('../settings/MemoryManagement.jsx', () => ({default: ({ onLoadedModelsChange }) => {@@ -97,3 +100,19 @@ describe('ModelsPanel live residency', () => {expect(warning.textContent).not.toContain('lmstudio-backend');});});++it('confirms duplicate linking and refreshes the inventory', async () => {+ const refresh = vi.fn();+ render(<MemoryRouter><ModelsPanel report={{ ...report, modelDuplicates: {+ items: [{ model: 'Example weights', sourcePath: '/models/example.safetensors', targetPath: '/pinokio/example.safetensors', canLink: true, sizeBytes: 1024, reclaimableBytes: 1024 }],+ } }} loading={false} onRunReport={refresh} cleanup={cleanup} /></MemoryRouter>);+ expect(screen.getByText('Duplicate Model Weights')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Link All' }));+ expect(rectifyModelDuplicates).not.toHaveBeenCalled();+ expect(screen.getByText(/In-place edits affect both applications/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Confirm linking' }));+ await waitFor(() => expect(refresh).toHaveBeenCalledOnce());+ expect(rectifyModelDuplicates).toHaveBeenCalledWith({ mode: 'hardlink', pairs: [{+ sourcePath: '/models/example.safetensors', targetPath: '/pinokio/example.safetensors',+ }] }, { silent: true });+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex b8d12ad11f..c07a0570a4 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -1,6 +1,10 @@import { request, API_BASE, throwApiError } from './apiCore.js';import { downloadBlob } from '../lib/downloadBlob.js';+export const rectifyModelDuplicates = (payload, options = {}) => request('/system-resources/duplicates/rectify', {+ method: 'POST', body: JSON.stringify(payload), ...options,+});+// Alertsexport const getAlertsSummary = (options) => request('/alerts/summary', options);diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex e087923f83..ea013c4a12 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -15545,6 +15545,14 @@"server/routes/dataSync.js"]},+ {+ "method": "POST",+ "path": "/api/system-resources/duplicates/rectify",+ "mountPath": "/api/system-resources",+ "sources": [+ "server/routes/systemResources.js"+ ]+ },{"method": "POST","path": "/api/system-resources/report",@@ -17780,8 +17788,8 @@],"stats": {"mounts": 150,- "operations": 2202,- "declarations": 2210,+ "operations": 2203,+ "declarations": 2211,"sourceFiles": 233}}diff --git a/server/routes/systemResources.js b/server/routes/systemResources.jsindex 599dabb3a9..7d04d71c1f 100644--- a/server/routes/systemResources.js+++ b/server/routes/systemResources.js@@ -14,7 +14,21 @@ import { onClientDisconnect } from '../lib/sseDownload.js';import { stopRun } from '../services/runner.js';import { getSystemResourceReport, triageSystemResources } from '../services/systemResources.js';+import { rectifyModelDuplicates } from '../services/modelDeduplication.js';+const router = Router();+const duplicatePairsSchema = z.object({+ pairs: z.array(z.object({+ sourcePath: z.string().min(1).max(4096),+ targetPath: z.string().min(1).max(4096),+ }).strict()).min(1).max(200),+ mode: z.literal('hardlink').default('hardlink'),+}).strict();++router.post('/duplicates/rectify', asyncHandler(async (req, res) => {+ const { pairs } = validateRequest(duplicatePairsSchema, req.body);+ res.json(await rectifyModelDuplicates(pairs));+}));const emptyBodySchema = z.object({}).strict();const blankToUndefined = (value) => {diff --git a/server/routes/systemResources.test.js b/server/routes/systemResources.test.jsindex 2f99bf2c9e..167069ed8d 100644--- a/server/routes/systemResources.test.js+++ b/server/routes/systemResources.test.js@@ -3,6 +3,9 @@ import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';+vi.mock('../services/modelDeduplication.js', () => ({ rectifyModelDuplicates: vi.fn() }));+const deduplication = await import('../services/modelDeduplication.js');+const lifecycle = vi.hoisted(() => ({ onDisconnect: null, stopRun: vi.fn(async () => true) }));vi.mock('../services/systemResources.js', () => ({@@ -96,3 +99,37 @@ describe('system resources routes', () => {expect(resources.triageSystemResources).not.toHaveBeenCalled();});});++it('validates duplicate requests and replaces a verified weight through the route', async () => {+ const fs = await import('node:fs/promises');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const actual = await vi.importActual('../services/modelDeduplication.js');+ const root = await fs.realpath(await fs.mkdtemp(join(tmpdir(), 'dedupe-route-')));+ const local = join(root, 'local');+ const external = join(root, 'pinokio');+ await fs.mkdir(local);+ await fs.mkdir(external);+ const sourcePath = join(local, 'example.gguf');+ const targetPath = join(external, 'example.gguf');+ const bytes = Buffer.alloc(10 * 1024 * 1024, 3);+ await fs.writeFile(sourcePath, bytes);+ await fs.writeFile(targetPath, bytes);+ deduplication.rectifyModelDuplicates.mockImplementation((pairs) => actual.rectifyModelDuplicates(pairs, {+ roots: { local: [local], external: [external] },+ }));+ const app = makeApp();+ const invalid = await request(app).post('/api/system-resources/duplicates/rectify').send({ pairs: [] });+ expect(invalid.status).toBe(400);+ const escaped = await request(app).post('/api/system-resources/duplicates/rectify').send({+ pairs: [{ sourcePath, targetPath: join(root, 'outside.gguf') }],+ });+ expect(escaped.status).toBe(400);+ const result = await request(app).post('/api/system-resources/duplicates/rectify').send({+ pairs: [{ sourcePath, targetPath }],+ });+ expect(result.status).toBe(200);+ expect(result.body.success).toBe(true);+ expect((await fs.stat(sourcePath)).ino).toBe((await fs.stat(targetPath)).ino);+ await fs.rm(root, { recursive: true, force: true });+});diff --git a/server/services/modelDeduplication.js b/server/services/modelDeduplication.jsnew file mode 100644index 0000000000..c6e4c1742f--- /dev/null+++ b/server/services/modelDeduplication.js@@ -0,0 +1,179 @@+/**+ * Machine-local model deduplication. Scans only explicit model roots; never+ * publishes paths through federation or AI triage. Replacements require a+ * fresh full SHA-256 comparison, and preserve HF snapshot symlinks.+ */+import fs from 'node:fs/promises';+import { homedir } from 'node:os';+import { basename, dirname, extname, join, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PATHS } from '../lib/paths.js';+import { sha256File } from '../lib/fileCore.js';+import { getHfCacheRoot } from '../lib/hfCache.js';+import { isPathInsideDir } from '../lib/pathSafety.js';+import { ServerError } from '../lib/errorHandler.js';++const MIN_BYTES = 10 * 1024 * 1024;+const WEIGHTS = new Set(['.safetensors', '.bin', '.pt', '.ckpt', '.gguf']);+const DRIVE_NAMES = ['mlx_models', 'checkpoints', 'loras', 'diffusers', 'models'];+const missing = (error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+};+const invalid = (message) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });+const identity = (info) => `${info.dev}:${info.ino}`;+const unchanged = (a, b) => identity(a) === identity(b) && a.size === b.size+ && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;++async function directories(root) {+ return (await fs.readdir(root, { withFileTypes: true }).catch(missing) || [])+ .filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name));+}++async function rootsForInstall() {+ const pinokio = resolve(process.env.PINOKIO_HOME || process.env.PINOKIO_PATH || join(homedir(), 'pinokio'));+ if (!(await fs.stat(pinokio).catch(missing))?.isDirectory()) return null;+ const peers = await directories(join(pinokio, 'drive', 'drives', 'peers'));+ const apps = await directories(join(pinokio, 'api'));+ const external = [+ ...DRIVE_NAMES.map((name) => join(pinokio, name)),+ ...peers.flatMap((peer) => DRIVE_NAMES.map((name) => join(peer, name))),+ ...apps.map((app) => join(app, 'models')),+ join(pinokio, 'cache', 'huggingface', 'hub'),+ ];+ // Named model mappings may point at drives outside Pinokio home.+ const manifest = await fs.readFile(join(pinokio, 'drive', 'drives.json'), 'utf8').catch(missing);+ const collectMappings = (value, key = '') => {+ if (typeof value === 'string' && DRIVE_NAMES.includes(key)) external.push(resolve(pinokio, value));+ else if (value && typeof value === 'object') {+ for (const [name, child] of Object.entries(value)) collectMappings(child, name);+ }+ };+ if (manifest) collectMappings(JSON.parse(manifest));+ const { getModelsDir } = await import('./lmStudioManager.js');+ const local = [getHfCacheRoot(), PATHS.loras, await getModelsDir()];+ const canonicalRoots = async (roots) => [...new Set((await Promise.all(+ roots.map((root) => fs.realpath(root).catch(missing)),+ )).filter(Boolean))];+ return { local: await canonicalRoots(local), external: await canonicalRoots(external) };+}++async function inventory(roots) {+ const files = [];+ const visited = new Set();+ let count = 0;+ const walk = async (path, depth) => {+ if (++count > 50000 || depth > 16) throw invalid('Model scan limit reached; narrow the model roots and retry.');+ const real = await fs.realpath(path).catch(missing);+ if (!real || !roots.some((root) => real === root || isPathInsideDir(root, real))) return;+ const info = await fs.stat(real).catch(missing);+ if (!info) return;+ if (info.isDirectory()) {+ if (visited.has(real)) return;+ visited.add(real);+ for (const entry of await fs.readdir(real)) await walk(join(path, entry), depth + 1);+ } else if (info.isFile() && info.size >= MIN_BYTES && WEIGHTS.has(extname(path).toLowerCase())) {+ files.push({ path, real, info, name: basename(path), model: basename(dirname(path)) });+ }+ };+ for (const root of roots) await walk(root, 0);+ return files;+}++export async function scanModelDuplicates({ roots } = {}) {+ roots ??= await rootsForInstall();+ if (!roots) return { pinokioDetected: false, items: [], totalReclaimableBytes: 0 };+ const local = await inventory(roots.local);+ const external = await inventory(roots.external);+ const hashes = new Map();+ const hash = (file) => {+ const key = identity(file.info);+ if (!hashes.has(key)) hashes.set(key, sha256File(file.real));+ return hashes.get(key);+ };+ const items = [];+ const seen = new Set();+ for (const target of external) {+ if (seen.has(target.real)) continue;+ for (const source of local) {+ if (source.info.size !== target.info.size || source.name !== target.name) continue;+ const alreadyLinked = identity(source.info) === identity(target.info);+ if (!alreadyLinked && await hash(source) !== await hash(target)) continue;+ // A target with other hardlink names cannot release blocks by replacing+ // this single name. Leave those aliases untouched and report zero savings.+ const reclaimableBytes = alreadyLinked || target.info.nlink > 1 ? 0 : target.info.blocks * 512;+ items.push({+ sourcePath: source.path, targetPath: target.path, model: target.model,+ sizeBytes: target.info.size, reclaimableBytes, alreadyLinked,+ canLink: !alreadyLinked && target.info.nlink === 1 && source.info.dev === target.info.dev+ && source.info.mode === target.info.mode && source.info.uid === target.info.uid && source.info.gid === target.info.gid,+ });+ seen.add(target.real);+ break;+ }+ }+ return { pinokioDetected: true, items, totalReclaimableBytes: items.reduce((sum, item) => sum + (item.canLink ? item.reclaimableBytes : 0), 0) };+}++async function validatedFile(path, roots) {+ if (!WEIGHTS.has(extname(path).toLowerCase()) || !roots.some((root) => isPathInsideDir(root, resolve(path)))) {+ throw invalid('File is outside the allowed model roots.');+ }+ const real = await fs.realpath(path).catch(missing);+ if (!real || !roots.some((root) => isPathInsideDir(root, real))) throw invalid('Unsafe or missing model link.');+ const info = await fs.stat(real);+ if (!info.isFile() || info.size < MIN_BYTES) throw invalid('Expected a model weight file of at least 10 MB.');+ return { path, real, info };+}++let rectifying = false;+export async function rectifyModelDuplicates(pairs, { roots } = {}) {+ if (rectifying) throw new ServerError('Model linking is already running.', { status: 409 });+ rectifying = true;+ return performRectification(pairs, roots).finally(() => { rectifying = false; });+}++async function performRectification(pairs, roots) {+ roots ??= await rootsForInstall();+ if (!roots) throw invalid('Pinokio is not installed.');+ const results = [];+ // Validate the entire batch before making its first replacement.+ const prepared = [];+ const targets = new Set();+ for (const pair of pairs) {+ const source = await validatedFile(pair.sourcePath, roots.local);+ const target = await validatedFile(pair.targetPath, roots.external);+ if (targets.has(target.real)) continue;+ targets.add(target.real);+ if (identity(source.info) === identity(target.info)) continue;+ if (target.info.nlink !== 1) throw invalid('Target has additional hardlinks; no space can be reclaimed safely.');+ if (source.info.mode !== target.info.mode || source.info.uid !== target.info.uid || source.info.gid !== target.info.gid) {+ throw invalid('File permissions or ownership differ; linking would change application access.');+ }+ if (source.info.dev !== target.info.dev) throw invalid('Hardlinks cannot span filesystems.');+ if (source.info.size !== target.info.size || await sha256File(source.real) !== await sha256File(target.real)) {+ throw invalid('Model contents differ; no files were linked.');+ }+ prepared.push({ source, target });+ }+ // No batch may replace a canonical source used by another pair.+ if (prepared.some(({ source }) => targets.has(source.real))) throw invalid('Overlapping source and target paths.');+ const sourceStates = new Map();+ for (const { source, target } of prepared) {+ const sourceNow = await fs.stat(source.real);+ const targetNow = await fs.stat(target.real);+ if (!unchanged(sourceStates.get(source.real) || source.info, sourceNow) || !unchanged(target.info, targetNow)+ || await fs.realpath(source.path) !== source.real || await fs.realpath(target.path) !== target.real) {+ throw invalid('Model changed since verification; rescan before linking.');+ }+ const temporary = join(dirname(target.real), `.portos-link-${randomUUID()}`);+ await fs.link(source.real, temporary);+ await fs.rename(temporary, target.real).catch(async (error) => {+ await fs.unlink(temporary);+ throw error;+ });+ sourceStates.set(source.real, await fs.stat(source.real));+ results.push({ ...pairs.find((pair) => pair.targetPath === target.path), reclaimedBytes: target.info.blocks * 512 });+ }+ return { success: true, reclaimedBytes: results.reduce((sum, result) => sum + result.reclaimedBytes, 0), results };+}diff --git a/server/services/modelDeduplication.test.js b/server/services/modelDeduplication.test.jsnew file mode 100644index 0000000000..a2305ac3e4--- /dev/null+++ b/server/services/modelDeduplication.test.js@@ -0,0 +1,115 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { scanModelDuplicates, rectifyModelDuplicates } from './modelDeduplication.js';++vi.mock('./lmStudioManager.js', () => ({ getModelsDir: async () => process.env.LM_STUDIO_MODELS_DIR }));++let root;+let roots;+const bytes = Buffer.alloc(10 * 1024 * 1024, 7);+async function weight(dir, name = 'example.safetensors', data = bytes) {+ await fs.mkdir(dir, { recursive: true });+ const path = join(dir, name);+ await fs.writeFile(path, data);+ return path;+}+beforeEach(async () => {+ root = await fs.realpath(await fs.mkdtemp(join(tmpdir(), 'model-dedupe-')));+ roots = { local: [join(root, 'local')], external: [join(root, 'pinokio')] };+ await Promise.all([...roots.local, ...roots.external].map((dir) => fs.mkdir(dir)));+});+afterEach(async () => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ await fs.rm(root, { recursive: true, force: true });+});++it('verifies contents, preserves HF snapshot links and links multiple copies to one source', async () => {+ const blob = await weight(join(roots.local[0], 'blobs'), 'hash');+ const snapshot = join(roots.local[0], 'snapshots', 'revision');+ await fs.mkdir(snapshot, { recursive: true });+ const sourcePath = join(snapshot, 'example.safetensors');+ await fs.symlink(blob, sourcePath);+ const targetPath = await weight(join(roots.external[0], 'first'));+ const secondPath = await weight(join(roots.external[0], 'second'));+ const wrongPath = await weight(join(roots.external[0], 'wrong'), 'example.safetensors', Buffer.alloc(bytes.length, 8));+ const report = await scanModelDuplicates({ roots });+ expect(report.items).toHaveLength(2);+ expect(report.totalReclaimableBytes).toBe((await fs.stat(targetPath)).blocks * 1024);+ const rename = vi.spyOn(fs, 'rename');+ const result = await rectifyModelDuplicates(report.items, { roots });+ expect(result.reclaimedBytes).toBe(report.totalReclaimableBytes);+ expect(rename).toHaveBeenCalledTimes(2);+ expect((await fs.lstat(sourcePath)).isSymbolicLink()).toBe(true);+ for (const path of [targetPath, secondPath]) {+ expect((await fs.stat(path)).ino).toBe((await fs.stat(blob)).ino);+ expect((await fs.readFile(path)).equals(bytes)).toBe(true);+ }+ expect((await fs.readFile(wrongPath)).equals(Buffer.alloc(bytes.length, 8))).toBe(true);+ const rescanned = await scanModelDuplicates({ roots });+ expect(rescanned.totalReclaimableBytes).toBe(0);+ expect(rescanned.items.every((item) => item.alreadyLinked)).toBe(true);+});++it('rejects mismatches and symlink escapes before replacing any batch entry', async () => {+ const sourcePath = await weight(roots.local[0]);+ const targetPath = await weight(roots.external[0]);+ const original = (await fs.stat(targetPath)).ino;+ const outside = await weight(root, 'outside.safetensors');+ const escape = join(roots.external[0], 'escape.safetensors');+ await fs.symlink(outside, escape);+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath }, { sourcePath, targetPath: escape }], { roots })).rejects.toThrow('Unsafe');+ expect((await fs.stat(targetPath)).ino).toBe(original);+ await fs.writeFile(targetPath, Buffer.alloc(bytes.length, 9));+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath }], { roots })).rejects.toThrow('contents differ');+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath: outside }], { roots })).rejects.toThrow('outside');+});++it('does not count target aliases and rejects cross-device replacement', async () => {+ const sourcePath = await weight(roots.local[0]);+ const targetPath = await weight(roots.external[0]);+ const alias = join(roots.external[0], 'alias.safetensors');+ await fs.link(targetPath, alias);+ expect((await scanModelDuplicates({ roots })).totalReclaimableBytes).toBe(0);+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath }], { roots })).rejects.toThrow('additional hardlinks');+ await fs.unlink(alias);+ const stat = fs.stat.bind(fs);+ vi.spyOn(fs, 'stat').mockImplementation(async (path, ...args) => {+ const info = await stat(path, ...args);+ if (path === targetPath) info.dev += 1;+ return info;+ });+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath }], { roots })).rejects.toThrow('span filesystems');+});++it('cleans a failed rename without replacing the original', async () => {+ const sourcePath = await weight(roots.local[0]);+ const targetPath = await weight(roots.external[0]);+ const original = (await fs.stat(targetPath)).ino;+ vi.spyOn(fs, 'rename').mockRejectedValue(new Error('rename failed'));+ await expect(rectifyModelDuplicates([{ sourcePath, targetPath }], { roots })).rejects.toThrow('rename failed');+ expect((await fs.stat(targetPath)).ino).toBe(original);+ expect(await fs.readdir(roots.external[0])).toEqual(['example.safetensors']);+});++it('does no directory traversal when Pinokio is absent', async () => {+ vi.stubEnv('PINOKIO_HOME', join(root, 'absent'));+ const read = vi.spyOn(fs, 'readdir');+ expect(await scanModelDuplicates()).toEqual({ pinokioDetected: false, items: [], totalReclaimableBytes: 0 });+ expect(read).not.toHaveBeenCalled();+});++it('discovers peer drives, app models and the separate HF cache from configured roots', async () => {+ vi.stubEnv('PINOKIO_HOME', roots.external[0]);+ vi.stubEnv('HF_HUB_CACHE', roots.local[0]);+ vi.stubEnv('LM_STUDIO_MODELS_DIR', join(root, 'absent-lm'));+ await weight(roots.local[0]);+ await weight(join(roots.external[0], 'drive', 'drives', 'peers', 'example-peer', 'mlx_models', 'example-model'));+ await weight(join(roots.external[0], 'api', 'example-app', 'models'));+ await weight(join(roots.external[0], 'cache', 'huggingface', 'hub', 'models--example--model', 'snapshots', 'revision'));+ const report = await scanModelDuplicates();+ expect(report.pinokioDetected).toBe(true);+ expect(report.items).toHaveLength(3);+});diff --git a/server/services/systemResources.js b/server/services/systemResources.jsindex 9d7237a261..60658ffe3d 100644--- a/server/services/systemResources.js+++ b/server/services/systemResources.js@@ -9,6 +9,7 @@*/import os from 'os';+import { scanModelDuplicates } from './modelDeduplication.js';import { statfs } from 'fs/promises';import { join } from 'path';import { z } from 'zod';@@ -373,6 +374,7 @@ export async function buildSystemResourceReport() {browserDownloadsBytes,cosTasks,cosStatus,+ modelDuplicates,] = await Promise.all([statfs('/').catch(() => null),getDataOverview({ strict: true }).catch(() => null),@@ -396,6 +398,7 @@ export async function buildSystemResourceReport() {dirSize(PATHS.browserDownloads, { strict: true }).catch(() => null),cos.getAllTasks().catch(() => null),cos.getStatus().catch(() => null),+ scanModelDuplicates().catch(() => ({ pinokioDetected: null, items: [], totalReclaimableBytes: 0, error: 'Duplicate model scan unavailable' })),]);const filesystem = filesystemFrom(diskStats);@@ -548,6 +551,7 @@ export async function buildSystemResourceReport() {},queues: { media: mediaQueue, agents: agentQueue },cleanupCandidates,+ modelDuplicates,sourceErrors,disabledSources,};diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.jsindex 250c8b49a4..8cc64a9e2f 100644--- a/server/services/systemResources.test.js+++ b/server/services/systemResources.test.js@@ -1,5 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+vi.mock('./modelDeduplication.js', () => ({ scanModelDuplicates: vi.fn(async () => ({ pinokioDetected: false, items: [], totalReclaimableBytes: 0 })) }));+vi.mock('fs/promises', async (importOriginal) => ({...(await importOriginal()),statfs: vi.fn(async () => ({ blocks: 1000, bsize: 100, bavail: 250 })),