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
fix: address Copilot review feedback on PR #188
Adam Eivyec64c3980f51
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 6da419696e..179d686c5e 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -23,7 +23,9 @@ import { PATHS } from './fileUtils.js';// synchronous version because `loadMediaModels()` is called at import-time// from videoGen/imageGen modules, which can't await before exporting.-const REGISTRY_FILE = join(PATHS.data, 'media-models.json');+// Allow tests + non-standard deployments to point at a different file+// without monkey-patching PATHS. Defaults to data/media-models.json.+const REGISTRY_FILE = process.env.PORTOS_MEDIA_MODELS_FILE || join(PATHS.data, 'media-models.json');const IS_WIN = process.platform === 'win32';const DEFAULT_REGISTRY = {@@ -47,14 +49,21 @@ const DEFAULT_REGISTRY = {{ id: 'flux2-klein-9b', name: 'Flux 2 Klein 9B', steps: 8, guidance: 3.5, broken: 'macos' },],textEncoders: [- { id: 'gemma-4bit', label: 'Gemma 3 12B 4-bit (default, ~7 GB)', repo: 'mlx-community/gemma-3-12b-it-4bit' },+ { id: 'gemma-4bit', label: 'Gemma 3 12B 4-bit (smallest, ~7 GB)', repo: 'mlx-community/gemma-3-12b-it-4bit' },{ id: 'gemma-qat-4bit', label: 'Gemma 3 12B QAT 4-bit (better, ~8 GB, LM Studio)', repo: 'mlx-community/gemma-3-12b-it-qat-4bit', localPath: '~/.lmstudio/models/mlx-community/gemma-3-12b-it-qat-4bit' },- { id: 'gemma-bf16', label: 'Gemma 3 12B bf16 (best, ~24 GB, large download)', repo: 'mlx-community/gemma-3-12b-it-bf16' },+ { id: 'gemma-bf16', label: 'Gemma 3 12B bf16 (default, best quality, ~24 GB)', repo: 'mlx-community/gemma-3-12b-it-bf16' },],- selectedTextEncoder: 'gemma-4bit',+ selectedTextEncoder: 'gemma-bf16',};-const expandHome = (p) => (p && p.startsWith('~') ? join(homedir(), p.slice(1)) : p);+// `path.join(homedir(), '/.foo')` discards the homedir because of the+// leading slash, so we have to strip the `~/` prefix (or `~`) before joining.+const expandHome = (p) => {+ if (!p || !p.startsWith('~')) return p;+ if (p === '~') return homedir();+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));+ return p;+};let cached = null;@@ -73,8 +82,17 @@ const seedIfMissing = () => {export const loadMediaModels = () => {if (cached) return cached;seedIfMissing();+ // Catch parse failures so a malformed user edit doesn't crash server boot+ // — the loader is invoked at module import-time from videoGen/imageGen, so+ // an exception here aborts startup. Fall back to the in-memory defaults+ // and surface the error in logs so the operator can fix the file.const raw = readFileSync(REGISTRY_FILE, 'utf-8');- cached = JSON.parse(raw);+ try {+ cached = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ Failed to parse ${REGISTRY_FILE} (${err.message}) — using built-in defaults`);+ cached = DEFAULT_REGISTRY;+ }return cached;};diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsnew file mode 100644index 0000000000..430884af5b--- /dev/null+++ b/server/lib/mediaModels.test.js@@ -0,0 +1,133 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir, homedir } from 'os';+import { join } from 'path';++let tmpDir;+let registryFile;++beforeEach(() => {+ tmpDir = mkdtempSync(join(tmpdir(), 'portos-media-models-'));+ registryFile = join(tmpDir, 'media-models.json');+ process.env.PORTOS_MEDIA_MODELS_FILE = registryFile;+ vi.resetModules();+});++afterEach(() => {+ delete process.env.PORTOS_MEDIA_MODELS_FILE;+ rmSync(tmpDir, { recursive: true, force: true });+});++describe('mediaModels registry', () => {+ it('seeds the registry file on first load', async () => {+ expect(existsSync(registryFile)).toBe(false);+ const { loadMediaModels } = await import('./mediaModels.js');+ loadMediaModels();+ expect(existsSync(registryFile)).toBe(true);+ const seeded = JSON.parse(readFileSync(registryFile, 'utf-8'));+ expect(seeded.video).toBeDefined();+ expect(seeded.image).toBeDefined();+ expect(seeded.textEncoders).toBeDefined();+ expect(seeded.selectedTextEncoder).toBe('gemma-bf16');+ });++ it('returns the platform-specific video model list', async () => {+ const { getVideoModels } = await import('./mediaModels.js');+ const list = getVideoModels();+ expect(Array.isArray(list)).toBe(true);+ expect(list.every((m) => m.id && m.name)).toBe(true);+ });++ it('hides models with broken === current platform', async () => {+ const here = process.platform === 'win32' ? 'windows' : 'macos';+ const elsewhere = process.platform === 'win32' ? 'macos' : 'windows';+ writeFileSync(registryFile, JSON.stringify({+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },+ image: [+ { id: 'works', name: 'Works' },+ { id: 'broken-here', name: 'Broken Here', broken: here },+ { id: 'broken-other', name: 'Broken Elsewhere', broken: elsewhere },+ ],+ textEncoders: [{ id: 't', label: 't', repo: 'r' }],+ selectedTextEncoder: 't',+ }));+ const { getImageModels } = await import('./mediaModels.js');+ const ids = getImageModels().map((m) => m.id);+ expect(ids).toContain('works');+ expect(ids).toContain('broken-other');+ expect(ids).not.toContain('broken-here');+ });++ it('expandHome resolves ~/ correctly without dropping the home dir', async () => {+ writeFileSync(registryFile, JSON.stringify({+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },+ image: [],+ textEncoders: [+ { id: 'tilde-only', label: 't', repo: 'r1', localPath: '~' },+ { id: 'tilde-slash', label: 't', repo: 'r2', localPath: '~/some/nonexistent/path' },+ ],+ selectedTextEncoder: 'tilde-slash',+ }));+ const { getTextEncoderEntries } = await import('./mediaModels.js');+ const entries = getTextEncoderEntries();+ const tilde = entries.find((e) => e.id === 'tilde-only');+ const slash = entries.find((e) => e.id === 'tilde-slash');+ // The bug being guarded against: `path.join(homedir(), '/.foo')` discards+ // the homedir because the second segment starts with /. The fix strips+ // the `~/` prefix before joining. Result MUST start with the user's+ // actual home directory, not just `/`.+ expect(slash.localPath.startsWith(homedir())).toBe(true);+ expect(slash.localPath).toContain('/some/nonexistent/path');+ expect(tilde.localPath).toBe(homedir());+ });++ it('getTextEncoderRepo prefers existing localPath over repo', async () => {+ writeFileSync(registryFile, JSON.stringify({+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },+ image: [],+ textEncoders: [+ { id: 'has-local', label: 'L', repo: 'org/repo', localPath: tmpDir },+ ],+ selectedTextEncoder: 'has-local',+ }));+ const { getTextEncoderRepo } = await import('./mediaModels.js');+ expect(getTextEncoderRepo()).toBe(tmpDir);+ });++ it('getTextEncoderRepo falls back to repo when localPath does not exist', async () => {+ writeFileSync(registryFile, JSON.stringify({+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },+ image: [],+ textEncoders: [{ id: 't', label: 't', repo: 'org/repo', localPath: '/definitely/not/existing/12345' }],+ selectedTextEncoder: 't',+ }));+ const { getTextEncoderRepo } = await import('./mediaModels.js');+ expect(getTextEncoderRepo()).toBe('org/repo');+ });++ it('falls back to defaults on malformed JSON without crashing', async () => {+ writeFileSync(registryFile, '{ this is not valid json');+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ expect(reg.video).toBeDefined();+ expect(reg.selectedTextEncoder).toBe('gemma-bf16');+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to parse'));+ logSpy.mockRestore();+ });++ it('caches the registry across calls (no repeat parse)', async () => {+ const { loadMediaModels } = await import('./mediaModels.js');+ const first = loadMediaModels();+ writeFileSync(registryFile, JSON.stringify({ ...first, selectedTextEncoder: 'gemma-4bit' }));+ const second = loadMediaModels();+ expect(second.selectedTextEncoder).toBe(first.selectedTextEncoder);+ });++ it('getDefaultVideoModelId returns the per-platform default', async () => {+ const { getDefaultVideoModelId } = await import('./mediaModels.js');+ const id = getDefaultVideoModelId();+ expect(typeof id).toBe('string');+ expect(id.length).toBeGreaterThan(0);+ });+});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex fb3a470826..58ed712e35 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -28,7 +28,7 @@ const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';// Catalog comes from data/media-models.json (see server/lib/mediaModels.js).-// Cached as a Map at boot for O(1) lookup by id, matching the prior shape.+// Cached as a plain object at boot for O(1) lookup by id, matching the prior shape.export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id, m]));export const listVideoModels = () => getVideoModels();@@ -127,7 +127,14 @@ const optimizeForStreaming = async (videoPath) => {});if (!ok) { await unlink(tmpPath).catch(() => {}); return; }// Atomic single-syscall replace — no window where the file is missing.- await rename(tmpPath, videoPath).catch(() => {});+ // If rename fails (cross-device, permissions, file-in-use) we'd otherwise+ // leak the tmp file silently and slowly fill data/videos with .fs.mp4s.+ try {+ await rename(tmpPath, videoPath);+ } catch (err) {+ await unlink(tmpPath).catch(() => {});+ console.log(`⚠️ Failed to install streaming-optimized video at ${videoPath}: ${err.message}`);+ }};export const loadHistory = () => readJSONFile(HISTORY_FILE, []);@@ -401,6 +408,13 @@ export async function extractLastFrame(historyId) {if (!existsSync(videoPath)) throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });await ensureDir(PATHS.images);+ // Same path-traversal concern as `item.filename` above — `item.id` could+ // contain path separators or `..` if history.json was tampered with.+ // generateVideo writes ids via randomUUID() (matches /^[a-f0-9-]{36}$/),+ // so reject anything else outright.+ if (!/^[a-f0-9-]{36}$/i.test(item.id)) {+ throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });+ }const frameFilename = `lastframe-${item.id}.png`;const framePath = join(PATHS.images, frameFilename);// Cache hit: ffmpeg-extracted frames are deterministic for a given video,