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
address review (codex): normalize gallery uploads to PNG so the gallery API manages them (#1327)
[._.]/ Adam Eivy4fa0503cc84c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3d04fdaaef..aea1f5f9ce 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -67,7 +67,7 @@## Fixed-- **[issue-1327] Uploaded (non-gallery) author headshots now transfer to federated peers.** The authors federation only shipped a headshot's image bytes when its `headshotImageUrl` pointed at `/data/images/<f>` (a gallery-picked image) — `headshotImageFilename()` maps that to the `image` asset the peer-sync pull worker fetches. But the Authors page's **upload** button routed through the generic `POST /api/uploads`, storing the file in `data/uploads/` and setting `headshotImageUrl = /api/uploads/<f>`, which is **not** a pullable asset kind — so on a peer the author record synced but the headshot 404'd. Author-headshot uploads now go through the gallery instead: a new `POST /api/image-gen/upload` saves the uploaded bytes into `data/images/` (sniffing the real format from the magic bytes — PNG/JPEG/WebP/GIF — and rejecting non-image payloads) and returns a `/data/images/<f>` URL, so the headshot rides the existing `image` pull path and its bytes reach every peer. The magic-byte sniffer is consolidated into a shared `detectImageFormat()` in `fileUtils.js` (reused by `imageClean.js`). (`server/lib/fileUtils.js`, `server/lib/imageClean.js`, `server/services/imageGen/local.js`, `server/routes/imageGen.js`, `client/src/services/apiSystem.js`, `client/src/pages/Authors.jsx`, #1327)+- **[issue-1327] Uploaded (non-gallery) author headshots now transfer to federated peers.** The authors federation only shipped a headshot's image bytes when its `headshotImageUrl` pointed at `/data/images/<f>` (a gallery-picked image) — `headshotImageFilename()` maps that to the `image` asset the peer-sync pull worker fetches. But the Authors page's **upload** button routed through the generic `POST /api/uploads`, storing the file in `data/uploads/` and setting `headshotImageUrl = /api/uploads/<f>`, which is **not** a pullable asset kind — so on a peer the author record synced but the headshot 404'd. Author-headshot uploads now go through the gallery instead: a new `POST /api/image-gen/upload` saves the uploaded bytes into `data/images/` — sniffing the real format from the magic bytes (PNG/JPEG/WebP/GIF), rejecting non-image payloads, and re-encoding to PNG so the saved file is a first-class gallery citizen (it lists in the gallery and deletes through the gallery API, both PNG-only) — and returns a `/data/images/<f>` URL, so the headshot rides the existing `image` pull path and its bytes reach every peer. The magic-byte sniffer is consolidated into a shared `detectImageFormat()` in `fileUtils.js` (reused by `imageClean.js`). (`server/lib/fileUtils.js`, `server/lib/imageClean.js`, `server/services/imageGen/local.js`, `server/routes/imageGen.js`, `client/src/services/apiSystem.js`, `client/src/pages/Authors.jsx`, #1327)- **[issue-1319] LoRA training and video renders now survive a `pm2 restart portos-server` instead of dying mid-run.** A multi-hour LoRA training run kept dying with `SIGINT`/`KeyboardInterrupt` at the exact second portos-server restarted (it restarts routinely on the memory ceiling). Root cause: pm2's `TreeKill` walks the parent→child process tree by **PPID** and signals every descendant of portos-server on restart — and the trainer/render children were descendants. `detached: true` didn't help (it only moves the child to a new process *group*; TreeKill keys on PPID, not the group), and `treekill: false` on the app broke pm2's own reap (lingering `:5555` → EADDRINUSE crash-loop). The fix is spawn-side: a new `spawnDetached` helper (`server/lib/detachedSpawn.js`) **double-forks** the job through a pure-`sh` launcher so it reparents to init (PPID=1) and leaves pm2's tree entirely, while the server keeps streaming progress by tailing on-disk log files (`stdout`/`stderr`/exit-status). Both spawn sites adopt it — `server/services/loraTraining/index.js` (was relying on the ineffective `detached: true`) and `server/services/videoGen/local.js` (which previously had *no* detach at all, so it was fully exposed). Cancel/SIGKILL escalation, the completion watchdog, and `caffeinate` keep-awake all work unchanged (they signal the job by PID, which still reaches the reparented child); video renders clean up their `data/videos/.detached/<jobId>` scratch dir on completion. Because a surviving child outlives the server, boot reconcile now **reaps** any still-running orphan (clean `SIGTERM` so the trainer checkpoints, then `SIGKILL`) before marking its run/job failed — and `resumeTrainingRun` reaps too — so a restart becomes a clean checkpointed stop instead of a mid-op `SIGINT` crash, and a resume can never spawn a second trainer into the same checkpoint dir. (Full re-attach-and-finalize across a restart is tracked in #1332.) The raised memory ceiling + checkpoint-resume remain the safety net for the rare restart that lands in the ~1ms pre-detach window. (`server/lib/detachedSpawn.js`, `server/services/loraTraining/index.js`, `server/services/videoGen/local.js`, `server/services/mediaJobQueue/index.js`, #1319)diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 74ad4ddb49..9dbcbe8feb 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -841,10 +841,12 @@ const MAX_GALLERY_UPLOAD_BYTES = 16 * 1024 * 1024;* Persist user-uploaded image bytes (base64) into the gallery dir under* `data/images/` so the file rides the existing `image` peer-sync asset path* (a record pointing at `/data/images/<f>` ships its bytes to peers; a- * `/api/uploads/<f>` path does not). The real format is sniffed from the- * leading bytes — the client-supplied name/extension is not trusted — and a- * non-image payload is rejected with a 400. Returns the bare gallery filename- * and its `/data/images/` mount path for the caller to store on the record.+ * `/api/uploads/<f>` path does not). The payload is sniffed by magic bytes —+ * the client-supplied name/extension is not trusted — and a non-image is+ * rejected with a 400, then re-encoded to **PNG** so the saved file is a+ * first-class gallery citizen: it lists in `/image-gen/gallery` and deletes via+ * `deleteImage`, both of which only manage `.png`. Returns the bare gallery+ * filename and its `/data/images/` mount path for the caller to store.** @param {string} base64Data - Raw base64 (no data: URI prefix) image bytes* @returns {Promise<{ filename: string, path: string }>}@@ -861,10 +863,12 @@ export async function saveUploadedGalleryImage(base64Data) {if (!detected) {throw new ServerError('Unsupported image format (expected PNG, JPEG, WebP, or GIF)', { status: 400, code: 'UNSUPPORTED_IMAGE' });}- const filename = `upload-${randomUUID().slice(0, 8)}${detected.ext}`;+ // Normalize to PNG so the gallery's PNG-only list/delete paths manage it.+ const png = await sharp(buffer).png().toBuffer();+ const filename = `upload-${randomUUID().slice(0, 8)}.png`;await ensureDir(PATHS.images);- await writeFile(join(PATHS.images, filename), buffer);- console.log(`📥 Saved uploaded gallery image: ${filename} (${(buffer.length / 1024).toFixed(0)}KB, ${detected.mime})`);+ await writeFile(join(PATHS.images, filename), png);+ console.log(`📥 Saved uploaded gallery image: ${filename} (${(png.length / 1024).toFixed(0)}KB PNG, from ${detected.mime})`);return { filename, path: `/data/images/${filename}` };}diff --git a/server/services/imageGen/saveUploadedGalleryImage.test.js b/server/services/imageGen/saveUploadedGalleryImage.test.jsindex 5cb10f13c5..18e35db27f 100644--- a/server/services/imageGen/saveUploadedGalleryImage.test.js+++ b/server/services/imageGen/saveUploadedGalleryImage.test.js@@ -2,8 +2,14 @@ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';+import sharp from 'sharp';import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';+// The PNG 8-byte signature — used to assert a written gallery file is a PNG+// without importing from the (mocked) fileUtils module.+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+const isPng = (buf) => buf.subarray(0, 8).equals(PNG_SIGNATURE);+// Redirect PATHS.images at a per-test temp dir so saving an uploaded image// writes into the temp gallery, not the repo's real data/images.let imagesDir;@@ -26,14 +32,18 @@ let tmpRoot;let priorRegistryEnv;let saveUploadedGalleryImage;-const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00]);-const GIF = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x00, 0x00]);+// A real 1x1 GIF89a (sharp can decode it). Real PNG/JPEG are built in beforeAll.+const GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');+let realPng;+let realJpeg;beforeAll(async () => {tmpRoot = mkdtempSync(join(tmpdir(), 'portos-gallery-upload-test-'));imagesDir = join(tmpRoot, 'images');priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRoot, 'media-models.json');+ realPng = await sharp({ create: { width: 2, height: 2, channels: 3, background: { r: 10, g: 20, b: 30 } } }).png().toBuffer();+ realJpeg = await sharp({ create: { width: 2, height: 2, channels: 3, background: { r: 40, g: 50, b: 60 } } }).jpeg().toBuffer();vi.resetModules();({ saveUploadedGalleryImage } = await import('./local.js'));});@@ -45,17 +55,21 @@ afterAll(() => {});describe('saveUploadedGalleryImage', () => {- it('writes PNG bytes into the gallery and returns a /data/images path', async () => {- const { filename, path } = await saveUploadedGalleryImage(PNG.toString('base64'));+ it('writes a PNG into the gallery and returns a /data/images path', async () => {+ const { filename, path } = await saveUploadedGalleryImage(realPng.toString('base64'));expect(filename).toMatch(/^upload-[0-9a-f]{8}\.png$/);expect(path).toBe(`/data/images/${filename}`);expect(existsSync(join(imagesDir, filename))).toBe(true);- expect(readFileSync(join(imagesDir, filename))).toEqual(PNG);+ // Written file is a valid PNG (so the gallery's PNG-only list/delete manage it).+ expect(isPng(readFileSync(join(imagesDir, filename)))).toBe(true);});- it('derives the extension from the real bytes, not a client filename', async () => {- const { filename } = await saveUploadedGalleryImage(GIF.toString('base64'));- expect(filename.endsWith('.gif')).toBe(true);+ it('normalizes a non-PNG upload (GIF/JPEG) to a managed .png gallery file', async () => {+ for (const src of [GIF, realJpeg]) {+ const { filename } = await saveUploadedGalleryImage(src.toString('base64'));+ expect(filename.endsWith('.png')).toBe(true);+ expect(isPng(readFileSync(join(imagesDir, filename)))).toBe(true);+ }});it('rejects an empty upload with a 400', async () => {