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(media): one collection per world + Clean buttons in all image lightboxes
Adam Eivyc6c90ac7c5d6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 62f31f9548..fab821f80e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,8 @@## Changed+- **World Builder batch render reuses one collection per world.** Auto-generated collection names drop the ` — YYYY-MM-DD HH:MM` suffix: a batch render of "Echoes of the Choir" now files into `World: Echoes of the Choir` every time instead of minting a fresh date-stamped bucket. A user-supplied `collectionName` also flows through find-or-create (case-insensitive trimmed match), so repeat renders into a custom name append into the same collection. Backed by a new `findOrCreateCollectionByName()` helper in `server/services/mediaCollections.js`. One-shot migration at `data/migrations/001-merge-worldbuilder-collections.js` collapses legacy date-suffixed `World: <name> — <date>` collections into their base name (dedupes items by `kind:ref`, preserves the earliest `createdAt`, rewrites `world-builder.json` `runs[].collectionId` references). Run via `npm run migrations`; idempotent.+- **Clean → Light / Aggressive available beyond Image Gen.** The Eraser pill that strips render artifacts now appears in any image lightbox: Media History and Media Collection Detail both wire `onClean` into `MediaLightbox`. Cleaning from inside a collection automatically adds the cleaned file to that collection alongside the original, so the user can compare side-by-side before deciding which to keep. (Image Gen behaviour unchanged; Video Gen's lightbox only renders videos so it intentionally doesn't expose Clean.)- **MediaCard thumbnails.** Removed the "IMAGE"/"VIDEO" badge overlay from the bottom-right of media cards — the icon and aspect already convey the kind, and the badge added visual noise on grid views.- **Pipeline Series page — two-pane layout.** PipelineSeries (`/pipeline/series/:id`) drops its `max-w-5xl` cap and splits into a sticky left bible sidebar + right card-grid canvas at `lg+`. The bible inputs (name / format / logline / target issue count / premise / style notes / world / characters) live in the sidebar; issues/episodes render as a responsive card grid (1/2/3/4 cols across breakpoints) showing number, status badge, title (line-clamped), and `updated <timeAgo>`. Sidebar collapses to a 48px rail via a panel toggle (state persists in `localStorage` under `portos-pipeline-series-sidebar-collapsed`) so the canvas can use the full viewport when you're deep in episode work. Mobile (< lg) stays single-column with the sidebar reflowing above the canvas. Phase 1 of the Pipeline Story-Arc Planning initiative — pure UI refactor, no schema or API change; subsequent phases evolve the card grid into an Arc → Season → Episode tree.diff --git a/.gitignore b/.gitignoreindex fb47e14288..c4f2839834 100644--- a/.gitignore+++ b/.gitignore@@ -5,8 +5,14 @@ node_modules/dist/build/-# Runtime data (contains app registry, history, runs)-data/+# Runtime data (app registry, history, runs). Override the directory-level+# `data/` rule from the global ~/.gitignore so git descends into data/ and+# evaluates the negations below; then re-exclude everything inside, and+# re-include the source-controlled migration scripts.+!data/+data/*+!data/migrations/+data/migrations/.applied.json# Environment files.envdiff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex 216cc007ea..9f89150d81 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -7,8 +7,9 @@ import MediaLightbox from '../components/media/MediaLightbox';import { normalizeImage, normalizeVideo } from '../components/media/normalize';import {getMediaCollection, updateMediaCollection,- removeMediaCollectionItem, listImageGallery, listVideoHistory,- extractLastFrame,+ addMediaCollectionItem, removeMediaCollectionItem,+ listImageGallery, listVideoHistory,+ extractLastFrame, cleanGalleryImage,} from '../services/api';// Hydrate a collection's "<kind>:<ref>" pointer list into the same@@ -115,6 +116,27 @@ export default function MediaCollectionDetail() {if (item.height) params.set('h', String(item.height));navigate(`/media/video?${params.toString()}`);};+ const handleClean = async (img, level) => {+ if (!img?.filename) throw new Error('Missing filename');+ const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {+ toast.error(err.message || 'Failed to clean image');+ throw err;+ });+ const updated = await addMediaCollectionItem(collection.id, {+ kind: 'image',+ ref: cleaned.filename,+ }).catch(() => null);+ if (updated) setCollection(updated);+ // Seed imagesByName so hydrate() can render the cleaned file immediately+ // — without this the next render misses it until refresh() reruns.+ setImagesByName((m) => {+ const next = new Map(m);+ next.set(cleaned.filename, cleaned);+ return next;+ });+ toast.success(`Cleaned (${level}) → ${cleaned.filename}`);+ };+const handleContinue = async (item) => {const { filename } = await extractLastFrame(item.id).catch((err) => {toast.error(err.message || 'Failed to extract last frame');@@ -208,6 +230,7 @@ export default function MediaCollectionDetail() {onRemix={preview.kind === 'image' ? (i) => handleRemix(i) : undefined}onSendToVideo={preview.kind === 'image' ? (i) => handleSendToVideo(i) : undefined}onContinue={preview.kind === 'video' ? (i) => handleContinue(i.raw || i) : undefined}+ onClean={preview.kind === 'image' ? (i, level) => handleClean(i?.raw || i, level) : undefined}/>)}</div>diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex 14e6ac5bba..eed124961b 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -16,7 +16,7 @@ import { getMediaNavProps } from '../lib/mediaNavigation';import {listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,upscaleVideo,- listImageGallery, deleteImage,+ listImageGallery, deleteImage, cleanGalleryImage,} from '../services/api';const FILTERS = [@@ -142,6 +142,17 @@ export default function MediaHistory() {}};+ const handleClean = async (img, level) => {+ if (!img?.filename) throw new Error('Missing filename');+ const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {+ toast.error(err.message || 'Failed to clean image');+ throw err;+ });+ const normalized = normalizeImage(cleaned);+ setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);+ toast.success(`Cleaned (${level}) → ${cleaned.filename}`);+ };+const handleRemix = (item) => {const params = new URLSearchParams();if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);@@ -296,6 +307,7 @@ export default function MediaHistory() {onRemix={handleRemix}onSendToVideo={handleSendToVideo}onContinue={handleContinue}+ onClean={(item, level) => handleClean(item?.raw, level)}{...previewNavProps}/></div>diff --git a/data/migrations/001-merge-worldbuilder-collections.js b/data/migrations/001-merge-worldbuilder-collections.jsnew file mode 100644index 0000000000..dae245ae69--- /dev/null+++ b/data/migrations/001-merge-worldbuilder-collections.js@@ -0,0 +1,166 @@+/**+ * One-shot merge of legacy World Builder collections.+ *+ * The pre-merge render route minted a fresh collection named+ * `World: <world name> — YYYY-MM-DD HH:MM`+ * on every batch render. The new route reuses a single `World: <world name>`+ * bucket per world. This migration collapses the legacy date-suffixed rows+ * into one bucket per base name, dedupes items, and rewrites every+ * World Builder run whose collectionId pointed at a removed row.+ *+ * Idempotent — a re-run finds no date-suffixed names and exits cleanly.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const ITEMS_MAX = 5000;+const NAME_MAX_LENGTH = 80;++// Match "World: <base> — YYYY-MM-DD[ HH:MM]". The em-dash is U+2014 with+// surrounding ASCII spaces, matching the pre-merge `worldBuilder.js` format.+const DATE_SUFFIX_RE = /^(World: .+?)\s+—\s+\d{4}-\d{2}-\d{2}(?:\s+\d{2}:\d{2})?$/;++const itemKey = (it) => `${it.kind}:${it.ref}`;++const readJson = async (path, fallback) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return fallback;+ return JSON.parse(raw);+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++export default {+ async up({ rootDir }) {+ const collectionsPath = join(rootDir, 'data', 'media-collections.json');+ const runsPath = join(rootDir, 'data', 'world-builder.json');++ const collectionsDoc = await readJson(collectionsPath, { collections: [] });+ const collections = Array.isArray(collectionsDoc.collections)+ ? collectionsDoc.collections+ : [];++ const groups = new Map();+ for (const c of collections) {+ if (!c || typeof c.name !== 'string') continue;+ const m = c.name.match(DATE_SUFFIX_RE);+ if (!m) continue;+ const base = m[1].trim().slice(0, NAME_MAX_LENGTH);+ if (!groups.has(base)) groups.set(base, []);+ groups.get(base).push(c);+ }++ if (groups.size === 0) {+ console.log('🌍 migration: no date-suffixed World collections found, skipping');+ return;+ }++ // remap: removed sourceId -> surviving target id (used to fix run refs).+ const remap = new Map();+ const removedIds = new Set();+ const byId = new Map(collections.map((c) => [c.id, c]));++ for (const [baseName, sources] of groups) {+ // Reuse an already-clean collection if the user renamed one of them+ // manually; otherwise the first source is promoted to the target.+ const sourceSet = new Set(sources);+ const existingTarget = collections.find(+ (c) => !sourceSet.has(c) && typeof c.name === 'string'+ && c.name.toLowerCase() === baseName.toLowerCase(),+ );++ const mergedItems = [];+ const seen = new Set();+ const candidates = existingTarget ? [existingTarget, ...sources] : sources;+ for (const src of candidates) {+ if (!Array.isArray(src.items)) continue;+ for (const it of src.items) {+ if (!it || typeof it.kind !== 'string' || typeof it.ref !== 'string') continue;+ const key = itemKey(it);+ if (seen.has(key)) continue;+ seen.add(key);+ mergedItems.push(it);+ if (mergedItems.length >= ITEMS_MAX) break;+ }+ if (mergedItems.length >= ITEMS_MAX) break;+ }+ // Chronological order so the auto-cover (newest) matches what the+ // live sanitizeCollection picks.+ mergedItems.sort((a, b) => {+ const aT = Date.parse(a.addedAt || '');+ const bT = Date.parse(b.addedAt || '');+ return (Number.isFinite(aT) ? aT : 0) - (Number.isFinite(bT) ? bT : 0);+ });++ const allCreatedAts = candidates+ .map((c) => Date.parse(c.createdAt || ''))+ .filter(Number.isFinite);+ const earliestCreatedAt = allCreatedAts.length+ ? new Date(Math.min(...allCreatedAts)).toISOString()+ : new Date().toISOString();++ const target = existingTarget ?? sources[0];+ const targetId = target.id;+ const itemKeys = new Set(mergedItems.map(itemKey));+ const coverKey =+ typeof target.coverKey === 'string' && itemKeys.has(target.coverKey)+ ? target.coverKey+ : null;++ byId.set(targetId, {+ ...target,+ id: targetId,+ name: baseName,+ description: target.description || `World Builder renders for "${baseName.replace(/^World:\s*/, '')}"`,+ coverKey,+ items: mergedItems,+ createdAt: earliestCreatedAt,+ updatedAt: new Date().toISOString(),+ });++ for (const src of sources) {+ if (src.id === targetId) continue;+ remap.set(src.id, targetId);+ removedIds.add(src.id);+ byId.delete(src.id);+ }++ console.log(+ `🌍 merged ${sources.length} collection${sources.length === 1 ? '' : 's'} (${mergedItems.length} items) → "${baseName}"`,+ );+ }++ // Preserve original ordering; survivors keep their slot, removed ids drop.+ const nextCollections = [];+ const seenIds = new Set();+ for (const c of collections) {+ if (!c?.id || seenIds.has(c.id) || removedIds.has(c.id)) continue;+ const updated = byId.get(c.id) ?? c;+ seenIds.add(updated.id);+ nextCollections.push(updated);+ }++ await writeJson(collectionsPath, { collections: nextCollections });++ const runsDoc = await readJson(runsPath, null);+ if (runsDoc && Array.isArray(runsDoc.runs) && remap.size) {+ let touched = 0;+ const nextRuns = runsDoc.runs.map((r) => {+ if (!r || typeof r.collectionId !== 'string') return r;+ const target = remap.get(r.collectionId);+ if (!target) return r;+ touched++;+ return { ...r, collectionId: target };+ });+ if (touched > 0) {+ await writeJson(runsPath, { ...runsDoc, runs: nextRuns });+ console.log(`🌍 remapped ${touched} run collectionId reference${touched === 1 ? '' : 's'}`);+ }+ }+ },+};diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex c58b75da30..63341fd339 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -21,7 +21,7 @@ import { expandWorldTemplate } from '../services/worldBuilderExpand.js';import { refineWorldPrompts } from '../services/worldBuilderRefine.js';import { enqueueJob } from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';-import { createCollection, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';+import { findOrCreateCollectionByName, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';const router = Router();@@ -234,12 +234,15 @@ router.post('/:id/render', asyncHandler(async (req, res) => {// Provision the collection up front so renders can be tagged as they// complete. The completion hook (worldBuilderCollectionHook) will add- // each finished image's filename to this collection.+ // each finished image's filename to this collection. Repeat renders of+ // the same world reuse the existing `World: <name>` bucket so per-world+ // output accumulates in one place instead of fragmenting into a fresh+ // date-suffixed collection per run.const collectionName = body.collectionName?.trim()- || `World: ${world.name} — ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`;- const collection = await createCollection({+ || `World: ${world.name}`;+ const collection = await findOrCreateCollectionByName({name: collectionName.slice(0, COLLECTION_NAME_MAX),- description: `World Builder run for "${world.name}" (${compiled.length} prompts)`,+ description: `World Builder renders for "${world.name}"`,});const runId = randomUUID();diff --git a/server/routes/worldBuilder.test.js b/server/routes/worldBuilder.test.jsindex aa29b0ac72..829200402a 100644--- a/server/routes/worldBuilder.test.js+++ b/server/routes/worldBuilder.test.js@@ -48,8 +48,20 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({enqueueJob: vi.fn(({ params }) => ({ jobId: `job-${++uuidCounter}`, position: 1, status: 'queued', params })),}));+// Tiny in-memory store so repeat-render tests can verify the new+// find-or-create semantics (existing name → same collection id).+const collectionsByName = new Map();+const mockCreateRec = (name) => {+ const id = `col-${collectionsByName.size + 1}`;+ const rec = { id, name, items: [] };+ collectionsByName.set(name.toLowerCase(), rec);+ return rec;+};vi.mock('../services/mediaCollections.js', () => ({- createCollection: vi.fn(async ({ name }) => ({ id: 'col-1', name, items: [] })),+ createCollection: vi.fn(async ({ name }) => mockCreateRec(name)),+ findOrCreateCollectionByName: vi.fn(async ({ name }) => {+ return collectionsByName.get(name.toLowerCase()) ?? mockCreateRec(name);+ }),addItem: vi.fn(),ERR_DUPLICATE: 'DUPLICATE',NAME_MAX_LENGTH: 80,@@ -76,6 +88,7 @@ describe('world-builder routes', () => {beforeEach(() => {fileStore.clear();uuidCounter = 0;+ collectionsByName.clear();});it('GET / returns []', async () => {@@ -237,6 +250,45 @@ describe('world-builder routes', () => {expect(res.body.jobIds).toHaveLength(1);});+ it('POST /:id/render reuses the same collection on repeat renders of the same world', async () => {+ const app = buildApp();+ const created = await request(app).post('/api/world-builder').send({+ name: 'Repeat World',+ categories: {+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },+ },+ });+ const first = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local' });+ expect(first.status).toBe(200);+ const second = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local' });+ expect(second.status).toBe(200);+ expect(second.body.collectionId).toBe(first.body.collectionId);+ // The auto-generated name has no date suffix — bare `World: <name>`.+ expect(second.body.collectionName).toBe('World: Repeat World');+ expect(second.body.collectionName).not.toMatch(/\d{4}-\d{2}-\d{2}/);+ });++ it('POST /:id/render reuses an existing collection when collectionName matches', async () => {+ const app = buildApp();+ const created = await request(app).post('/api/world-builder').send({+ name: 'Custom Bucket World',+ categories: {+ landscapes: { variations: [{ label: 'A', prompt: 'a' }] },+ },+ });+ const first = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local', collectionName: 'Shared Bucket' });+ const second = await request(app)+ .post(`/api/world-builder/${created.body.id}/render`)+ .send({ mode: 'local', collectionName: ' shared bucket ' });+ expect(second.body.collectionId).toBe(first.body.collectionId);+ });+it('POST /:id/render rejects when no variations exist', async () => {const app = buildApp();const created = await request(app).post('/api/world-builder').send({ name: 'Empty' });diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 0911f84e8a..e3a6d8502b 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -136,6 +136,35 @@ export async function createCollection({ name, description = '' }) {return next;}+// Find an existing collection by case-insensitive trimmed name, else create+// a fresh one. Lets repeat-render callers (World Builder) append into a+// single per-world bucket without growing a new collection on every run.+export async function findOrCreateCollectionByName({ name, description = '' }) {+ const trimmed = typeof name === 'string' ? name.trim() : '';+ if (!trimmed || trimmed.length > NAME_MAX_LENGTH) {+ throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);+ }+ const trimmedDescription = typeof description === 'string'+ ? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)+ : '';+ const all = await listCollections();+ const needle = trimmed.toLowerCase();+ const existing = all.find((c) => c.name.toLowerCase() === needle);+ if (existing) return existing;+ const now = new Date().toISOString();+ const next = {+ id: randomUUID(),+ name: trimmed,+ description: trimmedDescription,+ coverKey: null,+ items: [],+ createdAt: now,+ updatedAt: now,+ };+ await writeAll([...all, next]);+ return next;+}+export async function updateCollection(id, patch) {const all = await listCollections();const idx = all.findIndex((c) => c.id === id);diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex 391ee8bcd2..3b7c47e0bd 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -74,6 +74,29 @@ describe('mediaCollections service', () => {expect(await svc.listCollections()).toEqual([]);});+ it('findOrCreateCollectionByName returns the existing collection on case-insensitive match', async () => {+ const a = await svc.createCollection({ name: 'World: Foo' });+ const reused = await svc.findOrCreateCollectionByName({ name: ' world: foo ' });+ expect(reused.id).toBe(a.id);+ expect(await svc.listCollections()).toHaveLength(1);+ });++ it('findOrCreateCollectionByName creates a new collection when no name matches', async () => {+ await svc.createCollection({ name: 'World: Foo' });+ const created = await svc.findOrCreateCollectionByName({+ name: 'World: Bar',+ description: 'desc',+ });+ expect(created.name).toBe('World: Bar');+ expect(created.description).toBe('desc');+ expect(await svc.listCollections()).toHaveLength(2);+ });++ it('findOrCreateCollectionByName validates name like createCollection', async () => {+ await expect(svc.findOrCreateCollectionByName({ name: ' ' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });+it('sanitizes hand-edited JSON with bogus items', async () => {fileStore.set('/mock/data/media-collections.json', {collections: [