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: drop the media index row when an image or video is deleted (#2738)
[._.]/ Adam Eivy332b2060b2b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 004c906690..3f38e7886e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -48,6 +48,7 @@- A Creative Director project no longer wedges in "Planning" when its agent is interrupted or crashes mid-run. The stuck run is now cleaned up as soon as the dead agent is detected, so the project can retry on its own instead of waiting for the next server restart.- The Creative Director "Runs" tab now shows why a run failed (e.g. "interrupted by restart") instead of leaving failed runs blank with no explanation.- Creative Director agents are no longer told to run `/do:push` (or open a pull request) when they finish. A CD agent's job is to write its plan or update a scene over the API, not to change code — so the end-of-task "commit and push" instruction was wrong and just made the agent load that command for nothing. They now get a completion step that matches what they actually do.+- [issue-2738] **Deleting an image or video now drops your media asset count right away, instead of waiting for a restart.** The media index kept a row for every deleted asset until the next boot swept it up, so the Character sheet's Auteur skill and Media Assets tile — both of which count that index — kept counting media you'd already thrown away. Deletes now retire the row with the file, including for downloaded videos. The boot sweep stays as the backstop for anything removed outside PortOS (a file deleted straight off disk never runs a delete). A failing index removal can't fail the delete itself: the file is already gone, so the row just waits for the next sweep exactly as it used to.## Character Sheetdiff --git a/server/services/imageGen/deleteImage.test.js b/server/services/imageGen/deleteImage.test.jsnew file mode 100644index 0000000000..0dedb74c2b--- /dev/null+++ b/server/services/imageGen/deleteImage.test.js@@ -0,0 +1,91 @@+/**+ * Gallery image delete → media-asset-index delete hook (#2738).+ *+ * deleteImage unlinks real files, so PATHS.images is redirected at a temp+ * gallery (same pattern as saveUploadedGalleryImage.test.js) — this suite must+ * never touch the repo's real data/images. The index module is mocked: the+ * contract under test is the WIRING (the delete path calls the hook, with the+ * gallery filename, and survives a failing hook), not the SQL — db.test.js+ * covers the row/count side against a real table.+ */++import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';++let imagesDir;+vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: () => imagesDir,+ extraOverrides: () => ({ images: imagesDir }),+ });+});++// local.js imports pythonSetup at load; stub it so the module loads without+// resolving a real venv (mirrors local.test.js).+vi.mock('../../lib/pythonSetup.js', () => ({+ resolveFlux2Python: () => null,+ FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',+}));++const unindexImage = vi.fn(async () => {});+vi.mock('../mediaAssetIndex/index.js', () => ({ unindexImage }));++let tmpRoot;+let priorRegistryEnv;+let deleteImage;++beforeAll(async () => {+ tmpRoot = mkdtempSync(join(tmpdir(), 'portos-gallery-delete-test-'));+ imagesDir = join(tmpRoot, 'images');+ priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;+ process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRoot, 'media-models.json');+ vi.resetModules();+ ({ deleteImage } = await import('./local.js'));+});++afterAll(() => {+ if (priorRegistryEnv === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;+ else process.env.PORTOS_MEDIA_MODELS_FILE = priorRegistryEnv;+ rmSync(tmpRoot, { recursive: true, force: true });+});++beforeEach(() => {+ vi.clearAllMocks();+ rmSync(imagesDir, { recursive: true, force: true });+});++// Seed a gallery image + its sidecar in the temp dir.+function seedImage(filename) {+ mkdirSync(imagesDir, { recursive: true });+ writeFileSync(join(imagesDir, filename), 'not-a-real-png');+ writeFileSync(join(imagesDir, filename.replace('.png', '.metadata.json')), JSON.stringify({ prompt: 'p' }));+}++describe('deleteImage → media asset index delete hook', () => {+ it('unindexes the deleted image by its gallery filename', async () => {+ seedImage('img-1.png');+ const res = await deleteImage('img-1.png');++ expect(res).toEqual({ ok: true });+ expect(existsSync(join(imagesDir, 'img-1.png'))).toBe(false);+ // The ref must be the gallery filename — the key the index wrote the row under.+ expect(unindexImage).toHaveBeenCalledWith('img-1.png');+ });++ it('is non-fatal: a failing index removal still deletes the file and returns ok', async () => {+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ unindexImage.mockRejectedValueOnce(new Error('db down'));+ seedImage('img-2.png');++ // The file is already gone by the time the hook runs — a throwing index must+ // never turn a successful delete into a 500.+ await expect(deleteImage('img-2.png')).resolves.toEqual({ ok: true });+ expect(existsSync(join(imagesDir, 'img-2.png'))).toBe(false);+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('db down'));+ errSpy.mockRestore();+ });+});diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex bbf6d7264b..ee2d3de06b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -992,6 +992,15 @@ export async function deleteImage(filename) {await unlink(join(PATHS.images, filename)).catch(() => {});await unlink(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});await unlink(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});+ // Drop the derived index row with the file (#2738). Without this the row+ // survives until the next boot reconcile, so anything counting the index+ // (the Character sheet's Auteur skill / Media Assets tile) reads high in+ // between. Non-fatal + dynamically imported: a broken index must never fail+ // the user's delete, and this keeps the pg stack out of this module's static+ // graph (the mirror of how the index dynamically imports the media stack).+ await import('../mediaAssetIndex/index.js')+ .then((m) => m.unindexImage(filename))+ .catch((err) => console.error(`❌ Media index image delete hook: ${err.message}`));console.log(`🗑️ Deleted image: ${filename}`);return { ok: true };}diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsindex e23bb68094..edced24f12 100644--- a/server/services/mediaAssetIndex/db.js+++ b/server/services/mediaAssetIndex/db.js@@ -4,10 +4,15 @@* Writes the `media_assets` table. This table is a DERIVED index over media* that lives on disk, so the write surface is small:* - upsertAsset(row) — index/refresh one asset (the live hook + reconcile)- * - removeAsset(mediaKey) — drop one asset's row (delete hook, future slice)+ * - removeAsset(mediaKey) — drop one asset's row. Driven by the live delete+ * hooks (index.js unindexImage/unindexVideo), so a+ * row dies with its file rather than lingering+ * until the next boot (#2738).* - reconcileMediaAssets() — full sweep: upsert every on-disk asset, prune* rows whose backing file is gone. Idempotent and- * cheap to re-run; called at boot.+ * cheap to re-run; called at boot. Still the+ * backstop for OUT-OF-BAND removals (a file+ * deleted off-disk never runs a delete hook).* - listAssets(...) — query helper (no consumer reads it for* correctness yet; here for the follow-up slices* that make collections/catalog resolve through it)diff --git a/server/services/mediaAssetIndex/db.test.js b/server/services/mediaAssetIndex/db.test.jsindex 15c50692c0..4e111c24bf 100644--- a/server/services/mediaAssetIndex/db.test.js+++ b/server/services/mediaAssetIndex/db.test.js@@ -102,6 +102,26 @@ describe.skipIf(!dbReady)('media asset index DB round-trip', () => {await db.removeAsset(key);});+ it('a delete-hook removal drops the count immediately, with no reconcile (#2738)', async () => {+ // The acceptance criterion for the delete hooks, end-to-end against a real+ // table: index an asset exactly as the completed-hook does (imageToRow /+ // videoToRow), then remove it by the key the DELETE path derives+ // (imageMediaKey / videoMediaKey). If those two derivations ever diverge the+ // DELETE misses and the count stays high — which is the bug #2738 fixed.+ const { imageToRow, videoToRow, imageMediaKey, videoMediaKey } = await import('./logic.js');+ const before = await db.countAssets();++ await db.upsertAsset(imageToRow({ filename: `${PFX}del.png`, createdAt: '2026-01-01T00:00:00.000Z' }));+ await db.upsertAsset(videoToRow({ id: `${PFX}delvid`, filename: `${PFX}delvid.mp4`, createdAt: '2026-01-02T00:00:00.000Z' }));+ expect(await db.countAssets()).toBe(before + 2);++ await db.removeAsset(imageMediaKey(`${PFX}del.png`));+ expect(await db.countAssets()).toBe(before + 1);+ // Keyed by job id, not filename — deleting by the filename must NOT be what works.+ await db.removeAsset(videoMediaKey(`${PFX}delvid`));+ expect(await db.countAssets()).toBe(before);+ });+it('reconcile upserts on-disk assets and prunes stale rows (injected readers)', async () => {// Pre-seed a stale row that won't be in the injected "disk" set.await db.upsertAsset({ mediaKey: `image:${PFX}stale.png`, kind: 'image', ref: `${PFX}stale.png`, data: { filename: `${PFX}stale.png` }, createdAt: '2026-01-01T00:00:00.000Z' });diff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.jsindex 5a9030b071..ce534a93dd 100644--- a/server/services/mediaAssetIndex/index.js+++ b/server/services/mediaAssetIndex/index.js@@ -7,6 +7,8 @@* to the existing image/video `completed` events so a freshly generated* asset is indexed immediately, then runs a full reconcile so the index* matches disk regardless of any events missed while the server was down.+ * - unindexImage() / unindexVideo() — the delete-side mirror of those hooks,+ * called by the media delete paths so a row dies with its file (#2738).* - The reconcile + row I/O live in db.js; the pure transforms in logic.js.** No hot-path generator edits: we hang off the `imageGenEvents` /@@ -21,8 +23,8 @@import { checkHealth, ensureSchema } from '../../lib/db.js';import { imageGenEvents } from '../imageGenEvents.js';import { videoGenEvents } from '../videoGen/events.js';-import { upsertAsset, reconcileMediaAssets } from './db.js';-import { imageToRow, videoToRow } from './logic.js';+import { upsertAsset, removeAsset, reconcileMediaAssets } from './db.js';+import { imageMediaKey, imageToRow, videoMediaKey, videoToRow } from './logic.js';export { reconcileMediaAssets } from './db.js';@@ -64,6 +66,32 @@ async function onVideoCompleted({ generationId } = {}) {await upsertAsset(row).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));}+// Drop one row, non-fatally. The delete paths call this AFTER the file is+// already gone, so a failure here must never surface to the user — the row just+// lingers until the next boot reconcile prunes it, i.e. exactly the old+// behavior. Skipped under the escape hatch, where there's no index to maintain.+async function unindexKey(mediaKey, kind) {+ if (!mediaKey || isEscapeHatch()) return;+ await removeAsset(mediaKey).catch((err) => console.error(`❌ Media index ${kind} remove failed: ${err.message}`));+}++/**+ * Drop a deleted image's row. `filename` is the gallery filename — the same ref+ * onImageCompleted indexed it under, so the key matches the row that was written.+ * Never throws.+ */+export async function unindexImage(filename) {+ await unindexKey(imageMediaKey(filename), 'image');+}++/**+ * Drop a deleted video's row. `id` is the job id (NOT the filename) — the same+ * ref onVideoCompleted indexed it under. Never throws.+ */+export async function unindexVideo(id) {+ await unindexKey(videoMediaKey(id), 'video');+}+/*** Boot init: subscribe the completed-hooks (once) + run a full reconcile.* No-op under the escape hatch or when Postgres is unreachable (the boot DBdiff --git a/server/services/mediaAssetIndex/index.test.js b/server/services/mediaAssetIndex/index.test.jsindex 93df886a48..3cec395c08 100644--- a/server/services/mediaAssetIndex/index.test.js+++ b/server/services/mediaAssetIndex/index.test.js@@ -8,13 +8,14 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const upsertAsset = vi.fn(async () => {});+const removeAsset = vi.fn(async () => {});const reconcileMediaAssets = vi.fn(async () => ({ ok: true, indexed: 0, pruned: 0 }));const checkHealth = vi.fn(async () => ({ connected: true }));const ensureSchema = vi.fn(async () => {});const readImageSidecar = vi.fn(async () => ({ metadata: { prompt: 'p', createdAt: '2026-01-01T00:00:00.000Z' } }));const loadHistory = vi.fn(async () => ([{ id: 'job-1', filename: 'job-1.mp4', createdAt: '2026-01-02T00:00:00.000Z' }]));-vi.mock('./db.js', () => ({ upsertAsset, reconcileMediaAssets, removeAsset: vi.fn() }));+vi.mock('./db.js', () => ({ upsertAsset, reconcileMediaAssets, removeAsset }));vi.mock('../../lib/db.js', () => ({ checkHealth, ensureSchema }));vi.mock('../imageGen/local.js', () => ({ readImageSidecar, listGallery: vi.fn(async () => []) }));vi.mock('../videoGen/local.js', () => ({ loadHistory }));@@ -76,3 +77,54 @@ describe('initMediaAssetIndex', () => {vi.unstubAllEnvs();});});++describe('unindexImage / unindexVideo (delete hooks, #2738)', () => {+ // The whole point of the hook: the key it deletes must be the key the upsert+ // hook wrote, or the delete silently misses and the row lingers to the next+ // boot. Pin both halves against the SAME asset rather than a hardcoded string.+ it('removes exactly the key the completed hook indexed', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ const { initMediaAssetIndex, unindexImage, unindexVideo } = await import('./index.js');+ await initMediaAssetIndex();++ imageGenEvents.emit('completed', { generationId: 'g1', filename: 'img-1.png' });+ videoGenEvents.emit('completed', { generationId: 'job-1', filename: 'job-1.mp4' });+ await flush();+ const indexedKeys = upsertAsset.mock.calls.map(([row]) => row.mediaKey);++ await unindexImage('img-1.png');+ await unindexVideo('job-1');+ expect(removeAsset.mock.calls.map(([key]) => key)).toEqual(indexedKeys);+ // A video is keyed by job id, NOT its filename — the easy derivation to get wrong.+ expect(removeAsset).toHaveBeenCalledWith('video:job-1');+ vi.unstubAllEnvs();+ });++ it('is non-fatal: a failing removal does not reject the caller (the delete already happened)', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ removeAsset.mockRejectedValueOnce(new Error('db down'));+ const { unindexImage } = await import('./index.js');++ await expect(unindexImage('img-1.png')).resolves.toBeUndefined();+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('db down'));+ errSpy.mockRestore();+ vi.unstubAllEnvs();+ });++ it('no-ops under the escape hatch and on an unusable ref', async () => {+ vi.stubEnv('NODE_ENV', 'test');+ const { unindexImage } = await import('./index.js');+ await unindexImage('img-1.png');+ expect(removeAsset).not.toHaveBeenCalled();+ vi.unstubAllEnvs();++ // A ref-less asset never produced a row, so there's nothing to delete.+ vi.stubEnv('NODE_ENV', 'production');+ const { unindexImage: liveUnindex, unindexVideo: liveUnindexVideo } = await import('./index.js');+ await liveUnindex(undefined);+ await liveUnindexVideo('');+ expect(removeAsset).not.toHaveBeenCalled();+ vi.unstubAllEnvs();+ });+});diff --git a/server/services/mediaAssetIndex/logic.js b/server/services/mediaAssetIndex/logic.jsindex 29c58ba4b0..5c7d8e2002 100644--- a/server/services/mediaAssetIndex/logic.js+++ b/server/services/mediaAssetIndex/logic.js@@ -18,6 +18,18 @@import { itemKey } from '../../lib/mediaItemKey.js';import { mirrorTimestamp } from '../../lib/pgTimestamp.js';+// The one place each kind's ref is turned into a media_key. Both the row+// builders (which WRITE rows) and the delete hooks (which REMOVE them) derive+// their key here, so an unindex can never miss the row its upsert wrote.+// Returns null for an unusable ref, so callers can filter/no-op on it.+const mediaKeyFor = (kind, ref) => (typeof ref === 'string' && ref ? itemKey({ kind, ref }) : null);++/** media_key for a generated image. Its ref is the gallery FILENAME. */+export const imageMediaKey = (filename) => mediaKeyFor('image', filename);++/** media_key for a generated video. Its ref is the job ID, not the filename. */+export const videoMediaKey = (id) => mediaKeyFor('video', id);+/*** Build an index row for a generated image. `item` is a gallery entry as* produced by imageGen listGallery() — `{ filename, createdAt, ...sidecar }` —@@ -26,10 +38,11 @@ import { mirrorTimestamp } from '../../lib/pgTimestamp.js';*/export function imageToRow(item, { now } = {}) {const ref = item?.filename;- if (typeof ref !== 'string' || !ref) return null;+ const mediaKey = imageMediaKey(ref);+ if (!mediaKey) return null;const fallback = now || new Date().toISOString();return {- mediaKey: itemKey({ kind: 'image', ref }),+ mediaKey,kind: 'image',ref,data: item,@@ -45,10 +58,11 @@ export function imageToRow(item, { now } = {}) {*/export function videoToRow(entry, { now } = {}) {const ref = entry?.id;- if (typeof ref !== 'string' || !ref) return null;+ const mediaKey = videoMediaKey(ref);+ if (!mediaKey) return null;const fallback = now || new Date().toISOString();return {- mediaKey: itemKey({ kind: 'video', ref }),+ mediaKey,kind: 'video',ref,data: entry,diff --git a/server/services/videoDownload.js b/server/services/videoDownload.jsindex 24e6d287cf..1a48556ddd 100644--- a/server/services/videoDownload.js+++ b/server/services/videoDownload.js@@ -85,8 +85,8 @@ export async function listDownloads() {/*** Delete a downloaded video. Verifies the id is actually a download (not a* generated render) before delegating to the shared deleteHistoryItem, which- * removes the file, thumbnail, and history entry. The next mediaAssetIndex- * reconcile prunes its row (identical lifecycle to a deleted generation).+ * removes the file, thumbnail, history entry, and mediaAssetIndex row+ * (identical lifecycle to a deleted generation).*/export async function deleteDownload(id) {const history = await loadHistory().catch(() => []);diff --git a/server/services/videoGen/deleteHistoryItem.test.js b/server/services/videoGen/deleteHistoryItem.test.jsnew file mode 100644index 0000000000..1d5c1ac76c--- /dev/null+++ b/server/services/videoGen/deleteHistoryItem.test.js@@ -0,0 +1,110 @@+/**+ * Video delete → media-asset-index delete hook (#2738).+ *+ * Focused wiring suite: the contract is that deleteHistoryItem hands the index+ * the JOB ID (not the filename — the index keys videos by id) and survives a+ * failing hook. Disk + history are fully mocked, so nothing here touches real+ * videos; db.test.js covers the row/count side against a real table.+ *+ * `deleteDownload` (videoDownload.js) delegates straight to deleteHistoryItem,+ * so downloads inherit this hook — no separate wiring.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { join } from 'path';++const MOCK_PATHS = {+ root: '/mock/root',+ data: '/mock/data',+ videos: '/mock/data/videos',+ images: '/mock/data/images',+ videoThumbnails: '/mock/data/video-thumbnails',+ uploads: '/mock/data/uploads',+ loras: '/mock/data/loras',+};++vi.mock('../../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn(async () => null),+ ensureDir: vi.fn(async () => {}),+ PATHS: MOCK_PATHS,+ readJSONFile: vi.fn(async () => []),+ atomicWrite: vi.fn(async () => {}),+ assertSafeFilename: vi.fn(),+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,+}));++vi.mock('../../lib/mediaModels.js', () => ({+ getVideoModels: vi.fn(() => []),+ getDefaultVideoModelId: vi.fn(() => 'ltx2_unified'),+ getTextEncoderRepo: vi.fn(() => 'some/text-encoder'),+}));++vi.mock('../../lib/sseUtils.js', () => ({+ broadcastSse: vi.fn(),+ attachSseClient: vi.fn(() => true),+ closeJobAfterDelay: vi.fn(),+ PYTHON_NOISE_RE: /^\s*$/,+}));++vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),+ safeUnder: vi.fn((base, file) => (file ? join(base, file) : null)),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ optimizeForStreaming: vi.fn(async () => {}),+ upscaleVideo2x: vi.fn(async () => ({ ok: true })),+ extractEvaluationFrames: vi.fn(async () => []),+}));++vi.mock('../../lib/hfToken.js', () => ({+ hfTokenEnv: vi.fn(async () => ({})),+ getHfToken: vi.fn(async () => null),+}));++const unlink = vi.fn(async () => {});+vi.mock('fs/promises', () => ({ unlink, writeFile: vi.fn(async () => {}), copyFile: vi.fn(async () => {}) }));+vi.mock('fs', () => ({ existsSync: vi.fn(() => true), statSync: vi.fn(() => ({ size: 1000 })) }));++// The history store the delete reads/writes. mutateVideoHistory applies the+// mutator to the live list so the test can assert the entry really left.+let history = [];+const loadHistory = vi.fn(async () => history.slice());+const mutateVideoHistory = vi.fn(async (fn) => { history = fn(history.slice()); return history; });+vi.mock('./history.js', () => ({ loadHistory, mutateVideoHistory, saveHistory: vi.fn(async () => {}) }));++const unindexVideo = vi.fn(async () => {});+vi.mock('../mediaAssetIndex/index.js', () => ({ unindexVideo }));++const { deleteHistoryItem } = await import('./local.js');++beforeEach(() => {+ vi.clearAllMocks();+ history = [{ id: 'job-1', filename: 'job-1.mp4', thumbnail: 'job-1.jpg', createdAt: '2026-01-01T00:00:00.000Z' }];+});++describe('deleteHistoryItem → media asset index delete hook', () => {+ it('unindexes the deleted video by its JOB ID, not its filename', async () => {+ const res = await deleteHistoryItem('job-1');++ expect(res).toEqual({ ok: true });+ expect(history).toEqual([]);+ // videoToRow keys a video row `video:<id>`, so the delete must pass the id.+ // Passing item.filename here would DELETE NOTHING and leave the row stale.+ expect(unindexVideo).toHaveBeenCalledWith('job-1');+ expect(unindexVideo).not.toHaveBeenCalledWith('job-1.mp4');+ });++ it('is non-fatal: a failing index removal still removes the entry and returns ok', async () => {+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ unindexVideo.mockRejectedValueOnce(new Error('db down'));++ await expect(deleteHistoryItem('job-1')).resolves.toEqual({ ok: true });+ expect(history).toEqual([]);+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('db down'));+ errSpy.mockRestore();+ });++ it('never reaches the index for an unknown id (404 before any hook)', async () => {+ await expect(deleteHistoryItem('nope')).rejects.toThrow('Not found');+ expect(unindexVideo).not.toHaveBeenCalled();+ });+});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex fafaaa6c8b..c96889698f 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -1693,6 +1693,12 @@ export async function deleteHistoryItem(id) {// Serialized removal through the shared tail (re-filters the freshest list),// so a concurrent download/render append isn't dropped by this save.await mutateVideoHistory((h) => h.filter((x) => x.id !== id));+ // Drop the derived index row with the entry (#2738) — keyed by job id, the+ // ref the index wrote it under. Non-fatal + dynamically imported; see the+ // matching hook in imageGen/local.js#deleteImage for the rationale.+ await import('../mediaAssetIndex/index.js')+ .then((m) => m.unindexVideo(id))+ .catch((err) => console.error(`❌ Media index video delete hook: ${err.message}`));console.log(`🗑️ Deleted video: ${item.filename}`);return { ok: true };}