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-boards): re-host external pins into the gallery and compact the board header
[._.]/ Adam Eivy03045d1ed7a8
diff --git a/client/src/components/moodBoard/MoodBoardStylePanel.jsx b/client/src/components/moodBoard/MoodBoardStylePanel.jsxindex 36ba6edf22..4658e8ff36 100644--- a/client/src/components/moodBoard/MoodBoardStylePanel.jsx+++ b/client/src/components/moodBoard/MoodBoardStylePanel.jsx@@ -240,16 +240,16 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {const showCompose = plan.analyzed > 0;return (- <section className="bg-port-card border border-port-border rounded-md p-4 mb-6">- <div className="flex items-center gap-2 mb-1">+ <section className="bg-port-card border border-port-border rounded-md p-3">+ <div className="flex items-center gap-2 mb-2"><ScanEye className="w-4 h-4 text-port-accent" aria-hidden="true" /><h2 className="text-sm font-medium text-white">Board style</h2>+ <span className="text-[11px] text-gray-500 truncate" title="Prompt from media for each gallery item, then one composite style from those prompts. The poster is this board’s canonical reference image.">+ Analyze pins → composite style → poster+ </span></div>- <p className="text-[11px] text-gray-500 mb-3">- Prompt from media for each gallery item, then one composite style from those prompts. The poster is this board’s canonical reference image.- </p>- <div className="flex flex-col sm:flex-row gap-4">- <div className="w-full sm:w-56 shrink-0">+ <div className="flex flex-col sm:flex-row gap-3">+ <div className="w-full sm:w-36 shrink-0"><div className="aspect-[3/2] w-full rounded-md overflow-hidden border border-port-border bg-port-bg">{jobId ? (<MediaJobThumb jobId={jobId} onFilename={handleComplete} size="fill" label="Board poster" />@@ -263,7 +263,7 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {)}</div></div>- <div className="flex-1 min-w-0 space-y-3">+ <div className="flex-1 min-w-0 space-y-2"><ProviderModelSelectorproviders={providers}selectedProviderId={selectedProviderId}@@ -272,7 +272,7 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {onProviderChange={setSelectedProviderId}onModelChange={setSelectedModel}disabled={busy || providersLoading}- layout="stacked"+ layout="row"/>{providers.length === 0 && !providersLoading ? (<p className="text-xs text-port-warning">No vision-capable provider is enabled. Add one under Settings → Providers to analyze items. Composing from analyses you already have still works.</p>@@ -300,37 +300,44 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {</button>) : null}{!showAnalyze && !showCompose ? (- <p className="text-xs text-gray-500">Pin a gallery image or video to analyze this board. External links can’t be read.</p>+ <p className="text-xs text-gray-500">Pin an image or video to analyze this board.</p>) : null}</div>{plan.skipped > 0 ? (<p className="text-[11px] text-gray-500">- {formatCount(plan.skipped)} pin{plan.skipped === 1 ? '' : 's'} {plan.skipped === 1 ? 'is' : 'are'} an external link and can’t be analyzed.+ {formatCount(plan.skipped)} pin{plan.skipped === 1 ? '' : 's'} couldn’t be imported from {plan.skipped === 1 ? 'its' : 'their'} source URL and can’t be analyzed yet.</p>) : null}- <div>- <label htmlFor="board-style-prompt" className="block text-xs text-gray-400 mb-1">Style prompt</label>- <textarea- id="board-style-prompt"- value={prompt}- rows={4}- maxLength={8000}- onChange={(e) => setPrompt(e.target.value)}- placeholder="Compose a style from the item analyses, or write one."- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"- />- </div>- <div>- <label htmlFor="board-style-negative" className="block text-xs text-gray-400 mb-1">Negative prompt</label>- <textarea- id="board-style-negative"- value={negative}- rows={2}- maxLength={8000}- onChange={(e) => setNegative(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"- />- </div>+ <details className="group" open={!savedPrompt}>+ <summary className="cursor-pointer text-xs text-gray-400 hover:text-white select-none">+ Style prompt{savedPrompt ? `: ${savedPrompt.slice(0, 90)}${savedPrompt.length > 90 ? '…' : ''}` : ''}+ </summary>+ <div className="space-y-2 mt-2">+ <div>+ <label htmlFor="board-style-prompt" className="block text-xs text-gray-400 mb-1">Style prompt</label>+ <textarea+ id="board-style-prompt"+ value={prompt}+ rows={4}+ maxLength={8000}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder="Compose a style from the item analyses, or write one."+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"+ />+ </div>+ <div>+ <label htmlFor="board-style-negative" className="block text-xs text-gray-400 mb-1">Negative prompt</label>+ <textarea+ id="board-style-negative"+ value={negative}+ rows={2}+ maxLength={8000}+ onChange={(e) => setNegative(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"+ />+ </div>+ </div>+ </details>{board?.style?.rationale ? (<p className="text-xs text-gray-400">{board.style.rationale}</p>) : null}diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 77a32d0383..5e5c3cc1bd 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -32,6 +32,7 @@ import {syncMoodBoardPinterest,importMoodBoardPinterest,importMoodBoardXPost,+ localizeMoodBoardMedia,} from '../services/api';import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';import { moodBoardAnalysisFromResult } from '../lib/moodBoardAnalysis';@@ -101,6 +102,18 @@ function MoodBoardEditor({ id }) {setName(data.name || '');setDescription(data.description || '');setPinUrl(data.pinterest?.boardUrl || '');+ // Boards never serve remote URLs: re-host any external pins in the+ // background, then swap the localized board in.+ if ((data.items || []).some((it) => /^https?:\/\//i.test(it?.imageUrl || ''))) {+ localizeMoodBoardMedia(id, { silent: true }).then((res) => {+ if (!mountedRef.current || seq !== loadSeqRef.current || !res?.board) return;+ if (res.localized > 0) {+ setBoard(res.board);+ toast.success(`Imported ${res.localized} external image${res.localized === 1 ? '' : 's'} into the gallery`);+ }+ if (res.failed > 0) toast.error(`${res.failed} external image${res.failed === 1 ? '' : 's'} could not be downloaded`);+ }).catch(() => {});+ }} else {setBoard(null);toast.error('Mood board not found');@@ -370,7 +383,7 @@ function MoodBoardEditor({ id }) {);return (- <div className="max-w-7xl mx-auto space-y-6">+ <div className="max-w-7xl mx-auto space-y-4"><buttontype="button"onClick={() => navigate('/mood-boards')}@@ -379,10 +392,10 @@ function MoodBoardEditor({ id }) {<ArrowLeft className="w-4 h-4" aria-hidden="true" /> Boards</button>- {/* Board metadata */}- <div className="bg-port-card border border-port-border rounded-md p-4">- <div className="space-y-3">- <div>+ {/* Board metadata — one compact row on desktop */}+ <div className="bg-port-card border border-port-border rounded-md p-3">+ <div className="flex flex-col md:flex-row md:items-end gap-3">+ <div className="md:w-72 shrink-0"><label htmlFor="board-name" className="block text-xs text-gray-400 mb-1">Name</label><inputid="board-name"@@ -393,27 +406,25 @@ function MoodBoardEditor({ id }) {className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"/></div>- <div>+ <div className="flex-1 min-w-0"><label htmlFor="board-description" className="block text-xs text-gray-400 mb-1">Description</label><textareaid="board-description"value={description}maxLength={5000}- rows={2}+ rows={1}onChange={(e) => setDescription(e.target.value)}className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"/></div>- <div className="flex justify-end">- <button- type="button"- onClick={handleSaveMeta}- disabled={!metaDirty || savingMeta}- 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"- >- <Save className="w-4 h-4" aria-hidden="true" /> Save- </button>- </div>+ <button+ type="button"+ onClick={handleSaveMeta}+ disabled={!metaDirty || savingMeta}+ className="flex items-center justify-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"+ >+ <Save className="w-4 h-4" aria-hidden="true" /> Save+ </button></div></div>diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsxindex 4941900c63..eb088a237b 100644--- a/client/src/pages/MoodBoardDetail.test.jsx+++ b/client/src/pages/MoodBoardDetail.test.jsx@@ -12,6 +12,7 @@ const mockUpdateMoodBoardItem = vi.fn();const mockSyncMoodBoardPinterest = vi.fn();const mockImportMoodBoardPinterest = vi.fn();const mockImportMoodBoardXPost = vi.fn();+const mockLocalizeMoodBoardMedia = vi.fn();vi.mock('../services/api', () => ({getMoodBoard: (...args) => mockGetMoodBoard(...args),@@ -24,6 +25,7 @@ vi.mock('../services/api', () => ({syncMoodBoardPinterest: (...args) => mockSyncMoodBoardPinterest(...args),importMoodBoardPinterest: (...args) => mockImportMoodBoardPinterest(...args),importMoodBoardXPost: (...args) => mockImportMoodBoardXPost(...args),+ localizeMoodBoardMedia: (...args) => mockLocalizeMoodBoardMedia(...args),}));const mockToastError = vi.fn();@@ -106,6 +108,7 @@ const boardNameValue = () => screen.getByLabelText('Name').value;beforeEach(() => {vi.clearAllMocks();+ mockLocalizeMoodBoardMedia.mockResolvedValue({ board: null, localized: 0, failed: 0 });currentId = 'a';analysisDelay = null;});@@ -265,6 +268,34 @@ describe('MoodBoardDetail private Pinterest import', () => {});});+describe('MoodBoardDetail external media re-hosting', () => {+ it('imports external pins into the gallery on load and swaps in the localized board', async () => {+ mockGetMoodBoard.mockResolvedValueOnce({+ id: 'a', name: 'Board A',+ items: [{ id: 'mbi-1', type: 'image', imageUrl: 'https://example.com/a.jpg' }],+ });+ mockLocalizeMoodBoardMedia.mockResolvedValueOnce({+ board: { id: 'a', name: 'Board A', items: [{ id: 'mbi-1', type: 'image', imageUrl: '/data/images/board-1.jpg' }] },+ localized: 1,+ failed: 0,+ });+ renderPage();+ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Imported 1 external image into the gallery'));+ expect(mockLocalizeMoodBoardMedia).toHaveBeenCalledWith('a', { silent: true });+ expect(document.querySelector('img[src="/data/images/board-1.jpg"]')).not.toBeNull();+ });++ it('does not call the importer when every pin is already local', async () => {+ mockGetMoodBoard.mockResolvedValueOnce({+ id: 'a', name: 'Board A',+ items: [{ id: 'mbi-1', type: 'image', imageUrl: '/data/images/x.jpg' }],+ });+ renderPage();+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));+ expect(mockLocalizeMoodBoardMedia).not.toHaveBeenCalled();+ });+});+describe('MoodBoardDetail X post import', () => {it('imports a post URL and merges the returned board', async () => {mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.jsindex a943280dfd..849af0e8db 100644--- a/client/src/services/apiMoodBoard.js+++ b/client/src/services/apiMoodBoard.js@@ -109,3 +109,8 @@ export const importMoodBoardXPost = (id, url, options) =>body: JSON.stringify({ url }),...options,});++// Download every external image on the board into the local gallery.+// Resolves `{ board, localized, failed }`.+export const localizeMoodBoardMedia = (id, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/localize-media`, { method: 'POST', ...options });diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.jsindex c0ec76d194..c6fdc36e11 100644--- a/server/routes/moodBoard.js+++ b/server/routes/moodBoard.js@@ -40,6 +40,7 @@ import {syncPinterestBoard,importPrivatePinterestBoard,importXPost,+ localizeBoardMedia,} from '../services/moodBoard/index.js';const router = Router();@@ -169,4 +170,9 @@ router.post('/:id/x-post', asyncHandler(async (req, res) => {res.json(result);}));+// Re-host every external image URL on the board into the local gallery.+router.post('/:id/localize-media', asyncHandler(async (req, res) => {+ res.json(await localizeBoardMedia(req.params.id));+}));+export default router;diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.jsindex d57b678481..391168041f 100644--- a/server/services/moodBoard/db.js+++ b/server/services/moodBoard/db.js@@ -37,6 +37,7 @@ import {clearPinterestLinkRecord,appendPinterestPins,appendImportedItems as appendImportedItemsRecord,+ applyLocalizedImageUrls,} from './logic.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,@@ -301,6 +302,16 @@ export async function appendImportedItems(id, imported) {return { board, ...result };}+// Swap external image URLs for their re-hosted local copies in ONE locked write.+// Skips the write when nothing still matches. Returns { board, changed }.+export async function applyLocalizedItemImages(id, replacements) {+ const { board, result } = await withLockedBoard(id, (b) => {+ const { board: next, changed } = applyLocalizedImageUrls(b, replacements);+ return { board: next, result: changed, skipPersist: changed === 0 };+ });+ return { board, changed: result };+}+export async function removeBoardItem(id, itemId) {// Unknown itemId → skip the write entirely (no-op, no updated_at bump). The// route still 200s — removing an already-gone item is idempotent.diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex 945260201c..40d079260f 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -17,6 +17,7 @@import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import * as store from './db.js';+import { localizeImageUrl } from './localize.js';// Read paths + federation entry points pass straight through to the store. The// asset-manifest filename resolver lives in logic.js (pure) and is re-exported@@ -44,6 +45,9 @@ export { importPrivatePinterestBoard } from './privatePinterest.js';// federation emit after the store mutation.export { importXPost } from './xPost.js';+// Re-host external image URLs into the local gallery (boards never serve remote URLs).+export { localizeBoardMedia } from './localize.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)@@ -88,14 +92,22 @@ export async function deleteBoard(id) {// Inline item ops mutate the board record, so each propagates the whole board as// a structural edit (human-pace affordances, not a hot loop — safe to emit every// time; lastPushedHash + same-`updatedAt` LWW no-op dedup prevent ping-pong).+// Pinned/added remote image URLs are downloaded first so the item is born local+// (falls back to the URL when the host is unreachable — localizeBoardMedia can+// retry later).+async function withLocalImage(input) {+ if (!input || (input.type !== 'image' && input.type !== 'video')) return input;+ return input.imageUrl ? { ...input, imageUrl: await localizeImageUrl(input.imageUrl) } : input;+}+export async function addBoardItem(id, itemInput) {- const item = await store.addBoardItem(id, itemInput);+ const item = await store.addBoardItem(id, await withLocalImage(itemInput));emitRecordUpdated('moodBoard', id);return item;}export async function updateBoardItem(id, itemId, patch) {- const item = await store.updateBoardItem(id, itemId, patch);+ const item = await store.updateBoardItem(id, itemId, patch?.imageUrl ? { ...patch, imageUrl: await localizeImageUrl(patch.imageUrl) } : patch);emitRecordUpdated('moodBoard', id);return item;}diff --git a/server/services/moodBoard/localize.js b/server/services/moodBoard/localize.jsnew file mode 100644index 0000000000..a2f4c6445d--- /dev/null+++ b/server/services/moodBoard/localize.js@@ -0,0 +1,78 @@+/**+ * Mood Board — re-host external media.+ *+ * A board should never serve a remote URL: link rot, hotlink blocks, and the+ * fact that prompt-from-media can only read local gallery files. Any image (or+ * video poster) item whose `imageUrl` is http(s) is downloaded into+ * `data/images/` and the item is repointed at the local copy, so it federates+ * as a normal board asset and becomes analyzable. A URL that fails to download+ * (or isn't an image) is left as-is and reported in `failed`.+ *+ * Downloads run OUTSIDE the board row lock; the swap lands in one locked write+ * that only touches items still carrying the URL the download was started for.+ */++import { createHash } from 'crypto';+import { join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, ensureDir, detectImageFormat, writeFileGuarded } from '../../lib/fileUtils.js';+import { fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import { externalImageItems, isExternalImageUrl } from './logic.js';+import * as store from './db.js';++const IMAGE_TIMEOUT_MS = 20000;+const MAX_IMAGE_BYTES = 12 * 1024 * 1024;+const DOWNLOAD_CONCURRENCY = 3;+const UA = 'Mozilla/5.0 (compatible; PortOS Mood Board/1.0; +https://github.com/atomantic/PortOS)';+const IMAGE_HEADERS = { 'User-Agent': UA, Accept: 'image/*' };++/**+ * Download one remote image into the gallery. Returns its served path+ * (`/data/images/<file>`) or null on any failure (unreachable, blocked host,+ * non-image body). The filename is keyed on the URL so repeats are idempotent;+ * the format is sniffed from bytes, never trusted from Content-Type.+ */+export async function downloadExternalImage(url) {+ const res = await fetchPublicBinary(url.trim(), { timeoutMs: IMAGE_TIMEOUT_MS, headers: IMAGE_HEADERS, maxBytes: MAX_IMAGE_BYTES, throwOnUnsafe: false }).catch(() => null);+ if (!res?.buffer?.length) return null;+ const fmt = detectImageFormat(res.buffer);+ if (!fmt) return null;+ const filename = `board-${createHash('sha1').update(url.trim()).digest('hex').slice(0, 16)}${fmt.ext}`;+ await ensureDir(PATHS.images);+ await writeFileGuarded(join(PATHS.images, filename), res.buffer);+ return `/data/images/${filename}`;+}++/** Re-host a single item's image input for an add/update; falls back to the original URL. */+export async function localizeImageUrl(imageUrl) {+ if (!isExternalImageUrl(imageUrl)) return imageUrl;+ return (await downloadExternalImage(imageUrl)) || imageUrl;+}++/**+ * Re-host every external image on a board. Returns `{ board, localized, failed }`.+ * Throws 404 when the board doesn't exist.+ */+export async function localizeBoardMedia(boardId) {+ const board = await store.getBoard(boardId);+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ const targets = externalImageItems(board);+ if (!targets.length) return { board, localized: 0, failed: 0 };++ const replacements = [];+ let failed = 0;+ for (let i = 0; i < targets.length; i += DOWNLOAD_CONCURRENCY) {+ const batch = targets.slice(i, i + DOWNLOAD_CONCURRENCY);+ const results = await Promise.all(batch.map(async (item) => ({ item, to: await downloadExternalImage(item.imageUrl) })));+ for (const { item, to } of results) {+ if (to) replacements.push({ id: item.id, from: item.imageUrl, to });+ else failed += 1;+ }+ }++ const { board: next, changed } = await store.applyLocalizedItemImages(boardId, replacements);+ if (changed) emitRecordUpdated('moodBoard', boardId);+ console.log(`🖼️ Mood board ${boardId}: re-hosted ${changed} external image(s)${failed ? `, ${failed} failed` : ''}`);+ return { board: next, localized: changed, failed };+}diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.jsindex 22c2274e4d..7aa2b578c1 100644--- a/server/services/moodBoard/logic.js+++ b/server/services/moodBoard/logic.js@@ -433,3 +433,36 @@ export function appendImportedItems(board, imported) {const next = { ...board, items: [...items, ...fresh], updatedAt: nowIso() };return { board: next, added: fresh.length };}++// ─── Re-hosting external media ───────────────────────────────────────────────++/** True for an http(s) URL — the only `imageUrl` shape that isn't a local asset. */+export function isExternalImageUrl(url) {+ return isStr(url) && /^https?:\/\//i.test(url.trim());+}++/** Media items whose displayed image still points at a remote host. */+export function externalImageItems(board) {+ const items = Array.isArray(board?.items) ? board.items : [];+ return items.filter((it) => it && (it.type === 'image' || it.type === 'video') && isExternalImageUrl(it.imageUrl));+}++/**+ * Swap re-hosted images in. Each replacement is `{ id, from, to }`; it only+ * applies while the item still carries the `from` URL the download was started+ * for (the fetch runs outside the row lock, so the user may have edited the item+ * meanwhile). Returns `{ board, changed }`.+ */+export function applyLocalizedImageUrls(board, replacements) {+ const items = Array.isArray(board.items) ? board.items : [];+ const byId = new Map((replacements || []).map((r) => [r.id, r]));+ let changed = 0;+ const nextItems = items.map((it) => {+ const r = it && byId.get(it.id);+ if (!r || it.imageUrl !== r.from) return it;+ changed += 1;+ return { ...it, imageUrl: r.to };+ });+ if (!changed) return { board, changed: 0 };+ return { board: { ...board, items: nextItems, updatedAt: nowIso() }, changed };+}diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.jsindex d707c07c5c..324297fdbb 100644--- a/server/services/moodBoard/logic.test.js+++ b/server/services/moodBoard/logic.test.js@@ -21,6 +21,8 @@ import {clearPinterestLinkRecord,appendPinterestPins,appendImportedItems,+ externalImageItems,+ applyLocalizedImageUrls,} from './logic.js';describe('buildBoardRecord', () => {@@ -493,3 +495,35 @@ describe('appendImportedItems', () => {expect(next.items).toEqual([]);});});++describe('re-hosting external media', () => {+ const mk = () => ({+ ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }),+ items: [+ { id: 'a', type: 'image', imageUrl: 'https://example.com/a.jpg' },+ { id: 'b', type: 'image', imageUrl: '/data/images/b.jpg' },+ { id: 'c', type: 'video', mediaKey: 'video:c.mp4', imageUrl: 'http://example.com/c.jpg' },+ { id: 'd', type: 'text', text: 'note' },+ ],+ });++ it('finds only media items whose image is still remote', () => {+ expect(externalImageItems(mk()).map((it) => it.id)).toEqual(['a', 'c']);+ });++ it('swaps a URL only while the item still carries the URL that was downloaded', () => {+ const b = mk();+ const { board: next, changed } = applyLocalizedImageUrls(b, [+ { id: 'a', from: 'https://example.com/a.jpg', to: '/data/images/a.jpg' },+ { id: 'c', from: 'http://example.com/stale.jpg', to: '/data/images/c.jpg' },+ ]);+ expect(changed).toBe(1);+ expect(next.items.find((it) => it.id === 'a').imageUrl).toBe('/data/images/a.jpg');+ expect(next.items.find((it) => it.id === 'c').imageUrl).toBe('http://example.com/c.jpg');+ });++ it('returns the same board when nothing matches', () => {+ const b = mk();+ expect(applyLocalizedImageUrls(b, [{ id: 'zzz', from: 'x', to: 'y' }])).toEqual({ board: b, changed: 0 });+ });+});