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

30.0 KB
Raw Blame
/**
 * Pure record-transform tests for the mood board logic (issue #911). No I/O —
 * these lock the create/patch/item semantics the db store depends on, so the
 * two never drift without a live database.
 */

import { describe, it, expect } from 'vitest';
import {
  buildBoardRecord,
  applyBoardPatch,
  applyBoardRestore,
  addItem,
  updateItem,
  removeItem,
  sanitizeBoardForSync,
  mergeBoardRecord,
  imageUrlToAppAsset,
  MAX_ITEMS_PER_BOARD,
  applyPinterestLink,
  healPinterestFeedRecord,
  clearPinterestLinkRecord,
  appendPinterestPins,
  appendImportedItems,
  externalImageItems,
  applyLocalizedImageUrls,
  claimItemRender,
  settleItemRender,
  applyRenderedItem,
  projectInterruptedNoteRenders,
} from './logic.js';

describe('buildBoardRecord', () => {
  it('builds a board with empty items, mirrored timestamps, and the soft-delete trio', () => {
    const board = buildBoardRecord({ name: 'Refs' }, { id: 'mb-1', now: 't0' });
    expect(board).toEqual({
      id: 'mb-1',
      name: 'Refs',
      description: '',
      items: [],
      createdAt: 't0',
      updatedAt: 't0',
      deleted: false,
      deletedAt: null,
    });
  });
  it('keeps a provided description', () => {
    expect(buildBoardRecord({ name: 'Refs', description: 'd' }, { id: 'mb-1', now: 't0' }).description).toBe('d');
  });
});

describe('applyBoardPatch', () => {
  const base = buildBoardRecord({ name: 'A', description: 'old' }, { id: 'mb-1', now: 't0' });
  it('updates only present fields and bumps updatedAt', () => {
    const next = applyBoardPatch(base, { name: 'B' });
    expect(next.name).toBe('B');
    expect(next.description).toBe('old');
    expect(next.updatedAt).not.toBe('t0');
  });
  it('treats an empty-string description as a clear', () => {
    expect(applyBoardPatch(base, { description: '' }).description).toBe('');
  });
  it('preserves description when the key is absent', () => {
    expect(applyBoardPatch(base, { name: 'B' }).description).toBe('old');
  });
  it('stores a composite style and poster, and null clears both', () => {
    const style = { prompt: 'ink wash dusk', negativePrompt: 'gloss', analyzedItemCount: 2 };
    const withStyle = applyBoardPatch(base, { style, posterImageRef: 'poster.png' });
    expect(withStyle.style.prompt).toBe('ink wash dusk');
    expect(withStyle.style.negativePrompt).toBe('gloss');
    expect(withStyle.style.analyzedItemCount).toBe(2);
    expect(withStyle.style.composedAt).toEqual(expect.any(String));
    expect(withStyle.posterImageRef).toBe('poster.png');
    const cleared = applyBoardPatch(withStyle, { style: null, posterImageRef: null });
    expect(cleared.style).toBeNull();
    expect(cleared.posterImageRef).toBeNull();
  });
  it('leaves style and poster in place when the patch omits them', () => {
    const styled = {
      ...base,
      style: {
        prompt: 'keep',
        negativePrompt: null,
        rationale: null,
        analyzedItemCount: 0,
        providerId: null,
        model: null,
        composedAt: 't1',
      },
      posterImageRef: 'poster.png',
    };
    const next = applyBoardPatch(styled, { name: 'B' });
    expect(next.style.prompt).toBe('keep');
    expect(next.posterImageRef).toBe('poster.png');
  });
});

describe('addItem', () => {
  const base = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
  it('normalizes an image item with imageUrl', () => {
    const { board, item } = addItem(base, { type: 'image', imageUrl: 'https://x/y.png', caption: 'c' });
    expect(item.type).toBe('image');
    expect(item.imageUrl).toBe('https://x/y.png');
    expect(item.text).toBeNull();
    expect(item.caption).toBe('c');
    expect(item.id).toMatch(/^mbi-/);
    expect(board.items).toHaveLength(1);
  });
  it('normalizes an image item with mediaKey', () => {
    const { item } = addItem(base, { type: 'image', mediaKey: 'image:a.png' });
    expect(item.mediaKey).toBe('image:a.png');
    expect(item.imageUrl).toBeNull();
  });
  it('normalizes a text item and nulls image fields', () => {
    const { item } = addItem(base, { type: 'text', text: 'note' });
    expect(item.text).toBe('note');
    expect(item.mediaKey).toBeNull();
    expect(item.imageUrl).toBeNull();
  });
  it('normalizes a video item with mediaKey + poster imageUrl (#4188)', () => {
    const { item } = addItem(base, {
      type: 'video', mediaKey: 'video:upload-ab12cd34.mp4', imageUrl: '/data/video-thumbnails/upload-ab12cd34.jpg',
    });
    expect(item.type).toBe('video');
    expect(item.mediaKey).toBe('video:upload-ab12cd34.mp4');
    expect(item.imageUrl).toBe('/data/video-thumbnails/upload-ab12cd34.jpg');
    expect(item.text).toBeNull();
  });
  it('normalizes prompt on media items and nulls on text items', () => {
    const { item: img } = addItem(base, { type: 'image', mediaKey: 'image:a.png', prompt: 'an image prompt' });
    expect(img.prompt).toBe('an image prompt');
    const { item: txt } = addItem(base, { type: 'text', text: 'note', prompt: 'ignored prompt' });
    expect(txt.prompt).toBeNull();
  });
  it('throws BOARD_FULL at the item cap', () => {
    const full = { ...base, items: Array.from({ length: MAX_ITEMS_PER_BOARD }, (_, i) => ({ id: `i${i}` })) };
    expect(() => addItem(full, { type: 'text', text: 'x' })).toThrow(/full/i);
  });
});

describe('updateItem', () => {
  const withItem = (() => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), { type: 'text', text: 'orig' });
    return board;
  })();
  const itemId = withItem.items[0].id;

  it('patches present fields only', () => {
    const { item } = updateItem(withItem, itemId, { caption: 'new' });
    expect(item.caption).toBe('new');
    expect(item.text).toBe('orig');
  });
  it('patches prompt on a media item', () => {
    const fresh = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
    const { board: withImg, item: img } = addItem(fresh, { type: 'image', mediaKey: 'image:p.png' });
    const { item: patched } = updateItem(withImg, img.id, { prompt: 'updated prompt' });
    expect(patched.prompt).toBe('updated prompt');
  });
  it('throws NOT_FOUND for an unknown item id', () => {
    expect(() => updateItem(withItem, 'nope', { caption: 'x' })).toThrow(/not found/i);
  });
  it('ignores type-inappropriate body fields (text item cannot gain an imageUrl)', () => {
    const { item } = updateItem(withItem, itemId, { imageUrl: 'https://x/y.png', mediaKey: 'image:a.png', text: 'changed' });
    expect(item.imageUrl).toBeNull();
    expect(item.mediaKey).toBeNull();
    expect(item.text).toBe('changed');
  });
  it('ignores text on an image item', () => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-2', now: 't0' }), { type: 'image', imageUrl: 'https://x/y.png' });
    const imgId = board.items[0].id;
    const { item } = updateItem(board, imgId, { text: 'nope', caption: 'ok' });
    expect(item.text).toBeNull();
    expect(item.caption).toBe('ok');
  });
  it('rejects clearing an image item’s only source', () => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-3', now: 't0' }), { type: 'image', imageUrl: 'https://x/y.png' });
    const imgId = board.items[0].id;
    expect(() => updateItem(board, imgId, { imageUrl: null })).toThrow(/mediaKey or imageUrl/i);
  });
  it('rejects blanking a text item', () => {
    expect(() => updateItem(withItem, itemId, { text: '   ' })).toThrow(/non-empty text/i);
  });
  it('edits a video item like a media item and rejects clearing its mediaKey (#4188)', () => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-4', now: 't0' }), {
      type: 'video', mediaKey: 'video:a.mp4', imageUrl: '/data/video-thumbnails/a.jpg',
    });
    const vidId = board.items[0].id;
    const { item } = updateItem(board, vidId, { caption: 'clip', text: 'nope' });
    expect(item.caption).toBe('clip');
    expect(item.text).toBeNull();
    expect(() => updateItem(board, vidId, { mediaKey: null })).toThrow(/mediaKey/i);
    // A PATCH can't swap a video item onto a non-video or extension-less key
    // either — the merged key must stay a playable video:<filename>.
    expect(() => updateItem(board, vidId, { mediaKey: 'image:foo.png' })).toThrow(/mediaKey/i);
    expect(() => updateItem(board, vidId, { mediaKey: 'video:job-123' })).toThrow(/mediaKey/i);
  });
  it('persists a normalized analysis on a media item and clears it with null (#4188 Phase 3)', () => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-5', now: 't0' }), { type: 'image', imageUrl: 'https://x/y.png' });
    const imgId = board.items[0].id;
    const { board: analyzed, item } = updateItem(board, imgId, { analysis: { prompt: 'a moody castle' } });
    expect(item.analysis).toMatchObject({
      prompt: 'a moody castle',
      negativePrompt: null,
      rationale: null,
      providerId: null,
      model: null,
    });
    // analyzedAt is stamped server-side when the client didn't send one.
    expect(typeof item.analysis.analyzedAt).toBe('string');
    expect(item.analysis.analyzedAt.length).toBeGreaterThan(0);
    // Other patches leave the stored analysis untouched.
    const { board: captioned, item: kept } = updateItem(analyzed, imgId, { caption: 'c' });
    expect(kept.analysis.prompt).toBe('a moody castle');
    const { item: cleared } = updateItem(captioned, imgId, { analysis: null });
    expect(cleared.analysis).toBeNull();
  });
  it('keeps a client-provided analyzedAt on a video item and ignores analysis on a text item', () => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-6', now: 't0' }), { type: 'video', mediaKey: 'video:a.mp4' });
    const vidId = board.items[0].id;
    const { item } = updateItem(board, vidId, { analysis: { prompt: 'motion', analyzedAt: '2026-08-14T00:00:00.000Z' } });
    expect(item.analysis.analyzedAt).toBe('2026-08-14T00:00:00.000Z');
    // Analysis comes from the item's media, so a text item never gains one.
    const { item: textItem } = updateItem(withItem, itemId, { analysis: { prompt: 'nope' } });
    expect(textItem.analysis).toBeUndefined();
  });
});

describe('removeItem', () => {
  const withItem = (() => {
    const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), { type: 'text', text: 'orig' });
    return board;
  })();
  const itemId = withItem.items[0].id;

  it('removes a present item', () => {
    const { board, removed } = removeItem(withItem, itemId);
    expect(removed).toBe(true);
    expect(board.items).toHaveLength(0);
  });
  it('returns removed:false (no write) for an absent id', () => {
    const { board, removed } = removeItem(withItem, 'nope');
    expect(removed).toBe(false);
    expect(board).toBe(withItem);
  });
});

describe('sanitizeBoardForSync', () => {
  it('drops a non-object or id-less record', () => {
    expect(sanitizeBoardForSync(null)).toBeNull();
    expect(sanitizeBoardForSync([])).toBeNull();
    expect(sanitizeBoardForSync({ name: 'no id' })).toBeNull();
  });
  it('normalizes the soft-delete trio and defaults updatedAt to createdAt', () => {
    const out = sanitizeBoardForSync({ id: 'mb-1', name: 'A', createdAt: 't0' });
    expect(out).toMatchObject({ id: 'mb-1', createdAt: 't0', updatedAt: 't0', deleted: false, deletedAt: null });
  });
  it('preserves a tombstone', () => {
    const out = sanitizeBoardForSync({ id: 'mb-1', name: 'A', createdAt: 't0', updatedAt: 't1', deleted: true, deletedAt: 't1' });
    expect(out).toMatchObject({ deleted: true, deletedAt: 't1' });
  });
});

describe('mergeBoardRecord (LWW)', () => {
  const board = (over = {}) => ({ id: 'mb-1', name: 'A', description: '', items: [], createdAt: 't0', updatedAt: '2026-06-23T00:00:00.000Z', deleted: false, deletedAt: null, ...over });

  it('inserts when there is no local copy', () => {
    const { next, inserted, remoteWins } = mergeBoardRecord(null, board());
    expect(inserted).toBe(true);
    expect(remoteWins).toBe(true);
    expect(next.id).toBe('mb-1');
  });
  it('drops a malformed remote', () => {
    expect(mergeBoardRecord(board(), { name: 'no id' }).next).toBeNull();
  });
  it('newer remote updatedAt wins', () => {
    const local = board({ updatedAt: '2026-06-23T00:00:00.000Z' });
    const remote = board({ name: 'B', updatedAt: '2026-06-24T00:00:00.000Z' });
    const { remoteWins, changed, next } = mergeBoardRecord(local, remote);
    expect(remoteWins).toBe(true);
    expect(changed).toBe(true);
    expect(next.name).toBe('B');
  });
  it('older remote loses (local kept)', () => {
    const local = board({ name: 'local', updatedAt: '2026-06-24T00:00:00.000Z' });
    const remote = board({ name: 'remote', updatedAt: '2026-06-23T00:00:00.000Z' });
    const { remoteWins, next } = mergeBoardRecord(local, remote);
    expect(remoteWins).toBe(false);
    expect(next.name).toBe('local');
  });
  it('a tombstone with a newer updatedAt wins over a live local', () => {
    const local = board({ updatedAt: '2026-06-23T00:00:00.000Z' });
    const remote = board({ updatedAt: '2026-06-24T00:00:00.000Z', deleted: true, deletedAt: '2026-06-24T00:00:00.000Z' });
    const { remoteWins, next } = mergeBoardRecord(local, remote);
    expect(remoteWins).toBe(true);
    expect(next.deleted).toBe(true);
  });
  it('reports changed:false when the winner is byte-identical to local', () => {
    const local = board();
    const { changed } = mergeBoardRecord(local, board());
    expect(changed).toBe(false);
  });
});

describe('imageUrlToAppAsset', () => {
  it('resolves a gallery image path to { kind: image, filename }', () => {
    expect(imageUrlToAppAsset('/data/images/foo.png')).toEqual({ kind: 'image', filename: 'foo.png' });
    expect(imageUrlToAppAsset('/data/images/sub/foo.png?v=2')).toEqual({ kind: 'image', filename: 'foo.png' });
  });
  it('resolves an image-ref path (canon-sheet / noun pins) to { kind: image-ref, filename }', () => {
    expect(imageUrlToAppAsset('/data/image-refs/canon-abc.png')).toEqual({ kind: 'image-ref', filename: 'canon-abc.png' });
  });
  it('treats a bare/relative ref as a gallery image (legacy shape)', () => {
    expect(imageUrlToAppAsset('foo.png')).toEqual({ kind: 'image', filename: 'foo.png' });
  });
  it('returns null for external / other-absolute / empty values', () => {
    expect(imageUrlToAppAsset('https://x/y.png')).toBeNull();
    expect(imageUrlToAppAsset('data:image/png;base64,AAA')).toBeNull();
    expect(imageUrlToAppAsset('/data/videos/clip.mp4')).toBeNull(); // video bytes ride a media-key, not an imageUrl
    expect(imageUrlToAppAsset('/etc/passwd')).toBeNull();
    expect(imageUrlToAppAsset('')).toBeNull();
    expect(imageUrlToAppAsset(null)).toBeNull();
  });
});

describe('applyBoardRestore', () => {
  it('wholesale-restores name/description/items (unlike applyBoardPatch) and bumps updatedAt', () => {
    const base = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
    const items = [{ id: 'mbi-1', type: 'text', text: 'restored', mediaKey: null, imageUrl: null, caption: null, source: null, createdAt: 't0' }];
    const next = applyBoardRestore(base, { name: 'B', description: 'd', items });
    expect(next.name).toBe('B');
    expect(next.description).toBe('d');
    expect(next.items).toEqual(items);
    expect(next.updatedAt).not.toBe('t0');
  });
  it('ignores a non-array items field', () => {
    const base = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), items: [{ id: 'x' }] };
    expect(applyBoardRestore(base, { items: 'nope' }).items).toEqual([{ id: 'x' }]);
  });
  it('restores the composite style and poster when the journaled version had them', () => {
    const base = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), style: null, posterImageRef: 'new.png' };
    const next = applyBoardRestore(base, {
      style: { prompt: 'restored ink', analyzedItemCount: 1, composedAt: '2026-08-14T00:00:00.000Z' },
      posterImageRef: 'old.png',
    });
    expect(next.style.prompt).toBe('restored ink');
    expect(next.style.composedAt).toBe('2026-08-14T00:00:00.000Z');
    expect(next.posterImageRef).toBe('old.png');
  });
});

describe('applyPinterestLink', () => {
  const base = () => buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });

  it('stores the feed + board URLs and seeds sync state', () => {
    const next = applyPinterestLink(base(), { feedUrl: 'https://www.pinterest.com/j/b.rss', boardUrl: 'https://www.pinterest.com/j/b/' });
    expect(next.pinterest).toEqual({
      feedUrl: 'https://www.pinterest.com/j/b.rss',
      boardUrl: 'https://www.pinterest.com/j/b/',
      lastSyncedAt: null,
    });
    expect(next.updatedAt).not.toBe('t0');
  });

  it('preserves the prior sync timestamp when re-linking the SAME feed', () => {
    const linked = { ...base(), pinterest: { feedUrl: 'f.rss', boardUrl: 'oldb', lastSyncedAt: 's1' } };
    const next = applyPinterestLink(linked, { feedUrl: 'f.rss', boardUrl: 'newb' });
    expect(next.pinterest).toMatchObject({ feedUrl: 'f.rss', lastSyncedAt: 's1' });
  });

  it('clears the sync timestamp when re-linking to a DIFFERENT feed', () => {
    const linked = { ...base(), pinterest: { feedUrl: 'old.rss', boardUrl: 'oldb', lastSyncedAt: 's1' } };
    const next = applyPinterestLink(linked, { feedUrl: 'new.rss', boardUrl: 'newb' });
    expect(next.pinterest).toMatchObject({ feedUrl: 'new.rss', lastSyncedAt: null });
  });
});

describe('healPinterestFeedRecord', () => {
  const base = () => buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
  const heal = (b, link) => healPinterestFeedRecord(b, link);

  it('rewrites to the corrected feed when the stored feed still matches', () => {
    const linked = { ...base(), pinterest: { feedUrl: 'sec.rss', boardUrl: 'https://www.pinterest.com/j/b/s/', lastSyncedAt: null } };
    const { board, changed } = heal(linked, { fromFeedUrl: 'sec.rss', feedUrl: 'board.rss', boardUrl: 'https://www.pinterest.com/j/b/s/' });
    expect(changed).toBe(true);
    expect(board.pinterest.feedUrl).toBe('board.rss');
  });

  it('is a no-op (no resurrect) when the user unlinked concurrently', () => {
    const unlinked = base(); // pinterest removed mid-sync
    const out = heal(unlinked, { fromFeedUrl: 'sec.rss', feedUrl: 'board.rss', boardUrl: 'b' });
    expect(out.changed).toBe(false);
    expect(out.board).toBe(unlinked);
    expect(out.board.pinterest).toBeUndefined();
  });

  it('is a no-op when the user repointed the board to a different feed', () => {
    const repointed = { ...base(), pinterest: { feedUrl: 'other.rss', boardUrl: 'ob', lastSyncedAt: null } };
    const out = heal(repointed, { fromFeedUrl: 'sec.rss', feedUrl: 'board.rss', boardUrl: 'b' });
    expect(out.changed).toBe(false);
    expect(out.board.pinterest.feedUrl).toBe('other.rss');
  });

  it('is a no-op when already on the corrected feed (from === to)', () => {
    const linked = { ...base(), pinterest: { feedUrl: 'board.rss', boardUrl: 'b', lastSyncedAt: 's1' } };
    const out = heal(linked, { fromFeedUrl: 'board.rss', feedUrl: 'board.rss', boardUrl: 'b' });
    expect(out.changed).toBe(false);
  });
});

describe('clearPinterestLinkRecord', () => {
  it('removes the pinterest field and bumps updatedAt', () => {
    const linked = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), pinterest: { feedUrl: 'f' } };
    const { board, changed } = clearPinterestLinkRecord(linked);
    expect(changed).toBe(true);
    expect(board.pinterest).toBeUndefined();
    expect(board.updatedAt).not.toBe('t0');
  });

  it('is a no-op when not linked', () => {
    const board = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
    const out = clearPinterestLinkRecord(board);
    expect(out.changed).toBe(false);
    expect(out.board).toBe(board);
  });
});

describe('appendPinterestPins', () => {
  const linked = () => ({
    ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }),
    pinterest: { feedUrl: 'f', boardUrl: 'b', lastSyncedAt: null },
  });
  const imp = (n) => ({ imageUrl: `/data/images/p${n}.jpg`, caption: `c${n}`, source: `https://www.pinterest.com/pin/${n}/` });

  it('appends image items and stamps sync state', () => {
    const { board, added } = appendPinterestPins(linked(), [imp(1), imp(2)], { syncedAt: 's1' });
    expect(added).toBe(2);
    expect(board.items.map((it) => it.source)).toEqual(['https://www.pinterest.com/pin/1/', 'https://www.pinterest.com/pin/2/']);
    expect(board.items[0]).toMatchObject({ type: 'image', imageUrl: '/data/images/p1.jpg', caption: 'c1' });
    expect(board.pinterest).toMatchObject({ lastSyncedAt: 's1' });
  });

  it('dedupes against existing item sources', () => {
    const existing = { ...linked(), items: [{ id: 'mbi-x', type: 'image', source: 'https://www.pinterest.com/pin/1/' }] };
    const { added, board } = appendPinterestPins(existing, [imp(1), imp(2)], { syncedAt: 's1' });
    expect(added).toBe(1);
    expect(board.items).toHaveLength(2);
  });

  it('stamps lastSyncedAt even when nothing new was added', () => {
    const { board, added } = appendPinterestPins(linked(), [], { syncedAt: 's2' });
    expect(added).toBe(0);
    expect(board.pinterest).toMatchObject({ lastSyncedAt: 's2' });
  });

  it('truncates to MAX_ITEMS_PER_BOARD capacity', () => {
    const full = { ...linked(), items: Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `e${i}`, type: 'image', source: `e${i}` })) };
    const { added } = appendPinterestPins(full, [imp(1), imp(2), imp(3)], { syncedAt: 's1' });
    expect(added).toBe(1);
  });

  it('aborts (no append, no stamp) when the link changed mid-sync', () => {
    const b = { ...linked(), pinterest: { feedUrl: 'now.rss', lastSyncedAt: 'prev' } };
    const { board, added, aborted } = appendPinterestPins(b, [imp(1)], { syncedAt: 's9', expectedFeedUrl: 'stale.rss' });
    expect(aborted).toBe(true);
    expect(added).toBe(0);
    expect(board).toBe(b); // unchanged — no items appended, lastSyncedAt not bumped
  });

  it('proceeds when expectedFeedUrl matches the current link', () => {
    const b = { ...linked(), pinterest: { feedUrl: 'now.rss', lastSyncedAt: 'prev' } };
    const { added, aborted } = appendPinterestPins(b, [imp(1)], { syncedAt: 's9', expectedFeedUrl: 'now.rss' });
    expect(aborted).toBe(false);
    expect(added).toBe(1);
  });
});

describe('appendImportedItems', () => {
  const board = () => buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });

  it('appends image and video items', () => {
    const { board: next, added } = appendImportedItems(board(), [
      { type: 'image', imageUrl: '/data/images/a.jpg', source: 'https://x.com/i/status/1#0' },
      { type: 'video', mediaKey: 'video:x-abc.mp4', imageUrl: '/data/images/poster.jpg', source: 'https://x.com/i/status/1#video' },
    ]);
    expect(added).toBe(2);
    expect(next.items[0]).toMatchObject({ type: 'image', imageUrl: '/data/images/a.jpg' });
    expect(next.items[1]).toMatchObject({ type: 'video', mediaKey: 'video:x-abc.mp4', imageUrl: '/data/images/poster.jpg' });
  });

  it('dedupes against existing item sources', () => {
    const existing = { ...board(), items: [{ id: 'mbi-x', type: 'image', source: 'https://x.com/i/status/1#0' }] };
    const { added, board: next } = appendImportedItems(existing, [
      { type: 'image', imageUrl: '/data/images/a.jpg', source: 'https://x.com/i/status/1#0' },
      { type: 'image', imageUrl: '/data/images/b.jpg', source: 'https://x.com/i/status/1#1' },
    ]);
    expect(added).toBe(1);
    expect(next.items).toHaveLength(2);
  });

  it('truncates to MAX_ITEMS_PER_BOARD capacity', () => {
    const full = { ...board(), items: Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `e${i}`, type: 'image', source: `e${i}` })) };
    const { added } = appendImportedItems(full, [
      { type: 'image', imageUrl: '/data/images/a.jpg', source: 's1' },
      { type: 'image', imageUrl: '/data/images/b.jpg', source: 's2' },
    ]);
    expect(added).toBe(1);
  });

  it('handles an empty/non-array imported list', () => {
    const { added, board: next } = appendImportedItems(board(), []);
    expect(added).toBe(0);
    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 });
  });
});

describe('text note render lifecycle (#10531)', () => {
  const note = { id: 'n1', type: 'text', text: 'Palette: violet and cyan', caption: null, source: 'autonomous music video', createdAt: '2026-01-01T00:00:00.000Z' };
  const board = () => ({ id: 'mb-1', items: [{ id: 'i0', type: 'image', mediaKey: 'image:a.png' }, note, { id: 'n2', type: 'text', text: 'Motif' }] });

  it('turns the claimed note into an image in place, keeping its words as the caption', () => {
    const claimed = claimItemRender(board(), 'n1').board;
    const queued = settleItemRender(claimed, 'n1', { jobId: 'job-1', status: 'queued' }).board;
    const { board: done, item, changed } = applyRenderedItem(queued, 'n1', { jobId: 'job-1', filename: 'job-1.png', prompt: ' the prompt ' });
    expect(changed).toBe(true);
    expect(done.items.map((it) => it.id)).toEqual(['i0', 'n1', 'n2']);
    expect(item).toMatchObject({
      id: 'n1', type: 'image', mediaKey: 'image:job-1.png', text: null, prompt: 'the prompt',
      caption: note.text, source: note.source, createdAt: note.createdAt,
    });
    expect(item.render).toBeUndefined();
  });

  it('drops a stale job once a newer render owns the note', () => {
    const queued = settleItemRender(claimItemRender(board(), 'n1').board, 'n1', { jobId: 'job-2', status: 'queued' }).board;
    expect(applyRenderedItem(queued, 'n1', { jobId: 'job-1', filename: 'job-1.png' }).changed).toBe(false);
    expect(settleItemRender(queued, 'n1', { jobId: 'job-1', status: 'failed', error: 'x' }).changed).toBe(false);
  });

  it('refuses a duplicate render while the job lives, and replaces a dead one', () => {
    const queued = settleItemRender(claimItemRender(board(), 'n1').board, 'n1', { jobId: 'job-1', status: 'queued' }).board;
    expect(() => claimItemRender(queued, 'n1', { isLive: () => true })).toThrow(expect.objectContaining({ code: 'MOOD_BOARD_RENDER_BUSY' }));
    expect(claimItemRender(queued, 'n1', { isLive: () => false }).item.render).toMatchObject({ status: 'queued', jobId: null });
  });

  it('expires a claim that never got its job id', () => {
    const claimed = claimItemRender(board(), 'n1', { now: '2026-01-01T00:00:00.000Z' }).board;
    expect(() => claimItemRender(claimed, 'n1', { now: '2026-01-01T00:05:00.000Z' })).toThrow(expect.objectContaining({ code: 'MOOD_BOARD_RENDER_BUSY' }));
    expect(claimItemRender(claimed, 'n1', { now: '2026-01-01T00:11:00.000Z' }).item.render.queuedAt).toBe('2026-01-01T00:11:00.000Z');
  });

  it('only renders text notes', () => {
    expect(() => claimItemRender(board(), 'i0')).toThrow(expect.objectContaining({ code: 'MOOD_BOARD_ITEM_NOT_TEXT' }));
    expect(() => claimItemRender(board(), 'missing')).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }));
  });

  it('projects a queued note whose job is gone as interrupted, and leaves a live one', () => {
    const queued = settleItemRender(claimItemRender(board(), 'n1').board, 'n1', { jobId: 'job-dead', status: 'queued' }).board;
    queued.updatedAt = '2020-01-01T00:00:00.000Z';
    const dead = projectInterruptedNoteRenders(queued, { isLive: () => false });
    expect(dead.changed).toBe(true);
    expect(dead.board.items.find((it) => it.id === 'n1').render).toMatchObject({
      status: 'failed', error: 'interrupted by restart', jobId: 'job-dead',
    });
    expect(dead.board.updatedAt).not.toBe(queued.updatedAt);
    const live = projectInterruptedNoteRenders(queued, { isLive: (jobId) => jobId === 'job-dead' });
    expect(live).toEqual({ board: queued, changed: false });
  });

  it('keeps a claim with no job id until the claim TTL, then fails it', () => {
    const claimed = claimItemRender(board(), 'n1', { now: '2026-01-01T00:00:00.000Z' }).board;
    expect(projectInterruptedNoteRenders(claimed, { now: '2026-01-01T00:09:00.000Z' }).changed).toBe(false);
    const expired = projectInterruptedNoteRenders(claimed, { now: '2026-01-01T00:11:00.000Z' });
    expect(expired.board.items.find((it) => it.id === 'n1').render).toMatchObject({
      status: 'failed', error: 'interrupted by restart', jobId: null,
    });
  });

  it('ignores an image item and a note that is not queued', () => {
    const image = { id: 'i0', type: 'image', mediaKey: 'image:a.png', render: { status: 'queued', jobId: 'job-x' } };
    const failed = { id: 'n1', type: 'text', text: 'note', render: { status: 'failed', jobId: 'job-y', error: 'boom' } };
    const board = { items: [image, failed] };
    expect(projectInterruptedNoteRenders(board, { isLive: () => false })).toEqual({ board, changed: false });
  });
});


it('returns the original media pin on retry even at capacity, preserving user edits', () => {
  const original = { id: 'pin-original', type: 'image', mediaKey: 'image:upload.png', caption: 'Edited caption' };
  const board = { items: [original, ...Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `note-${i}`, type: 'text', text: 'Note' }))] };
  expect(addItem(board, { type: 'image', mediaKey: original.mediaKey, caption: 'Upload caption' })).toEqual({ board, item: original });
});