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: mood board collage compilation and video frame extraction
Adam Eivy5305cca2be5c
diff --git a/client/src/components/moodBoard/MoodBoardCollagePanel.jsx b/client/src/components/moodBoard/MoodBoardCollagePanel.jsxnew file mode 100644index 0000000000..9f96f5507b--- /dev/null+++ b/client/src/components/moodBoard/MoodBoardCollagePanel.jsx@@ -0,0 +1,89 @@+import { useState } from 'react';+import { LayoutGrid, Download } from 'lucide-react';+import toast from '../ui/Toast';+import { composeMoodBoardCollage } from '../../services/api';++/**+ * Board-level "Collage" control: compiles every image (plus sampled video+ * frames) into one near-square grid image saved to the gallery.+ */+export default function MoodBoardCollagePanel({ board, onBoardChange }) {+ const items = Array.isArray(board?.items) ? board.items : [];+ const hasVideo = items.some((it) => it.type === 'video');+ const hasVisual = items.some((it) => it.type === 'image' || it.type === 'video');+ const [framesPerVideo, setFramesPerVideo] = useState(3);+ const [addFramesToBoard, setAddFramesToBoard] = useState(false);+ const [building, setBuilding] = useState(false);+ const [result, setResult] = useState(null);++ if (!hasVisual) return null;++ const handleBuild = async () => {+ setBuilding(true);+ const res = await composeMoodBoardCollage(+ board.id,+ { framesPerVideo, addFramesToBoard: hasVideo && addFramesToBoard },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Could not build collage'); return null; });+ setBuilding(false);+ if (!res) return;+ setResult(res);+ if (res.board && addFramesToBoard) onBoardChange?.(res.board);+ toast.success(`Collage built: ${res.cols}×${res.rows} grid, ${res.cells} image${res.cells === 1 ? '' : 's'}`);+ };++ return (+ <div className="bg-port-card border border-port-border rounded-md p-3 space-y-3" aria-label="Collage">+ <div className="flex flex-wrap items-end gap-3">+ <h2 className="text-sm font-medium text-white flex items-center gap-1.5 mr-2 self-center">+ <LayoutGrid className="w-4 h-4" aria-hidden="true" /> Collage+ </h2>+ {hasVideo ? (+ <>+ <div>+ <label htmlFor="collage-frames" className="block text-xs text-gray-400 mb-1">Frames per video</label>+ <input+ id="collage-frames"+ type="number"+ min={1}+ max={24}+ value={framesPerVideo}+ onChange={(e) => setFramesPerVideo(Math.max(1, Math.min(24, Math.floor(Number(e.target.value)) || 1)))}+ className="w-20 bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"+ />+ </div>+ <label htmlFor="collage-add-frames" className="flex items-center gap-2 text-sm text-gray-300 min-h-[40px]">+ <input+ id="collage-add-frames"+ type="checkbox"+ checked={addFramesToBoard}+ onChange={(e) => setAddFramesToBoard(e.target.checked)}+ />+ Also add frames to the board+ </label>+ </>+ ) : null}+ <button+ type="button"+ onClick={handleBuild}+ disabled={building}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ <LayoutGrid className={`w-4 h-4 ${building ? 'animate-pulse' : ''}`} aria-hidden="true" />+ {building ? 'Building…' : 'Build collage'}+ </button>+ </div>+ {result ? (+ <div className="space-y-2">+ <img src={result.url} alt="Board collage" className="w-full max-w-md rounded border border-port-border" />+ <div className="flex items-center gap-3 text-xs text-gray-400">+ <span>{result.width}×{result.height}px · {result.cols}×{result.rows} grid{result.skipped ? ` · ${result.skipped} skipped` : ''}</span>+ <a href={result.url} download={result.filename} className="flex items-center gap-1 text-port-accent hover:underline">+ <Download className="w-3.5 h-3.5" aria-hidden="true" /> Download+ </a>+ </div>+ </div>+ ) : null}+ </div>+ );+}diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 3e1a7bc5f4..37123246d8 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -11,7 +11,7 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, Link } from 'react-router';-import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy, AtSign, Download, Sparkles } from 'lucide-react';+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy, AtSign, Download, Sparkles, Clapperboard } from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';import TabPills from '../components/ui/TabPills';@@ -20,6 +20,7 @@ import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker';import { PromptFromMediaModal } from '../components/media/PromptFromMedia';import MoodBoardStylePanel from '../components/moodBoard/MoodBoardStylePanel';+import MoodBoardCollagePanel from '../components/moodBoard/MoodBoardCollagePanel';import { copyToClipboard } from '../lib/clipboard';import {getMoodBoard,@@ -33,6 +34,7 @@ import {importMoodBoardPinterest,importMoodBoardXPost,localizeMoodBoardMedia,+ extractMoodBoardItemFrames,} from '../services/api';import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';import {@@ -78,6 +80,10 @@ function MoodBoardEditor({ id }) {// persist PATCH updates the board state.const [analyzeItemId, setAnalyzeItemId] = useState(null);+ // Per-video frame extraction: requested frame count + the item in flight.+ const [frameCount, setFrameCount] = useState(4);+ const [extractingItemId, setExtractingItemId] = useState(null);+// Pinterest link/sync.const [pinUrl, setPinUrl] = useState('');const [linking, setLinking] = useState(false);@@ -270,6 +276,18 @@ function MoodBoardEditor({ id }) {: prev));};+ const handleExtractFrames = async (itemId) => {+ if (!mountedRef.current) return;+ setExtractingItemId(itemId);+ const res = await extractMoodBoardItemFrames(id, itemId, frameCount, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Could not extract frames'); return null; });+ if (!mountedRef.current) return;+ setExtractingItemId(null);+ if (!res?.board) return;+ setBoard(res.board);+ toast.success(res.added ? `Added ${res.added} frame${res.added === 1 ? '' : 's'} to the board` : 'Those frames are already on the board');+ };+const handleRemoveItem = async (itemId) => {if (!mountedRef.current) return;setConfirmingItemId(null);@@ -462,6 +480,8 @@ function MoodBoardEditor({ id }) {<MoodBoardStylePanel board={board} onBoardChange={setBoard} />+ <MoodBoardCollagePanel board={board} onBoardChange={setBoard} />+{/* Desktop 2-column layout: items on left, add forms on right column */}<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_380px] xl:grid-cols-[minmax(0,1fr)_400px] gap-6 items-start">{/* Left column: Mood board items */}@@ -616,6 +636,29 @@ function MoodBoardEditor({ id }) {<span className="text-[10px] text-gray-500 truncate" title={item.source}>{item.source}</span>) : <span />}<div className="flex items-center gap-1">+ {videoSrc ? (+ <span className="inline-flex items-center gap-1">+ <input+ type="number"+ min={1}+ max={24}+ value={frameCount}+ aria-label="Frames to extract"+ onChange={(e) => setFrameCount(Math.max(1, Math.min(24, Math.floor(Number(e.target.value)) || 1)))}+ className="w-10 bg-port-bg border border-port-border rounded px-1 py-0.5 text-white text-[11px] outline-none focus:border-port-accent"+ />+ <button+ type="button"+ onClick={() => handleExtractFrames(item.id)}+ disabled={extractingItemId === item.id}+ title={`Extract ${frameCount} frame${frameCount === 1 ? '' : 's'} and add to board`}+ aria-label="Extract frames to board"+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-white disabled:opacity-50 transition-colors"+ >+ <Clapperboard className={`w-3.5 h-3.5 ${extractingItemId === item.id ? 'animate-pulse' : ''}`} aria-hidden="true" />+ </button>+ </span>+ ) : null}{analysisSource ? (<buttontype="button"diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.jsindex ca98671445..46990b1f76 100644--- a/client/src/services/apiMoodBoard.js+++ b/client/src/services/apiMoodBoard.js@@ -119,3 +119,17 @@ export const importMoodBoardXPost = (id, url, options) =>// Resolves `{ board, localized, failed }`.export const localizeMoodBoardMedia = (id, options) =>request(`/mood-boards/${encodeURIComponent(id)}/localize-media`, { method: 'POST', ...options });++export const composeMoodBoardCollage = (id, body, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/collage`, {+ method: 'POST',+ body: JSON.stringify(body ?? {}),+ ...options,+ });++export const extractMoodBoardItemFrames = (id, itemId, count, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}/extract-frames`, {+ method: 'POST',+ body: JSON.stringify({ count }),+ ...options,+ });diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.jsindex 0a3bfc7f8e..26b6badb0d 100644--- a/server/lib/moodBoardValidation.js+++ b/server/lib/moodBoardValidation.js@@ -182,3 +182,17 @@ export const moodBoardItemUpdateSchema = z.object({prompt: promptSchema,analysis: moodBoardItemAnalysisSchema.nullable().optional(),}).strict();++// Collage compilation + video frame extraction. `framesPerVideo` is how many+// evenly spaced frames each video pin contributes to the grid; the per-item+// extract endpoint always appends its frames to the board, so it only takes a+// count. Bounds mirror MAX_FRAMES_PER_VIDEO in moodBoard/collage.js.+export const moodBoardCollageSchema = z.object({+ framesPerVideo: z.number().int().min(1).max(24).optional().default(3),+ addFramesToBoard: z.boolean().optional().default(false),+ cellSize: z.number().int().min(128).max(1024).optional().default(512),+}).strict();++export const moodBoardExtractFramesSchema = z.object({+ count: z.number().int().min(1).max(24),+}).strict();diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.jsindex 5466e8b339..fcd8a5be07 100644--- a/server/routes/moodBoard.js+++ b/server/routes/moodBoard.js@@ -18,6 +18,8 @@ import {moodBoardItemUpdateSchema,moodBoardPinterestLinkSchema,moodBoardXPostImportSchema,+ moodBoardCollageSchema,+ moodBoardExtractFramesSchema,isPaginationRequested,paginateArray,} from '../lib/validation.js';@@ -42,6 +44,8 @@ import {importPrivatePinterestBoard,importXPost,localizeBoardMedia,+ composeBoardCollage,+ extractItemFrames,} from '../services/moodBoard/index.js';const router = Router();@@ -184,4 +188,17 @@ router.post('/:id/localize-media', asyncHandler(async (req, res) => {res.json(await localizeBoardMedia(req.params.id));}));+// Compile every image (and sampled video frames) into one square-ish grid image+// saved to the gallery.+router.post('/:id/collage', asyncHandler(async (req, res) => {+ const data = validateRequest(moodBoardCollageSchema, req.body ?? {});+ res.json(await composeBoardCollage(req.params.id, data));+}));++// Sample N frames from a video pin and append them to the board as image items.+router.post('/:id/items/:itemId/extract-frames', asyncHandler(async (req, res) => {+ const data = validateRequest(moodBoardExtractFramesSchema, req.body);+ res.json(await extractItemFrames(req.params.id, req.params.itemId, data));+}));+export default router;diff --git a/server/routes/moodBoard.test.js b/server/routes/moodBoard.test.jsindex 271ea8e4b6..a60cdee047 100644--- a/server/routes/moodBoard.test.js+++ b/server/routes/moodBoard.test.js@@ -20,6 +20,8 @@ vi.mock('../services/moodBoard/index.js', () => ({unlinkPinterestBoard: vi.fn(),syncPinterestBoard: vi.fn(),importXPost: vi.fn(),+ composeBoardCollage: vi.fn(),+ extractItemFrames: vi.fn(),}));// The synthesis service pulls the aiProvider/promptRunner stack — stub it so@@ -187,4 +189,22 @@ describe('mood-board routes', () => {expect(svc.importXPost).not.toHaveBeenCalled();});});+ describe('collage + frame extraction', () => {+ it('applies collage defaults and rejects out-of-range frame counts', async () => {+ svc.composeBoardCollage.mockResolvedValueOnce({ filename: 'c.jpg' });+ const ok = await request(makeApp()).post('/api/mood-boards/mb-1/collage').send({});+ expect(ok.status).toBe(200);+ expect(svc.composeBoardCollage).toHaveBeenCalledWith('mb-1', { framesPerVideo: 3, addFramesToBoard: false, cellSize: 512 });+ const bad = await request(makeApp()).post('/api/mood-boards/mb-1/collage').send({ framesPerVideo: 99 });+ expect(bad.status).toBe(400);+ });++ it('requires a count for per-item frame extraction', async () => {+ svc.extractItemFrames.mockResolvedValueOnce({ added: 4 });+ const ok = await request(makeApp()).post('/api/mood-boards/mb-1/items/i1/extract-frames').send({ count: 4 });+ expect(ok.status).toBe(200);+ expect(svc.extractItemFrames).toHaveBeenCalledWith('mb-1', 'i1', { count: 4 });+ expect((await request(makeApp()).post('/api/mood-boards/mb-1/items/i1/extract-frames').send({})).status).toBe(400);+ });+ });});diff --git a/server/services/moodBoard/collage.js b/server/services/moodBoard/collage.jsnew file mode 100644index 0000000000..f3ddd08a50--- /dev/null+++ b/server/services/moodBoard/collage.js@@ -0,0 +1,226 @@+/**+ * Mood Board — collage compilation + video frame extraction.+ *+ * `composeBoardCollage` flattens every visual on a board into ONE near-square+ * grid image saved to the gallery. Image pins contribute themselves; video pins+ * are sampled into N evenly spaced frames, each becoming a cell. Text pins and+ * pins with no local file (external URLs not yet re-hosted) are skipped and+ * counted. `extractItemFrames` does the same sampling for a single video pin and+ * appends the frames to the board as image items.+ *+ * ffmpeg/sharp work runs OUTSIDE the board row lock; only the final append is a+ * locked write (store.appendImportedItems), which dedupes on `source`.+ */++import { createHash } from 'crypto';+import { mkdtemp, rm, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, ensureDir, atomicWrite } from '../../lib/fileUtils.js';+import { findFfmpeg, runFfmpegProcess, probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';+import { assetBasename } from '../../lib/localImageFilename.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import { boardItemLocalImage } from './logic.js';+import * as store from './db.js';++export const MAX_FRAMES_PER_VIDEO = 24;+export const DEFAULT_CELL_SIZE = 512;+const MAX_COLLAGE_SIDE_PX = 8192;+const GAP_PX = 4;+const BG = { r: 15, g: 15, b: 15 };+const RESIZE_CONCURRENCY = 6;++/**+ * Grid dimensions that keep the composite as square as possible: the smallest+ * column count whose square covers `count`, then only as many rows as needed+ * (e.g. 5 → 3×2, 10 → 4×3, 16 → 4×4). Cells are square, so the image aspect+ * follows the grid aspect.+ */+export function squareGridDims(count) {+ const n = Math.max(1, Math.floor(count) || 1);+ const cols = Math.ceil(Math.sqrt(n));+ return { cols, rows: Math.ceil(n / cols) };+}++/** Evenly spaced sample times — the midpoint of each of `count` equal segments. */+export function frameSampleTimes(durationSec, count) {+ return Array.from({ length: count }, (_, i) => ((i + 0.5) * durationSec) / count);+}++function videoFilename(item) {+ if (item?.type !== 'video' || typeof item.mediaKey !== 'string' || !item.mediaKey.startsWith('video:')) return null;+ return assetBasename(item.mediaKey.slice('video:'.length)) || null;+}++async function requireBoard(boardId) {+ const board = await store.getBoard(boardId);+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ return board;+}++/**+ * Sample `count` frames from a local video into `outDir` as `<prefix><i>.jpg`.+ * Returns the written paths in timeline order. Throws a 422 when ffmpeg is+ * missing, the file is unreadable, or no frame could be decoded.+ */+async function sampleVideoFrames(videoFile, count, outDir, prefix) {+ const videoPath = safeUnder(PATHS.videos, videoFile);+ if (!videoPath) throw new ServerError('Invalid video reference', { status: 400, code: 'VALIDATION_ERROR' });+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw new ServerError('ffmpeg is not installed', { status: 422, code: 'FFMPEG_MISSING' });+ const duration = await probeVideoDuration(videoPath);+ if (!duration) throw new ServerError('Could not read that video (missing or unreadable)', { status: 422, code: 'VIDEO_UNREADABLE' });++ const times = frameSampleTimes(duration, count);+ const paths = [];+ for (let i = 0; i < times.length; i++) {+ const out = join(outDir, `${prefix}${i + 1}.jpg`);+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: ['-ss', times[i].toFixed(3), '-i', videoPath, '-frames:v', '1', '-q:v', '3', '-y', out],+ stderrTailBytes: 0,+ });+ if (result.ok) paths.push(out);+ }+ if (!paths.length) throw new ServerError('No frames could be extracted from that video', { status: 422, code: 'FRAME_EXTRACT_FAILED' });+ return paths;+}++/** Copy sampled frames into the gallery under stable, content-keyed names. */+async function storeFramesInGallery(paths, videoFile, count) {+ await ensureDir(PATHS.images);+ const key = createHash('sha1').update(`${videoFile}|${count}`).digest('hex').slice(0, 12);+ const names = [];+ for (let i = 0; i < paths.length; i++) {+ const name = `board-frame-${key}-${i + 1}of${count}.jpg`;+ await atomicWrite(join(PATHS.images, name), await readFile(paths[i]));+ names.push(name);+ }+ return names;+}++/**+ * Extract `count` frames from one video pin and append them to the board as+ * image items. Re-running with the same count is a no-op (source-deduped).+ * Returns `{ board, added, frames }`.+ */+export async function extractItemFrames(boardId, itemId, { count }) {+ const board = await requireBoard(boardId);+ const item = (board.items || []).find((it) => it.id === itemId);+ if (!item) throw new ServerError('Item not found', { status: 404, code: 'NOT_FOUND' });+ const file = videoFilename(item);+ if (!file) throw new ServerError('Only video items can have frames extracted', { status: 400, code: 'VALIDATION_ERROR' });++ const tmp = await mkdtemp(join(tmpdir(), 'portos-board-frames-'));+ try {+ const paths = await sampleVideoFrames(file, count, tmp, 'f');+ const names = await storeFramesInGallery(paths, file, count);+ const imported = names.map((name, i) => ({+ type: 'image',+ imageUrl: `/data/images/${name}`,+ source: `frame:${file}#${i + 1}of${count}`,+ caption: item.caption ? `${item.caption} (frame ${i + 1}/${count})` : `Frame ${i + 1}/${count} of ${file}`,+ }));+ const { board: next, added } = await store.appendImportedItems(boardId, imported);+ if (added) emitRecordUpdated('moodBoard', boardId);+ console.log(`🎞️ Mood board ${boardId}: extracted ${names.length} frame(s) from ${file}, added ${added}`);+ return { board: next, added, frames: names };+ } finally {+ await rm(tmp, { recursive: true, force: true }).catch(() => {});+ }+}++async function resizeCell(source, cell) {+ return sharp(source).rotate().resize(cell, cell, { fit: 'cover', position: 'centre' }).jpeg({ quality: 90 }).toBuffer();+}++/**+ * Compile the whole board into one square-ish grid image in the gallery.+ * Options: `framesPerVideo` (frames sampled from each video pin),+ * `addFramesToBoard` (also append those frames as board items), `cellSize`.+ * Returns `{ filename, url, width, height, cols, rows, cells, skipped, board }`.+ */+export async function composeBoardCollage(boardId, { framesPerVideo, addFramesToBoard = false, cellSize = DEFAULT_CELL_SIZE }) {+ const board = await requireBoard(boardId);+ const items = Array.isArray(board.items) ? board.items : [];+ const tmp = await mkdtemp(join(tmpdir(), 'portos-board-collage-'));+ try {+ const sources = []; // file paths or Buffers, in board order+ const imported = [];+ let skipped = 0;++ for (const item of items) {+ if (item.type === 'image') {+ const local = boardItemLocalImage(item);+ const dir = local?.kind === 'image' ? PATHS.images : local?.kind === 'image-ref' ? PATHS.imageRefs : null;+ const path = dir ? safeUnder(dir, local.filename) : null;+ if (path) sources.push(path); else skipped += 1;+ } else if (item.type === 'video') {+ const file = videoFilename(item);+ if (!file) { skipped += 1; continue; }+ const frames = await sampleVideoFrames(file, framesPerVideo, tmp, `${item.id}-`).catch((err) => {+ console.warn(`⚠️ Mood board ${boardId}: collage skipped video ${file}: ${err.message}`);+ return [];+ });+ if (!frames.length) { skipped += 1; continue; }+ sources.push(...frames);+ if (addFramesToBoard) {+ const names = await storeFramesInGallery(frames, file, framesPerVideo);+ names.forEach((name, i) => imported.push({+ type: 'image',+ imageUrl: `/data/images/${name}`,+ source: `frame:${file}#${i + 1}of${framesPerVideo}`,+ caption: item.caption ? `${item.caption} (frame ${i + 1}/${framesPerVideo})` : `Frame ${i + 1}/${framesPerVideo} of ${file}`,+ }));+ }+ } // text pins carry no image — not a collage cell, not counted as skipped+ }++ if (!sources.length) throw new ServerError('This board has no local images or videos to compile', { status: 422, code: 'NOTHING_TO_COMPOSE' });++ const { cols, rows } = squareGridDims(sources.length);+ const cell = Math.max(64, Math.min(cellSize, Math.floor((MAX_COLLAGE_SIDE_PX - GAP_PX * (cols + 1)) / cols)));+ const width = cols * cell + GAP_PX * (cols + 1);+ const height = rows * cell + GAP_PX * (rows + 1);++ const buffers = [];+ for (let i = 0; i < sources.length; i += RESIZE_CONCURRENCY) {+ const batch = sources.slice(i, i + RESIZE_CONCURRENCY);+ const results = await Promise.all(batch.map((s) => resizeCell(s, cell).catch(() => null)));+ buffers.push(...results);+ }+ const composites = buffers.filter(Boolean);+ skipped += buffers.length - composites.length;+ if (!composites.length) throw new ServerError('None of the board images could be decoded', { status: 422, code: 'NOTHING_TO_COMPOSE' });++ // Re-pack decoded cells so a failed decode leaves no hole, centering a short last row.+ const placed = composites.map((input, idx) => {+ const row = Math.floor(idx / cols);+ const inRow = row === rows - 1 ? composites.length - row * cols : cols;+ const offset = Math.floor(((cols - inRow) * (cell + GAP_PX)) / 2);+ return { input, left: GAP_PX + offset + (idx % cols) * (cell + GAP_PX), top: GAP_PX + row * (cell + GAP_PX) };+ });++ const jpeg = await sharp({ create: { width, height, channels: 3, background: BG } })+ .composite(placed)+ .jpeg({ quality: 90 })+ .toBuffer();++ await ensureDir(PATHS.images);+ const filename = `board-collage-${boardId.replace(/[^A-Za-z0-9]/g, '').slice(0, 12)}-${Date.now()}.jpg`;+ await atomicWrite(join(PATHS.images, filename), jpeg);++ let nextBoard = board;+ if (imported.length) {+ const res = await store.appendImportedItems(boardId, imported);+ nextBoard = res.board;+ if (res.added) emitRecordUpdated('moodBoard', boardId);+ }+ console.log(`🧩 Mood board ${boardId}: collage ${cols}x${rows} (${composites.length} cells, ${skipped} skipped) → ${filename}`);+ return { filename, url: `/data/images/${filename}`, width, height, cols, rows, cells: composites.length, skipped, board: nextBoard };+ } finally {+ await rm(tmp, { recursive: true, force: true }).catch(() => {});+ }+}diff --git a/server/services/moodBoard/collage.test.js b/server/services/moodBoard/collage.test.jsnew file mode 100644index 0000000000..a7e31f4451--- /dev/null+++ b/server/services/moodBoard/collage.test.js@@ -0,0 +1,27 @@+import { describe, it, expect } from 'vitest';+import { squareGridDims, frameSampleTimes } from './collage.js';++describe('squareGridDims', () => {+ it.each([+ [1, 1, 1], [2, 2, 1], [4, 2, 2], [5, 3, 2], [9, 3, 3], [10, 4, 3], [16, 4, 4], [17, 5, 4],+ ])('%i cells → %i cols × %i rows', (n, cols, rows) => {+ expect(squareGridDims(n)).toEqual({ cols, rows });+ });++ it('never leaves a wholly empty row and always covers the count', () => {+ for (let n = 1; n <= 200; n++) {+ const { cols, rows } = squareGridDims(n);+ expect(cols * rows).toBeGreaterThanOrEqual(n);+ expect((rows - 1) * cols).toBeLessThan(n);+ expect(cols - rows).toBeGreaterThanOrEqual(0);+ expect(cols - rows).toBeLessThanOrEqual(1);+ }+ });+});++describe('frameSampleTimes', () => {+ it('samples segment midpoints, staying inside the clip', () => {+ expect(frameSampleTimes(10, 4)).toEqual([1.25, 3.75, 6.25, 8.75]);+ expect(frameSampleTimes(5, 1)).toEqual([2.5]);+ });+});diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex 9e6e0130b2..d250552ee7 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -48,6 +48,9 @@ export { importXPost } from './xPost.js';// Re-host external image URLs into the local gallery (boards never serve remote URLs).export { localizeBoardMedia } from './localize.js';+// Collage compilation + video frame extraction (fires its own federation emits).+export { composeBoardCollage, extractItemFrames } from './collage.js';+// Announce a newly-created board to the per-record peer-sync pipeline: emit the// 'updated' event so any existing subscription pushes it, AND auto-subscribe// every moodBoards-enabled peer so brand-new boards (and their later tombstones)