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: keep a mood board X-import poster another board still uses when the video download fails (#10263)
[._.]/ Adam Eivy6fe9a002d5be
diff --git a/server/services/moodBoard/xPost.js b/server/services/moodBoard/xPost.jsindex eea5d2a515..1f807d1571 100644--- a/server/services/moodBoard/xPost.js+++ b/server/services/moodBoard/xPost.js@@ -16,7 +16,7 @@*/import { createHash } from 'crypto';-import { unlink } from 'fs/promises';+import { access, unlink } from 'fs/promises';import { join, basename } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, detectImageFormat, detectVideoFormat, writeFileGuarded } from '../../lib/fileUtils.js';@@ -42,17 +42,20 @@ function fingerprint(canonicalUrl, tag) {// Download an image (photo or video poster) into data/images/, sniffing the// format from bytes (never trusting Content-Type) — same posture as Pinterest's-// downloadPinImage. Returns the served path, or null on any failure. Both-// downloads are post-keyed, so a re-import rewrites bytes a board may already-// name: each write holds the backup lease (#9982) so it never overlaps a snapshot.+// downloadPinImage. Returns { path, created } (created=false when the post-keyed+// file already existed, so another board may name it), or null on any failure.+// Both downloads are post-keyed, so a re-import rewrites bytes a board may+// already name: each write holds the backup lease (#9982) so it never overlaps a snapshot.async function downloadImage(url, canonicalUrl, tag) {const res = await fetchPublicBinary(url, { timeoutMs: FETCH_TIMEOUT_MS, headers: MEDIA_HEADERS, maxBytes: MAX_IMAGE_BYTES });if (!res?.buffer?.length) return null;const fmt = detectImageFormat(res.buffer);if (!fmt) return null;const filename = `x-${fingerprint(canonicalUrl, tag)}${fmt.ext}`;- await withBackupAssetPublication(() => writeFileGuarded(join(PATHS.images, filename), res.buffer));- return `/data/images/${filename}`;+ const target = join(PATHS.images, filename);+ const created = await access(target).then(() => false, () => true);+ await withBackupAssetPublication(() => writeFileGuarded(target, res.buffer));+ return { path: `/data/images/${filename}`, created };}// Download the post's video/GIF (X serves a looping GIF as an mp4) into@@ -117,8 +120,8 @@ export async function importXPost(boardId, { url }) {for (let i = 0; i < images.length && imported.length < capacity; i++) {const source = `${canonicalUrl}#${i}`;if (seen.has(source)) continue;- const imageUrl = await downloadImage(images[i], canonicalUrl, String(i));- if (imageUrl) imported.push({ type: 'image', imageUrl, source, caption: null });+ const image = await downloadImage(images[i], canonicalUrl, String(i));+ if (image) imported.push({ type: 'image', imageUrl: image.path, source, caption: null });}if (video && imported.length < capacity) {const source = `${canonicalUrl}#video`;@@ -131,12 +134,13 @@ export async function importXPost(boardId, { url }) {video.poster ? downloadImage(video.poster, canonicalUrl, 'poster') : Promise.resolve(null),]);if (filename) {- imported.push({ type: 'video', mediaKey: `video:${filename}`, imageUrl: poster, source, caption: null });- } else if (poster) {+ imported.push({ type: 'video', mediaKey: `video:${filename}`, imageUrl: poster.path, source, caption: null });+ } else if (poster?.created) {// The video failed but its poster downloaded first (they ran in- // parallel) — nothing will ever reference it, so remove it rather- // than leaving an orphaned file in data/images.- await unlink(join(PATHS.images, basename(poster))).catch(() => {});+ // parallel) — nothing will ever reference a poster THIS import created,+ // so remove it rather than leaving an orphan. A poster that already+ // existed may be named by another board's item: leave it alone.+ await withBackupAssetPublication(() => unlink(join(PATHS.images, basename(poster.path)))).catch(() => {});}}}diff --git a/server/services/moodBoard/xPost.test.js b/server/services/moodBoard/xPost.test.jsindex 75a424086e..ae8c4c5dd8 100644--- a/server/services/moodBoard/xPost.test.js+++ b/server/services/moodBoard/xPost.test.js@@ -21,7 +21,9 @@ vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated: (...a) => emitconst writeFile = vi.fn();const unlink = vi.fn(async () => {});-vi.mock('fs/promises', () => ({ writeFile: (...a) => writeFile(...a), unlink: (...a) => unlink(...a) }));+// access resolves = file exists; the default rejects = the target is absent.+const access = vi.fn(async () => { throw new Error('ENOENT'); });+vi.mock('fs/promises', () => ({ writeFile: (...a) => writeFile(...a), unlink: (...a) => unlink(...a), access: (...a) => access(...a) }));// Keep the real detectImageFormat (byte-sniffing) — only override PATHS/ensureDir.vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({...(await importOriginal()),@@ -39,6 +41,7 @@ const CANONICAL = 'https://x.com/i/status/42';beforeEach(() => {vi.clearAllMocks();+ access.mockImplementation(async () => { throw new Error('ENOENT'); });vi.spyOn(console, 'log').mockImplementation(() => {});});@@ -161,4 +164,21 @@ describe('importXPost', () => {expect(deletedPosterPath).toMatch(/^\/tmp\/imgs\/x-[0-9a-f]{16}\.jpg$/);expect(store.appendImportedItems).not.toHaveBeenCalled();});++ it('keeps a poster that already existed (another board may name it) when the video body fails', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ net.fetchPublicText.mockResolvedValue(JSON.stringify({+ video: {+ poster: 'https://pbs.twimg.com/poster.jpg',+ variants: [{ type: 'video/mp4', src: 'https://video.twimg.com/v.mp4', bitrate: 1000 }],+ },+ }));+ net.fetchPublicBinary.mockImplementation(async (url) => (+ url === 'https://video.twimg.com/v.mp4' ? null : { buffer: JPEG_BYTES, contentType: 'image/jpeg' }+ ));+ access.mockResolvedValue(undefined); // poster file pre-exists++ await expect(importXPost('mb-1', { url: POST_URL })).rejects.toMatchObject({ code: 'X_POST_DOWNLOAD_FAILED' });+ expect(unlink).not.toHaveBeenCalled();+ });});