Skip to content

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

address review (codex): PM2 custom-home starts, install race, CI deleted-path selectors, style-reference purge/race

[._.]/ Adam Eivy94f8626ab1da
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index 71891be22a..f42aa76c89 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -90,6 +90,15 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
const savedDraftSnapshotRef = useRef(universeDraftSnapshot(createEmptyUniverseDraft()));
const savedStyleSnapshotRef = useRef(ensureInfluences(createEmptyUniverseDraft().influences));
const pendingCanonAdditionsRef = useRef(emptyPendingCanon());
+ // Serializes removeStyleReference calls and tracks the array across them —
+ // draftRef only syncs after a React effect, which can still be one render
+ // behind when two removals fire before either PATCH resolves; both would
+ // otherwise derive their replacement array from the same stale list and the
+ // second request's wholesale-replace PATCH would silently restore the item
+ // the first request just removed. Reset whenever the selected universe
+ // changes (see the selectedId-load effect below).
+ const styleReferenceQueueRef = useRef(Promise.resolve());
+ const styleReferenceSnapshotRef = useRef(null);
useEffect(() => () => { mountedRef.current = false; }, []);
useEffect(() => { draftRef.current = draft; }, [draft]);
@@ -147,6 +156,11 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
setPendingDeleteId(null);
setCanonDirty(false);
clearPendingCanonAdditions();
+ // A new selection means any in-flight removeStyleReference chain belongs
+ // to the PREVIOUS universe — reset so the next removal seeds its snapshot
+ // from the freshly-hydrated draft instead of a stale/foreign one.
+ styleReferenceQueueRef.current = Promise.resolve();
+ styleReferenceSnapshotRef.current = null;
if (!selectedId) {
const empty = createEmptyUniverseDraft();
setDraft(empty);
@@ -334,23 +348,36 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
return true;
}, [draft, markStyleGuidanceSaved, selectedId]);
- const removeStyleReference = useCallback(async (referenceId) => {
- if (!selectedId) return false;
- const current = draftRef.current || draft;
- const styleReferences = (current.styleReferences || []).filter((item) => item.id !== referenceId);
- const updated = await updateUniverse(selectedId, { styleReferences }, { silent: true }).catch((error) => {
- toast.error(`Reference removal failed: ${error.message}`);
- return null;
+ const removeStyleReference = useCallback((referenceId) => {
+ if (!selectedId) return Promise.resolve(false);
+ // Chain onto the queue so a second removal clicked before the first PATCH
+ // resolves derives its replacement array from the FIRST removal's actual
+ // result (tracked in styleReferenceSnapshotRef), not from draftRef — which
+ // only syncs one React effect later and would still show both items present.
+ const task = styleReferenceQueueRef.current.then(async () => {
+ const base = styleReferenceSnapshotRef.current
+ ?? (draftRef.current || draft).styleReferences
+ ?? [];
+ const styleReferences = base.filter((item) => item.id !== referenceId);
+ const updated = await updateUniverse(selectedId, { styleReferences }, { silent: true }).catch((error) => {
+ toast.error(`Reference removal failed: ${error.message}`);
+ return null;
+ });
+ if (!updated) return false;
+ styleReferenceSnapshotRef.current = updated.styleReferences || [];
+ setDraft((latest) => ({
+ ...latest,
+ styleReferences: updated.styleReferences || [],
+ updatedAt: updated.updatedAt,
+ }));
+ setWorlds((previous) => upsertByIdPrepend(previous, updated));
+ toast.success('Art reference removed');
+ return true;
});
- if (!updated) return false;
- setDraft((latest) => ({
- ...latest,
- styleReferences: updated.styleReferences || [],
- updatedAt: updated.updatedAt,
- }));
- setWorlds((previous) => upsertByIdPrepend(previous, updated));
- toast.success('Art reference removed');
- return true;
+ // Keep the queue alive even if this removal failed, so the NEXT removal
+ // still runs (in its turn) rather than inheriting a rejected chain.
+ styleReferenceQueueRef.current = task.catch(() => {});
+ return task;
}, [draft, selectedId]);
const handleCanonChange = useCallback((updated) => {
diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsx
index b98d87e743..08c9683abb 100644
--- a/client/src/hooks/useUniverseDraft.test.jsx
+++ b/client/src/hooks/useUniverseDraft.test.jsx
@@ -162,4 +162,27 @@ describe('useUniverseDraft', () => {
expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [] });
expect(result.current.draft.styleReferences).toEqual([]);
});
+
+ it('removes both references when two removals are triggered before either PATCH resolves', async () => {
+ const refA = { id: 'style-ref-a', title: 'Ref A', prompt: 'moody', imageRefs: ['a.png'] };
+ const refB = { id: 'style-ref-b', title: 'Ref B', prompt: 'bright', imageRefs: ['b.png'] };
+ apiMocks.getUniverse.mockResolvedValueOnce({ ...universe, styleReferences: [refA, refB] });
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refA, refB]));
+
+ // Both removals derive their PATCH from the ARRAY THE SERVER LAST CONFIRMED
+ // (the queue's tracked snapshot), not from a shared stale `draft` read at
+ // call time — otherwise the second request's wholesale-replace payload
+ // would still include refA (or refB) and silently restore it on resolve.
+ await act(async () => {
+ const first = result.current.removeStyleReference(refA.id);
+ const second = result.current.removeStyleReference(refB.id);
+ await Promise.all([first, second]);
+ });
+
+ expect(apiMocks.updateUniverse).toHaveBeenCalledTimes(2);
+ expect(apiMocks.updateUniverse.mock.calls[0][1]).toEqual({ styleReferences: [refB] });
+ expect(apiMocks.updateUniverse.mock.calls[1][1]).toEqual({ styleReferences: [] });
+ expect(result.current.draft.styleReferences).toEqual([]);
+ });
});
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index ca875d1aa4..35b67c5432 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -205,7 +205,10 @@ export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = f
return fullPlan(changed, `wide change (${executable.length} executable files)`);
}
- const directTests = executable.filter(isTestFile);
+ // `changed` includes deleted paths (diff-filter ACMRD), but a deleted test
+ // file passed as an exact Vitest selector makes the runner exit non-zero on
+ // an otherwise-valid deletion PR — trackedSet (git ls-files) excludes it.
+ const directTests = executable.filter(isTestFile).filter((path) => trackedSet.has(path));
const sourceFiles = executable.filter((path) => !isTestFile(path));
const unsupportedSources = sourceFiles.filter((path) => (
!isServerRunnerFile(path) && !path.startsWith('client/')
@@ -260,8 +263,10 @@ export function buildCiTestPlan(changedFiles, { trackedFiles = [], forceFull = f
client,
db: executable.some((path) => DB_RISK_RULES.some((rule) => rule.test(path))),
lint: {
- mode: changed.some((path) => CLIENT_LINT_RE.test(path)) ? 'files' : 'skip',
- files: changed.filter((path) => CLIENT_LINT_RE.test(path)),
+ // Same deleted-path guard as directTests above — ESLint given a
+ // nonexistent explicit path exits non-zero instead of skipping it.
+ mode: changed.some((path) => CLIENT_LINT_RE.test(path) && trackedSet.has(path)) ? 'files' : 'skip',
+ files: changed.filter((path) => CLIENT_LINT_RE.test(path) && trackedSet.has(path)),
},
build: hasClientSource,
smoke: hasServerSource,
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index e519c9a157..7ef5806abc 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -13,8 +13,10 @@ const TRACKED = [
'server/services/sprites/atlasGrid.test.js',
'server/services/sprites/atlasLayout.test.js',
'client/src/a11yConventions.test.js',
+ 'client/src/components/catalog/CatalogCard.jsx',
'client/src/components/catalog/CatalogCard.test.jsx',
'client/src/components/sprites/WalkWorkflow.test.jsx',
+ 'client/src/lib/catalogLinks.js',
'client/src/lib/index.test.js',
'client/src/services/apiSprites.test.js',
'scripts/migrations/210-example.test.js',
@@ -149,6 +151,26 @@ describe('CI test impact planner', () => {
});
});
+ it('excludes a deleted test file from the exact server selector list, and a deleted client file from lint', () => {
+ // `changed` includes deleted paths (diff-filter ACMRD), but neither
+ // `TRACKED` (git ls-files) nor the trackedFiles fixture below lists them
+ // — a deletion-only PR must not hand a nonexistent path to Vitest/ESLint
+ // as an exact selector, which exits non-zero on a perfectly valid PR.
+ const plan = buildCiTestPlan([
+ 'server/services/sprites/atlas.test.js', // deleted alongside its source
+ 'client/src/components/catalog/CatalogCard.test.jsx', // deleted test
+ 'client/src/lib/catalogLinks.js', // deleted lint-relevant client file
+ ], { trackedFiles: TRACKED.filter((path) => ![
+ 'server/services/sprites/atlas.test.js',
+ 'client/src/components/catalog/CatalogCard.test.jsx',
+ 'client/src/lib/catalogLinks.js',
+ ].includes(path)) });
+
+ expect(plan.full).toBe(false);
+ expect(plan.server.files).not.toContain('server/services/sprites/atlas.test.js');
+ expect(plan.lint.files).not.toContain('client/src/lib/catalogLinks.js');
+ });
+
it('falls back to full CI for unknown artifacts and wide changes', () => {
const unknown = buildCiTestPlan(['data.reference/bootstrap.bin'], {
trackedFiles: TRACKED,
diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.js
index d0d32c2d18..c2a57a8f08 100644
--- a/server/routes/apps/lifecycle.js
+++ b/server/routes/apps/lifecycle.js
@@ -53,7 +53,7 @@ async function launchDesktopProcess(app, processName, command) {
processName,
app.repoPath,
command,
- { autorestart: false }
+ { autorestart: false, pm2Home: app.pm2Home }
).catch(err => ({ success: false, error: err.message }));
}
@@ -150,7 +150,7 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {
results[name] = await launchDesktopProcess(app, name, command);
continue;
}
- const result = await pm2Service.startWithCommand(name, app.repoPath, command, {})
+ const result = await pm2Service.startWithCommand(name, app.repoPath, command, { pm2Home: app.pm2Home })
.catch(err => ({ success: false, error: err.message }));
results[name] = result;
}
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 22a0474b1d..5c5a9901f3 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -97,6 +97,21 @@ describe('Apps Lifecycle Routes', () => {
);
});
+ it('starts the native target in the app\'s own PM2 home', async () => {
+ appsService.getAppById.mockResolvedValue({ ...mockApp, pm2Home: '/tmp/example-pm2' });
+ pm2Service.getAppStatus.mockResolvedValue({ status: 'stopped' });
+ pm2Service.deleteApp.mockResolvedValue({ success: true });
+ pm2Service.startWithCommand.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/app-001/native-launch');
+
+ expect(response.status).toBe(200);
+ expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
+ 'mixed-game', '/tmp', './scripts/game run', { autorestart: false, pm2Home: '/tmp/example-pm2' }
+ );
+ });
+
it('does not open a second native window while one is launching', async () => {
appsService.getAppById.mockResolvedValue(mockApp);
pm2Service.getAppStatus.mockResolvedValue({ status: 'launching' });
@@ -178,6 +193,27 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(404);
});
+ it('starts a command-based app (no ecosystem config) in its own PM2 home', async () => {
+ const mockApp = {
+ id: 'app-001',
+ name: 'Test App',
+ repoPath: '/path/to/repo',
+ pm2ProcessNames: ['test-app'],
+ startCommands: ['npm run dev'],
+ pm2Home: '/tmp/example-pm2'
+ };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ pm2Service.startWithCommand.mockResolvedValue({ success: true });
+ history.logAction.mockResolvedValue();
+
+ const response = await request(app).post('/api/apps/app-001/start');
+
+ expect(response.status).toBe(200);
+ expect(pm2Service.startWithCommand).toHaveBeenCalledWith(
+ 'test-app', '/path/to/repo', 'npm run dev', { pm2Home: '/tmp/example-pm2' }
+ );
+ });
+
it('launches a desktop app from its startCommands with autorestart OFF (#2991)', async () => {
const mockApp = {
id: 'game-001',
diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.js
index a2f40cbd83..2dc257948e 100644
--- a/server/routes/imageTo3d.js
+++ b/server/routes/imageTo3d.js
@@ -132,6 +132,20 @@ async function handleTargetInstall(targetId, req, res) {
// finished on its own and blocking every later Install click.
let currentKill = null;
let aborted = false;
+ // `adapter.install()` itself can run an async preflight (e.g. a toolchain
+ // probe) BEFORE returning { promise, kill } — during that window `currentKill`
+ // is still null, so a naive close handler would release the slot even though
+ // the adapter may already be spawning its first child. Track that window
+ // explicitly so the slot is held through it, and release exactly once via a
+ // single guarded function — never eagerly in the close handler for a window
+ // where nothing is killable yet AND an install may already be starting.
+ let installStarting = false;
+ let slotReleased = false;
+ const releaseSlot = () => {
+ if (slotReleased) return;
+ slotReleased = true;
+ installsInFlight.delete(targetId);
+ };
req.on('close', () => {
aborted = true;
installLog.cancel();
@@ -142,17 +156,18 @@ async function handleTargetInstall(targetId, req, res) {
// terminate, but let the install promise's own `.finally()` (below)
// release the slot once the kill actually lands — releasing it here,
// before the child has exited, would let a second install for the same
- // target start while the first is still shutting down, and this
- // handler's own delete would then race the first install's delayed
- // `.finally()`, which could clobber the second install's slot when it
- // settles.
+ // target start while the first is still shutting down.
currentKill();
- } else {
- // Nothing has spawned yet (still resolving env / adapter preflight) —
- // the code below will see `aborted` and bail without ever registering
- // a `.finally()`, so release the slot here or it would leak forever.
- installsInFlight.delete(targetId);
+ } else if (!installStarting) {
+ // Nothing has spawned yet (still resolving env) — the code below will
+ // see `aborted` and bail without ever registering a `.finally()`, so
+ // release the slot here or it would leak forever.
+ releaseSlot();
}
+ // Else: `adapter.install()`'s own preflight is in flight and `kill` isn't
+ // available yet — do NOT release here. The code right after that await
+ // (below) sees `aborted` and calls `kill()` + `releaseSlot()` itself once
+ // it actually has something to kill.
safeEnd();
});
@@ -167,18 +182,24 @@ async function handleTargetInstall(targetId, req, res) {
} catch (err) {
console.error(`❌ ${target.label} install could not resolve its environment: ${err.message}`);
emit({ type: 'error', message: `Could not prepare the ${target.label} install environment: ${err.message}` });
- installsInFlight.delete(targetId);
+ releaseSlot();
return safeEnd();
}
// The client hung up during the await — don't start a multi-GB install nobody
// is listening to.
if (aborted) return safeEnd();
+ installStarting = true;
const { promise, kill } = await adapter.install({ onEvent: emit, env: installEnv });
// The client may have hung up while the adapter ran its own async preflight
// (e.g. a toolchain probe) — terminate whatever it just spawned rather than
- // let an orphaned install run unattended.
- if (aborted) return kill();
+ // let an orphaned install run unattended, and release the slot now that we
+ // finally have something to kill (the close handler deliberately did not).
+ if (aborted) {
+ kill();
+ releaseSlot();
+ return;
+ }
currentKill = kill;
promise
.then(() => installLog.success())
@@ -193,7 +214,7 @@ async function handleTargetInstall(targetId, req, res) {
})
.finally(() => {
currentKill = null;
- installsInFlight.delete(targetId);
+ releaseSlot();
safeEnd();
});
}
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 1e5cbd4749..a19e5b3c9d 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -489,14 +489,22 @@ export async function getLogs(name, lines = 100, pm2Home = null) {
* restart-tuning fields (max_restarts/min_uptime/restart_delay) are omitted in
* that mode since they only apply when autorestart is on.
* @param {number} [options.maxRestarts=10] Restart cap when autorestart is on.
+ * @param {string} [options.pm2Home=null] Custom PM2_HOME. When set, starts via
+ * CLI (like deleteApp/getAppStatus) instead of the default-daemon Node API —
+ * otherwise the process would launch under PortOS's own PM2 daemon and be
+ * invisible to every subsequent status/log/delete call that targets pm2Home.
*/
export async function startWithCommand(name, cwd, command, options = {}) {
- const { autorestart = true, maxRestarts = 10 } = options;
+ const { autorestart = true, maxRestarts = 10, pm2Home = null } = options;
// Parse with quote-awareness so `node --opt "arg with spaces"` survives;
// a bare split(' ') would shred quoted segments. PM2 accepts `args` as an
// array, which avoids re-joining and re-splitting on the way through.
const [script, ...args] = parseCommandArgs(command);
+ if (pm2Home) {
+ return spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home });
+ }
+
return connectAndRun((pm2) => {
return new Promise((resolve, reject) => {
const opts = {
@@ -532,6 +540,34 @@ export async function startWithCommand(name, cwd, command, options = {}) {
});
}
+/**
+ * CLI-based counterpart to startWithCommand's Node-API path, used whenever a
+ * custom pm2Home is given. `min_uptime` has no CLI flag equivalent — it only
+ * tunes the autorestart=true nursing behavior, which no current caller uses
+ * together with a custom pm2Home.
+ */
+function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home }) {
+ return new Promise((resolve, reject) => {
+ const cliArgs = ['start', script, '--name', name, '--cwd', cwd];
+ if (!isJsScript(script)) cliArgs.push('--interpreter', 'none');
+ if (autorestart) {
+ cliArgs.push('--max-restarts', String(maxRestarts), '--restart-delay', '5000', '--max-memory-restart', '500M');
+ } else {
+ cliArgs.push('--no-autorestart');
+ }
+ if (args.length > 0) cliArgs.push('--', ...args);
+
+ const child = spawnPm2(cliArgs, { env: buildEnv(pm2Home) });
+ let stderr = '';
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
+ child.on('close', (code) => {
+ if (code !== 0) return reject(new Error(stderr || `pm2 start exited with code ${code}`));
+ resolve({ success: true });
+ });
+ child.on('error', reject);
+ });
+}
+
/**
* Spawn pm2 start with an ecosystem config file
* @param {string} cwd Working directory
diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.js
index ba617e7e43..0b003665c2 100644
--- a/server/services/pm2.launch.test.js
+++ b/server/services/pm2.launch.test.js
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { EventEmitter } from 'events';
const mockPm2 = vi.hoisted(() => ({
connect: vi.fn(),
@@ -8,13 +9,29 @@ const mockPm2 = vi.hoisted(() => ({
vi.mock('pm2', () => ({ default: mockPm2 }));
+const mockSpawn = vi.hoisted(() => vi.fn());
+vi.mock('child_process', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: mockSpawn,
+}));
+
import { startApp, startWithCommand } from './pm2.js';
+// Fake child_process.spawn result: closes with the given exit code on next tick.
+function fakeChild(exitCode = 0) {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ queueMicrotask(() => child.emit('close', exitCode));
+ return child;
+}
+
describe('PM2 command launch interpreters', () => {
beforeEach(() => {
vi.clearAllMocks();
mockPm2.connect.mockImplementation(callback => callback(null));
mockPm2.start.mockImplementation((options, callback) => callback(null, options));
+ mockSpawn.mockImplementation(() => fakeChild(0));
});
it('executes shell-script commands directly instead of parsing them with Node', async () => {
@@ -50,4 +67,45 @@ describe('PM2 command launch interpreters', () => {
interpreter: 'none'
}), expect.any(Function));
});
+
+ describe('with a custom pm2Home', () => {
+ it('starts via the PM2 CLI (not the default-daemon Node API) so the process is visible to CLI-based status/log/delete calls targeting the same home', async () => {
+ const result = await startWithCommand(
+ 'elsewhere-acres-godot',
+ '/repo/elsewhere-acres',
+ './scripts/game run',
+ { autorestart: false, pm2Home: '/tmp/example-pm2' }
+ );
+
+ expect(result).toEqual({ success: true });
+ expect(mockPm2.start).not.toHaveBeenCalled();
+ expect(mockSpawn).toHaveBeenCalledTimes(1);
+ const [, spawnArgv, spawnOpts] = mockSpawn.mock.calls[0];
+ const pm2Args = spawnArgv.slice(1); // spawnArgv[0] is the local pm2 CLI binary path
+ expect(pm2Args).toEqual(expect.arrayContaining([
+ 'start', './scripts/game', '--name', 'elsewhere-acres-godot',
+ '--cwd', '/repo/elsewhere-acres', '--interpreter', 'none', '--no-autorestart',
+ ]));
+ expect(pm2Args.slice(-2)).toEqual(['--', 'run']);
+ expect(spawnOpts.env.PM2_HOME).toBe('/tmp/example-pm2');
+ });
+
+ it('rejects when the pm2 CLI exits non-zero', async () => {
+ mockSpawn.mockImplementation(() => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ queueMicrotask(() => {
+ child.stderr.emit('data', Buffer.from('pm2 blew up'));
+ child.emit('close', 1);
+ });
+ return child;
+ });
+
+ await expect(startWithCommand(
+ 'elsewhere-acres-godot', '/repo/elsewhere-acres', './scripts/game run',
+ { autorestart: false, pm2Home: '/tmp/example-pm2' }
+ )).rejects.toThrow(/pm2 blew up|exited with code 1/);
+ });
+ });
});
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 9b87f24809..a4b74e2b60 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -589,8 +589,14 @@ export async function setCanonKindLockAll(universeId, kind, locked) {
/**
* Strip a filename from every `imageRefs[]` across every universe's
- * characters/places/objects. Mirror of the series-side purge so the image-
- * delete route can clean both stores in one pass.
+ * characters/places/objects, and from every top-level `styleReferences[]`
+ * entry. Mirror of the series-side purge so the image-delete route can clean
+ * both stores in one pass.
+ *
+ * A style reference's `imageRefs` is capped to exactly one image
+ * (`sanitizeStyleReference`), and the sanitizer drops the whole entry when
+ * that array is empty — so purging the image removes the entire reference
+ * rather than leaving a dangling title/prompt with no picture to show.
*/
export async function purgeImageRefFromAllUniverses(filename) {
if (!filename || typeof filename !== 'string') return { removed: 0 };
@@ -620,6 +626,17 @@ export async function purgeImageRefFromAllUniverses(filename) {
});
if (keyTouched) patch[key] = nextList;
}
+ const styleReferences = Array.isArray(cur.styleReferences) ? cur.styleReferences : null;
+ if (styleReferences) {
+ const nextStyleReferences = styleReferences.filter((ref) => {
+ const refs = Array.isArray(ref?.imageRefs) ? ref.imageRefs : [];
+ return !refs.includes(filename);
+ });
+ if (nextStyleReferences.length !== styleReferences.length) {
+ perUniverse += styleReferences.length - nextStyleReferences.length;
+ patch.styleReferences = nextStyleReferences;
+ }
+ }
return Object.keys(patch).length > 0 ? patch : null;
});
removed += perUniverse;
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 1091a583a1..c4c5521886 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -541,4 +541,27 @@ describe('universeCanon — purgeImageRefFromAllUniverses', () => {
expect(await canonSvc.purgeImageRefFromAllUniverses('')).toEqual({ removed: 0 });
expect(await canonSvc.purgeImageRefFromAllUniverses(null)).toEqual({ removed: 0 });
});
+
+ it('removes an art style reference whose sole image is deleted, so no dangling reference survives', async () => {
+ const w = await svc.createUniverse({
+ name: 'Test Universe',
+ starterPrompt: 'test seed',
+ stylePrompt: 'test style',
+ });
+ // sanitizeStyleReference caps imageRefs to exactly one image, so purging
+ // it must drop the whole entry — a title/prompt with no picture is dead.
+ await svc.updateUniverse(w.id, {
+ styleReferences: [
+ { title: 'Ref A', prompt: 'moody lighting', imageRefs: ['shared.png'] },
+ { title: 'Ref B', prompt: 'bright palette', imageRefs: ['other.png'] },
+ ],
+ });
+
+ const result = await canonSvc.purgeImageRefFromAllUniverses('shared.png');
+ expect(result.removed).toBe(1);
+
+ const reread = (await svc.listUniverses()).find((u) => u.id === w.id);
+ expect(reread.styleReferences).toHaveLength(1);
+ expect(reread.styleReferences[0].title).toBe('Ref B');
+ });
});