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

feat(media): favorite + note annotations for generated images and videos

Adam Eivycb5d94239da7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fab821f80e..fb00a5c7fa 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Favorite + note any generated image or video.** Every MediaCard now has a star toggle in the corner; clicking the tile opens the lightbox where a single editable note (max 2000 chars, 500ms debounced save) lives next to the prompt. Favorites and notes are surfaced across all four gallery surfaces — Media History, Image Gen, Video Gen, and Media Collection Detail — and a "Favorites" filter chip on each scopes the grid to starred items only. Press `s` while a lightbox is open to toggle favorite. Annotations persist to a new sidecar `data/media-annotations.json` keyed by `<kind>:<ref>` (same scheme as collections) so they survive when the underlying job records get pruned. Empty annotations (`!starred && !note`) get removed from disk on write to keep the file lean. Backed by `server/services/mediaAnnotations.js` + `server/routes/mediaAnnotations.js` (GET / PATCH with prune-on-empty + 2000-char note cap), the shared `useMediaAnnotations()` hook with optimistic-update + revert, and `MediaCard` / `MediaLightbox` prop extensions (`starred`, `hasNote`, `onToggleStar`, `annotation`, `onAnnotationChange`).
+
- **World Builder — per-element Render buttons.** Each composite board, each category item (variation), and each category header now has its own inline Render button — no need to render the whole batch when you just want to iterate on one image. Per-board and per-variation buttons render exactly one prompt; the per-category header button renders every variation in that category. All three reuse the page's existing render-options panel (backend, model, resolution, batch-per-prompt) and route through the same job-queue + collection-tagging path as the full batch render, so toast + run history behave identically. Buttons disable themselves when the world isn't saved, no backend is configured, or a render is already in flight; per-category disables when the category has no variations yet.
- **World Builder — Refine prompts modal.** Once a world has a starter idea, click *Refine prompts* to describe a tweak in plain English ("more painterly", "lean harder into the moebius linework", "drop the cyberpunk neon") and the LLM rewrites the starter, style, and negative prompts together, with a one-line rationale shown alongside each. Each rewritten field is editable inline before *Apply*; applying auto-persists the result back to a saved world (mirrors the *Expand* flow's auto-save) so subsequent renders/expansions pick up the refinement immediately. Backed by `POST /api/world-builder/refine-prompts` + `server/services/worldBuilderRefine.js` reusing the same stage-runner plumbing the Expand pass uses.
- **Refine Prompt action in the Media Lightbox.** Open any past image or video render and click *Refine Prompt* to describe what you'd like to change in plain English ("more painterly", "switch to watercolor", "drop the cyberpunk neon"). PortOS hands the original prompt + your feedback to any enabled AI provider — API (OpenAI, Anthropic, LM Studio) or CLI (Codex, Claude Code, Gemini CLI) — and shows the rewritten positive and negative prompts as editable text plus a one-line rationale. Tweak the new prompt if you want, then *Queue Render* to make a new render that inherits the original's model, resolution, LoRAs, seed, and other settings.
diff --git a/client/src/components/media/FavoritesFilterChip.jsx b/client/src/components/media/FavoritesFilterChip.jsx
new file mode 100644
index 0000000000..846a64ae3c
--- /dev/null
+++ b/client/src/components/media/FavoritesFilterChip.jsx
@@ -0,0 +1,24 @@
+import { Star } from 'lucide-react';
+
+// Pill that scopes a media gallery to favorited items. Used by MediaHistory,
+// ImageGen, VideoGen — anywhere a grid of MediaCards needs a "show only the
+// starred ones" toggle. `size` matches the surrounding chip row so the gold
+// pressed state lines up visually with sibling filter chips.
+export default function FavoritesFilterChip({ active, onToggle, size = 'sm' }) {
+ const padding = size === 'sm' ? 'px-2 py-1' : 'px-2.5 py-1';
+ return (
+ <button
+ type="button"
+ onClick={onToggle}
+ className={`flex items-center gap-1 ${padding} rounded-full border text-xs ${
+ active
+ ? 'bg-port-warning/20 border-port-warning text-port-warning'
+ : 'border-port-border text-gray-400 hover:text-white hover:bg-port-border/50'
+ }`}
+ title="Show favorites only"
+ aria-pressed={active}
+ >
+ <Star className={`w-3 h-3 ${active ? 'fill-current' : ''}`} /> Favorites
+ </button>
+ );
+}
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index f742ee1a20..1fc0544252 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -1,4 +1,4 @@
-import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2, Wand2 } from 'lucide-react';
+import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2, Wand2, Star, MessageSquare } from 'lucide-react';
import AddToCollectionMenu from './AddToCollectionMenu';
import { loraDisplayName } from './normalize';
@@ -22,6 +22,9 @@ export default function MediaCard({
disabled = false,
hideActions = false,
showCollectionMenu = true,
+ starred = false,
+ hasNote = false,
+ onToggleStar,
}) {
const { kind, prompt, modelId, previewUrl, downloadUrl } = item;
const isVideo = kind === 'video';
@@ -47,6 +50,30 @@ export default function MediaCard({
{selectionLabel}
</div>
)}
+ {(onToggleStar || starred || hasNote) && (
+ <div className="absolute bottom-1.5 left-1.5 flex items-center gap-1">
+ {onToggleStar && (
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onToggleStar(item); }}
+ className={`p-1 rounded-full ${starred ? 'bg-port-warning/90 text-black' : 'bg-black/50 text-white/70 hover:text-white'}`}
+ title={starred ? 'Unfavorite' : 'Favorite'}
+ aria-label={starred ? 'Unfavorite' : 'Favorite'}
+ >
+ <Star className={`w-3.5 h-3.5 ${starred ? 'fill-current' : ''}`} />
+ </button>
+ )}
+ {hasNote && (
+ <span
+ className="p-1 rounded-full bg-port-accent/80 text-white"
+ title="Has note"
+ aria-label="Has note"
+ >
+ <MessageSquare className="w-3 h-3" />
+ </span>
+ )}
+ </div>
+ )}
<div className="absolute top-1.5 right-1.5 flex flex-col items-end gap-0.5">
{[
item.stitchedFrom && { label: 'stitched', cls: 'bg-port-success/80 text-white' },
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index bf49a11522..7797fe2030 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -1,11 +1,14 @@
import { useEffect, useRef, useState } from 'react';
import {
X, Copy, Sparkles, Film, Image as ImageIcon, Download, Eraser,
- ChevronLeft, ChevronRight, Maximize2, Minimize2,
+ ChevronLeft, ChevronRight, Maximize2, Minimize2, Star,
} from 'lucide-react';
import toast from '../ui/Toast';
import PromptRefineModal from './PromptRefineModal';
+const NOTE_MAX = 2000;
+const NOTE_DEBOUNCE_MS = 500;
+
// Mirror of CLEAN_LEVELS in server/routes/imageClean.js. If the server adds a
// new level, drop a label here and the pill renders automatically.
const CLEAN_LEVEL_LABELS = { light: 'Light', aggressive: 'Aggressive' };
@@ -28,21 +31,25 @@ export default function MediaLightbox({
onNext,
hasPrevious = false,
hasNext = false,
+ annotation = null,
+ onAnnotationChange,
}) {
const [cleaning, setCleaning] = useState(null);
const [fullScreen, setFullScreen] = useState(false);
const [drawerOpen, setDrawerOpen] = useState(false);
const [refineOpen, setRefineOpen] = useState(false);
const touchStart = useRef({ x: null, y: null });
- // Read callbacks from refs so the keydown listener doesn't re-subscribe on
- // every parent render (callers pass inline arrows; the lightbox parent re-
- // renders constantly while media-gen events stream in).
- const callbacksRef = useRef({ onClose, onPrevious, onNext });
- useEffect(() => { callbacksRef.current = { onClose, onPrevious, onNext }; });
+ // Read callbacks + frequently-changing values from refs so the keydown
+ // listener and the note-save debounce don't tear down on every parent
+ // render. Callers pass inline arrows for onAnnotationChange, and the
+ // parent re-renders constantly while media-gen events stream in.
+ const starred = !!annotation?.starred;
+ const refs = useRef({ onClose, onPrevious, onNext, onAnnotationChange, starred });
+ useEffect(() => { refs.current = { onClose, onPrevious, onNext, onAnnotationChange, starred }; });
useEffect(() => {
if (!item) return;
const onKey = (e) => {
- const cb = callbacksRef.current;
+ const cb = refs.current;
if (e.key === 'Escape') {
if (refineOpen) { setRefineOpen(false); return; }
if (fullScreen && drawerOpen) { setDrawerOpen(false); return; }
@@ -54,6 +61,17 @@ export default function MediaLightbox({
setFullScreen((v) => !v);
return;
}
+ // `s` toggles favorite — but only when focus is on the body, not while
+ // typing in the note textarea (which would eat every literal "s").
+ if ((e.key === 's' || e.key === 'S') && cb.onAnnotationChange) {
+ const t = e.target;
+ const inEditable = t && (t.tagName === 'TEXTAREA' || t.tagName === 'INPUT' || t.isContentEditable);
+ if (!inEditable) {
+ e.preventDefault();
+ cb.onAnnotationChange({ starred: !cb.starred });
+ return;
+ }
+ }
if (e.key === 'ArrowLeft' && hasPrevious && cb.onPrevious) {
e.preventDefault();
cb.onPrevious();
@@ -213,6 +231,8 @@ export default function MediaLightbox({
setCleaning={setCleaning}
copy={copy}
onRefine={() => setRefineOpen(true)}
+ annotation={annotation}
+ onAnnotationChange={onAnnotationChange}
/>
)}
</div>
@@ -225,22 +245,55 @@ function SettingsPane({
item, meta, isVideo, fullScreen,
onClose, onPrimaryClose, onRemix, onSendToVideo, onContinue, onClean,
cleaning, setCleaning, copy, onRefine,
+ annotation, onAnnotationChange,
}) {
const asideClasses = fullScreen
? 'absolute top-0 right-0 bottom-0 w-full sm:w-96 z-20 bg-port-card border-l border-port-border flex flex-col shadow-2xl'
: 'md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border max-h-[40vh] md:max-h-[92vh]';
+ const starred = !!annotation?.starred;
+ // Local draft state debounces saves so each keystroke doesn't PATCH.
+ // onSaveRef keeps the debounce effect off the parent's render churn —
+ // page components pass inline-arrow onAnnotationChange callbacks, which
+ // would otherwise restart the timer every time a media-gen event arrived.
+ const [noteDraft, setNoteDraft] = useState(annotation?.note ?? '');
+ const onSaveRef = useRef(onAnnotationChange);
+ useEffect(() => { onSaveRef.current = onAnnotationChange; });
+ useEffect(() => {
+ setNoteDraft(annotation?.note ?? '');
+ }, [item?.key, annotation?.note]);
+ useEffect(() => {
+ if (!onSaveRef.current) return undefined;
+ if (noteDraft === (annotation?.note ?? '')) return undefined;
+ const handle = setTimeout(() => {
+ onSaveRef.current?.({ note: noteDraft });
+ }, NOTE_DEBOUNCE_MS);
+ return () => clearTimeout(handle);
+ }, [noteDraft, annotation?.note]);
return (
<aside className={asideClasses} onClick={(e) => e.stopPropagation()}>
<header className="flex items-center justify-between p-3 border-b border-port-border">
<span className="text-xs uppercase tracking-wide text-gray-400">{isVideo ? 'Video' : 'Image'} settings</span>
- <button
- type="button"
- onClick={onClose}
- className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
- aria-label={fullScreen ? 'Hide settings' : 'Close'}
- >
- <X className="w-4 h-4" />
- </button>
+ <div className="flex items-center gap-1">
+ {onAnnotationChange && (
+ <button
+ type="button"
+ onClick={() => onAnnotationChange({ starred: !starred })}
+ className={`p-1.5 rounded ${starred ? 'bg-port-warning/90 text-black' : 'text-gray-400 hover:text-white hover:bg-port-border/50'}`}
+ aria-label={starred ? 'Unfavorite' : 'Favorite'}
+ title={starred ? 'Unfavorite (s)' : 'Favorite (s)'}
+ >
+ <Star className={`w-4 h-4 ${starred ? 'fill-current' : ''}`} />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={onClose}
+ className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ aria-label={fullScreen ? 'Hide settings' : 'Close'}
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
</header>
<div className="flex-1 overflow-y-auto p-3 space-y-3 text-xs">
@@ -261,6 +314,23 @@ function SettingsPane({
</div>
)}
+ {onAnnotationChange && (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-gray-500 uppercase tracking-wide">Notes</span>
+ <span className="text-[10px] text-gray-500">{noteDraft.length}/{NOTE_MAX}</span>
+ </div>
+ <textarea
+ value={noteDraft}
+ onChange={(e) => setNoteDraft(e.target.value.slice(0, NOTE_MAX))}
+ placeholder="Add a note — use this for cover, reshoot at 24fps, etc."
+ rows={3}
+ maxLength={NOTE_MAX}
+ className="w-full bg-port-bg border border-port-border rounded p-2 text-xs text-gray-200 placeholder:text-gray-600 focus:outline-none focus:border-port-accent resize-y"
+ />
+ </div>
+ )}
+
{item.negativePrompt && (
<div>
<div className="flex items-center justify-between mb-1">
diff --git a/client/src/hooks/useMediaAnnotations.js b/client/src/hooks/useMediaAnnotations.js
new file mode 100644
index 0000000000..e9e0b5d494
--- /dev/null
+++ b/client/src/hooks/useMediaAnnotations.js
@@ -0,0 +1,66 @@
+import { useCallback, useEffect, useState } from 'react';
+import { listMediaAnnotations, setMediaAnnotation } from '../services/api';
+import toast from '../components/ui/Toast';
+
+// Loads the full media-annotation map once and exposes optimistic-update
+// helpers. Shared by every gallery surface (MediaHistory, ImageGen, VideoGen,
+// MediaCollectionDetail) so favorites stay in sync across pages and the same
+// optimistic-update / revert behavior lives in one place.
+//
+// Returns:
+// annotations — { [key]: { starred, note, updatedAt } }
+// toggleStar(item) — flips starred for item.key (optimistic + revert on error)
+// updateAnnotation(key, patch) — generic partial update used by the lightbox note editor
+export function useMediaAnnotations() {
+ const [annotations, setAnnotations] = useState({});
+
+ useEffect(() => {
+ let cancelled = false;
+ listMediaAnnotations().then(
+ (res) => { if (!cancelled) setAnnotations(res?.annotations || {}); },
+ () => { /* fallback to empty map — non-fatal */ },
+ );
+ return () => { cancelled = true; };
+ }, []);
+
+ const updateAnnotation = useCallback(async (key, patch) => {
+ // Snapshot prior state for revert; build optimistic next state.
+ let prior;
+ setAnnotations((prev) => {
+ prior = prev[key];
+ const merged = {
+ starred: 'starred' in patch ? patch.starred : (prior?.starred ?? false),
+ note: 'note' in patch ? patch.note : (prior?.note ?? ''),
+ updatedAt: new Date().toISOString(),
+ };
+ const next = { ...prev };
+ if (!merged.starred && !merged.note) delete next[key];
+ else next[key] = merged;
+ return next;
+ });
+ const res = await setMediaAnnotation(key, patch).catch((err) => {
+ toast.error(err?.message || 'Failed to save annotation');
+ setAnnotations((prev) => {
+ const reverted = { ...prev };
+ if (prior) reverted[key] = prior;
+ else delete reverted[key];
+ return reverted;
+ });
+ return null;
+ });
+ return res?.entry ?? null;
+ }, []);
+
+ // Reads prior starred state from the functional setter so the callback's
+ // identity doesn't change on every annotations update (otherwise every
+ // MediaCard receives a new `onToggleStar` prop after each star flip).
+ const toggleStar = useCallback((item) => {
+ if (!item?.key) return;
+ setAnnotations((prev) => {
+ updateAnnotation(item.key, { starred: !prev[item.key]?.starred });
+ return prev;
+ });
+ }, [updateAnnotation]);
+
+ return { annotations, toggleStar, updateAnnotation };
+}
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index a2b1df0b9e..87f519027c 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -14,6 +14,7 @@ import Drawer from '../components/Drawer';
import { ImageGenTab } from '../components/settings/ImageGenTab';
import MediaCard from '../components/media/MediaCard';
import MediaLightbox from '../components/media/MediaLightbox';
+import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import StylePresetPicker from '../components/media/StylePresetPicker';
import BackendChipStrip from '../components/media/BackendChipStrip';
import { normalizeImage } from '../components/media/normalize';
@@ -22,6 +23,7 @@ import Flux2TokenBanner from '../components/imageGen/Flux2TokenBanner';
import ImageGenControls from '../components/imageGen/ImageGenControls';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
+import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import {
Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,
AlertTriangle, X, Film,
@@ -100,6 +102,8 @@ export default function ImageGen() {
const [gallery, setGallery] = useState([]);
const [preview, setPreview] = useState(null);
const [showHidden, setShowHidden] = useState(false);
+ const [favoritesOnly, setFavoritesOnly] = useState(false);
+ const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();
// FLUX.2 readiness — drives the gating banner. Lazy-fetched on the first
// selection of a flux2 model so we don't make an extra request when the
// user is only using mflux/external/codex.
@@ -449,10 +453,15 @@ export default function ImageGen() {
const flux2Issue = isFlux2Model && flux2Status
? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)
: null;
- const { visibleGallery, hiddenGallery } = useMemo(() => ({
- visibleGallery: gallery.filter((img) => !img.hidden),
- hiddenGallery: gallery.filter((img) => img.hidden),
- }), [gallery]);
+ const { visibleGallery, hiddenGallery } = useMemo(() => {
+ const visible = gallery.filter((img) => !img.hidden);
+ const hidden = gallery.filter((img) => img.hidden);
+ if (!favoritesOnly) return { visibleGallery: visible, hiddenGallery: hidden };
+ // Normalize to derive the canonical item.key rather than hand-building
+ // `image:${img.filename}` — the kind/ref convention lives in normalize.js.
+ const isStarred = (img) => !!annotations[normalizeImage(img).key]?.starred;
+ return { visibleGallery: visible.filter(isStarred), hiddenGallery: hidden.filter(isStarred) };
+ }, [gallery, favoritesOnly, annotations]);
const previewItems = useMemo(() => [
...visibleGallery.map(normalizeImage),
...(showHidden ? hiddenGallery.map(normalizeImage) : []),
@@ -1100,30 +1109,40 @@ export default function ImageGen() {
<MediaJobsQueue kind="image" />
- {visibleGallery.length > 0 && (
+ {(visibleGallery.length > 0 || favoritesOnly) && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">
- <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
<h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Recent renders ({Math.min(visibleGallery.length, 5)} of {visibleGallery.length})</h2>
- {visibleGallery.length > 5 && (
- <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>
- )}
- </div>
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {visibleGallery.slice(0, 5).map((img) => {
- const item = normalizeImage(img);
- return (
- <MediaCard
- key={item.key}
- item={item}
- onPreview={() => setPreview(item)}
- onRemix={() => handleRemix(img)}
- onSendToVideo={() => sendToVideo(img)}
- onDelete={() => handleDelete(img.filename)}
- onToggleHidden={() => handleToggleHidden(item)}
- />
- );
- })}
+ <div className="flex items-center gap-2">
+ <FavoritesFilterChip active={favoritesOnly} onToggle={() => setFavoritesOnly((v) => !v)} />
+ {visibleGallery.length > 5 && (
+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>
+ )}
+ </div>
</div>
+ {visibleGallery.length === 0 ? (
+ <div className="text-xs text-gray-500 py-3">No favorited images yet.</div>
+ ) : (
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
+ {visibleGallery.slice(0, 5).map((img) => {
+ const item = normalizeImage(img);
+ return (
+ <MediaCard
+ key={item.key}
+ item={item}
+ onPreview={() => setPreview(item)}
+ onRemix={() => handleRemix(img)}
+ onSendToVideo={() => sendToVideo(img)}
+ onDelete={() => handleDelete(img.filename)}
+ onToggleHidden={() => handleToggleHidden(item)}
+ starred={!!annotations[item.key]?.starred}
+ hasNote={!!annotations[item.key]?.note}
+ onToggleStar={toggleStar}
+ />
+ );
+ })}
+ </div>
+ )}
</div>
)}
@@ -1150,6 +1169,9 @@ export default function ImageGen() {
onSendToVideo={() => sendToVideo(img)}
onDelete={() => handleDelete(img.filename)}
onToggleHidden={() => handleToggleHidden(item)}
+ starred={!!annotations[item.key]?.starred}
+ hasNote={!!annotations[item.key]?.note}
+ onToggleStar={toggleStar}
/>
);
})}
@@ -1164,6 +1186,8 @@ export default function ImageGen() {
onRemix={(item) => item?.raw && handleRemix(item.raw)}
onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}
onClean={(item, level) => handleClean(item?.raw, level)}
+ annotation={preview ? annotations[preview.key] ?? null : null}
+ onAnnotationChange={preview ? (patch) => updateAnnotation(preview.key, patch) : undefined}
{...previewNavProps}
/>
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 9f89150d81..7990fa34f9 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -5,6 +5,7 @@ import toast from '../components/ui/Toast';
import MediaCard from '../components/media/MediaCard';
import MediaLightbox from '../components/media/MediaLightbox';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
+import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import {
getMediaCollection, updateMediaCollection,
addMediaCollectionItem, removeMediaCollectionItem,
@@ -43,6 +44,7 @@ export default function MediaCollectionDetail() {
const [editingName, setEditingName] = useState(false);
const [nameDraft, setNameDraft] = useState('');
const [preview, setPreview] = useState(null);
+ const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();
const refresh = useCallback(async () => {
setLoading(true);
@@ -204,6 +206,9 @@ export default function MediaCollectionDetail() {
onContinue={item.kind === 'video' ? handleContinue : undefined}
onDelete={handleRemove}
showCollectionMenu={false}
+ starred={!!annotations[key]?.starred}
+ hasNote={!!annotations[key]?.note}
+ onToggleStar={toggleStar}
/>
<button
type="button"
@@ -231,6 +236,8 @@ export default function MediaCollectionDetail() {
onSendToVideo={preview.kind === 'image' ? (i) => handleSendToVideo(i) : undefined}
onContinue={preview.kind === 'video' ? (i) => handleContinue(i.raw || i) : undefined}
onClean={preview.kind === 'image' ? (i, level) => handleClean(i?.raw || i, level) : undefined}
+ annotation={annotations[preview.key] ?? null}
+ onAnnotationChange={(patch) => updateAnnotation(preview.key, patch)}
/>
)}
</div>
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index eed124961b..41284cd09e 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -10,8 +10,10 @@ import { Combine, Image as ImageIcon, Film, Search, X } from 'lucide-react';
import toast from '../components/ui/Toast';
import MediaCard from '../components/media/MediaCard';
import MediaLightbox from '../components/media/MediaLightbox';
+import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
+import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import { getMediaNavProps } from '../lib/mediaNavigation';
import {
listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,
@@ -35,6 +37,8 @@ export default function MediaHistory() {
const [selected, setSelected] = useState([]); // video ids
const [stitching, setStitching] = useState(false);
const [preview, setPreview] = useState(null);
+ const [favoritesOnly, setFavoritesOnly] = useState(false);
+ const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();
const refresh = useCallback(async ({ silent = false } = {}) => {
if (!silent) setLoading(true);
@@ -84,10 +88,14 @@ export default function MediaHistory() {
() => tokens.length === 0 ? items : items.filter((_, idx) => tokens.every((t) => haystacks[idx].includes(t))),
[items, haystacks, tokens]
);
- const filtered = useMemo(
+ const kindFiltered = useMemo(
() => filter === 'all' ? searched : searched.filter(i => i.kind === filter),
[searched, filter]
);
+ const filtered = useMemo(
+ () => favoritesOnly ? kindFiltered.filter((i) => annotations[i.key]?.starred) : kindFiltered,
+ [kindFiltered, favoritesOnly, annotations]
+ );
const previewNavProps = getMediaNavProps(filtered, preview, setPreview);
const counts = useMemo(() => {
const c = { all: 0, image: 0, video: 0 };
@@ -231,6 +239,7 @@ export default function MediaHistory() {
{f.label} <span className="opacity-60">{counts[f.id]}</span>
</button>
))}
+ <FavoritesFilterChip active={favoritesOnly} onToggle={() => setFavoritesOnly((v) => !v)} size="md" />
</div>
<div className="flex items-center gap-1">
<Link to="/media/image" className="flex items-center gap-1.5 px-2 py-1 text-xs text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50">
@@ -295,6 +304,9 @@ export default function MediaHistory() {
selected={idx !== -1}
disabled={stitchMode && it.kind !== 'video'}
hideActions={stitchMode}
+ starred={!!annotations[it.key]?.starred}
+ hasNote={!!annotations[it.key]?.note}
+ onToggleStar={!stitchMode ? toggleStar : undefined}
/>
);
})}
@@ -308,6 +320,8 @@ export default function MediaHistory() {
onSendToVideo={handleSendToVideo}
onContinue={handleContinue}
onClean={(item, level) => handleClean(item?.raw, level)}
+ annotation={preview ? annotations[preview.key] ?? null : null}
+ onAnnotationChange={preview ? (patch) => updateAnnotation(preview.key, patch) : undefined}
{...previewNavProps}
/>
</div>
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 97685bd6c2..9bf5753589 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -41,7 +41,9 @@ import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import BatchQueuePanel from '../components/media/BatchQueuePanel';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
+import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
+import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import {
getVideoGenStatus, generateVideo, cancelVideoGen,
listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,
@@ -214,10 +216,23 @@ export default function VideoGen() {
visibleHistory: history.filter((v) => !v.hidden),
hiddenHistory: history.filter((v) => v.hidden),
}), [history]);
+ const [favoritesOnly, setFavoritesOnly] = useState(false);
+ const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();
+ // Gallery sections respect the favorites filter; the extend-mode dropdown
+ // (which reads visibleHistory directly) intentionally does not, since
+ // hiding non-favorites from the "pick a previous video" picker would
+ // surprise the user.
+ const { galleryVisible, galleryHidden } = useMemo(() => {
+ if (!favoritesOnly) return { galleryVisible: visibleHistory, galleryHidden: hiddenHistory };
+ // Normalize to derive the canonical item.key rather than hand-building
+ // `video:${v.id}` — the kind/ref convention lives in normalize.js.
+ const isStarred = (v) => !!annotations[normalizeVideo(v).key]?.starred;
+ return { galleryVisible: visibleHistory.filter(isStarred), galleryHidden: hiddenHistory.filter(isStarred) };
+ }, [visibleHistory, hiddenHistory, favoritesOnly, annotations]);
const previewItems = useMemo(() => [
- ...visibleHistory.map(normalizeVideo),
- ...(showHidden ? hiddenHistory.map(normalizeVideo) : []),
- ], [visibleHistory, hiddenHistory, showHidden]);
+ ...galleryVisible.map(normalizeVideo),
+ ...(showHidden ? galleryHidden.map(normalizeVideo) : []),
+ ], [galleryVisible, galleryHidden, showHidden]);
const previewNavProps = getMediaNavProps(previewItems, preview, setPreview);
const handleDeleteHistory = async (item) => {
@@ -1289,46 +1304,56 @@ export default function VideoGen() {
<MediaJobsQueue kind="video" />
- {visibleHistory.length > 0 && (
+ {(galleryVisible.length > 0 || favoritesOnly) && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">
- <div className="flex items-center justify-between">
- <h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Recent renders ({Math.min(visibleHistory.length, 5)} of {visibleHistory.length})</h2>
- {visibleHistory.length > 5 && (
- <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>
- )}
- </div>
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {visibleHistory.slice(0, 5).map((v) => {
- const item = normalizeVideo(v);
- return (
- <MediaCard
- key={item.key}
- item={item}
- onPreview={() => setPreview(item)}
- onContinue={() => handleContinueHistory(v)}
- onUpscale={() => handleUpscaleHistory(v)}
- onDelete={() => handleDeleteHistory(v)}
- onToggleHidden={() => handleToggleHistoryHidden(v)}
- />
- );
- })}
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Recent renders ({Math.min(galleryVisible.length, 5)} of {galleryVisible.length})</h2>
+ <div className="flex items-center gap-2">
+ <FavoritesFilterChip active={favoritesOnly} onToggle={() => setFavoritesOnly((v) => !v)} />
+ {galleryVisible.length > 5 && (
+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">View all →</Link>
+ )}
+ </div>
</div>
+ {galleryVisible.length === 0 ? (
+ <div className="text-xs text-gray-500 py-3">No favorited videos yet.</div>
+ ) : (
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
+ {galleryVisible.slice(0, 5).map((v) => {
+ const item = normalizeVideo(v);
+ return (
+ <MediaCard
+ key={item.key}
+ item={item}
+ onPreview={() => setPreview(item)}
+ onContinue={() => handleContinueHistory(v)}
+ onUpscale={() => handleUpscaleHistory(v)}
+ onDelete={() => handleDeleteHistory(v)}
+ onToggleHidden={() => handleToggleHistoryHidden(v)}
+ starred={!!annotations[item.key]?.starred}
+ hasNote={!!annotations[item.key]?.note}
+ onToggleStar={toggleStar}
+ />
+ );
+ })}
+ </div>
+ )}
</div>
)}
- {hiddenHistory.length > 0 && (
+ {galleryHidden.length > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-2">
<button
type="button"
onClick={() => setShowHidden((s) => !s)}
className="flex items-center justify-between w-full text-xs font-medium text-gray-400 uppercase tracking-wide hover:text-white"
>
- <span>{showHidden ? 'Hide' : 'Show'} hidden ({hiddenHistory.length})</span>
+ <span>{showHidden ? 'Hide' : 'Show'} hidden ({galleryHidden.length})</span>
<span className="text-xs text-gray-500">{showHidden ? '▾' : '▸'}</span>
</button>
{showHidden && (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {hiddenHistory.map((v) => {
+ {galleryHidden.map((v) => {
const item = normalizeVideo(v);
return (
<MediaCard
@@ -1338,6 +1363,9 @@ export default function VideoGen() {
onContinue={() => handleContinueHistory(v)}
onDelete={() => handleDeleteHistory(v)}
onToggleHidden={() => handleToggleHistoryHidden(v)}
+ starred={!!annotations[item.key]?.starred}
+ hasNote={!!annotations[item.key]?.note}
+ onToggleStar={toggleStar}
/>
);
})}
@@ -1350,6 +1378,8 @@ export default function VideoGen() {
item={preview}
onClose={() => setPreview(null)}
onContinue={(item) => handleContinueHistory(item.raw)}
+ annotation={preview ? annotations[preview.key] ?? null : null}
+ onAnnotationChange={preview ? (patch) => updateAnnotation(preview.key, patch) : undefined}
{...previewNavProps}
/>
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 8501401ed2..f35d82a068 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -116,6 +116,18 @@ export const removeMediaCollectionItem = (id, key) => request(`/media/collection
method: 'DELETE',
});
+// Media annotations — per-item star + free-text note, keyed by "<kind>:<ref>"
+// (same shape as collections + the client-side `item.key` from normalize.js).
+// Decoupled from generation pipeline data so favorites survive job pruning.
+// GET returns `{ annotations: { [key]: { starred, note, updatedAt } } }`.
+// PATCH partial-merges; the entry is removed entirely when both fields end
+// up empty — `entry` in the response is `null` to signal that.
+export const listMediaAnnotations = () => request('/media/annotations');
+export const setMediaAnnotation = (key, patch) => request(`/media/annotations/${encodeURIComponent(key)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+});
+
// Models management (HF cache + LoRAs)
export const listCachedModels = () => request('/image-video/models');
export const deleteCachedModel = (dirName) => request(`/image-video/models/hf/${encodeURIComponent(dirName)}`, { method: 'DELETE' });
diff --git a/server/index.js b/server/index.js
index 8199468762..f2a78159a0 100644
--- a/server/index.js
+++ b/server/index.js
@@ -67,6 +67,7 @@ import searchRoutes from './routes/search.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
import mediaCollectionsRoutes from './routes/mediaCollections.js';
+import mediaAnnotationsRoutes from './routes/mediaAnnotations.js';
import dataSyncRoutes from './routes/dataSync.js';
import identityRoutes from './routes/identity.js';
import instancesRoutes from './routes/instances.js';
@@ -273,6 +274,7 @@ app.use('/api/search', searchRoutes);
app.use('/api/palette', paletteRoutes);
app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);
app.use('/api/media/collections', mediaCollectionsRoutes);
+app.use('/api/media/annotations', mediaAnnotationsRoutes);
app.use('/api/attachments', attachmentsRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/database', databaseRoutes);
diff --git a/server/lib/mediaItemKey.js b/server/lib/mediaItemKey.js
new file mode 100644
index 0000000000..c3556ac454
--- /dev/null
+++ b/server/lib/mediaItemKey.js
@@ -0,0 +1,33 @@
+/**
+ * Shared `<kind>:<ref>` key vocabulary for media items.
+ *
+ * Both mediaCollections.js and mediaAnnotations.js identify generated media
+ * by `{ kind: 'image'|'video', ref: <filename|videoId> }` and serialize that
+ * to the API surface as `"<kind>:<ref>"`. This module centralizes the rules
+ * so the two services can't diverge on what counts as a valid kind, the
+ * maximum ref length, or how `:` is rejected inside refs.
+ */
+
+export const ITEM_KINDS = ['image', 'video'];
+export const ITEM_KIND = new Set(ITEM_KINDS);
+export const REF_MAX_LENGTH = 256;
+
+export const itemKey = (it) => `${it.kind}:${it.ref}`;
+
+// Split `<kind>:<ref>` on the first `:` and validate both halves. Returns
+// `{ kind, ref }` on success, `null` on any rejection. A ref containing `:`
+// would be unambiguously persisted but ambiguously addressable via the REST
+// surface (DELETE /:key, coverKey lookups), so we reject it here.
+export function parseKey(key) {
+ if (typeof key !== 'string') return null;
+ const idx = key.indexOf(':');
+ if (idx <= 0) return null;
+ const kind = key.slice(0, idx);
+ const ref = key.slice(idx + 1);
+ if (!ITEM_KIND.has(kind)) return null;
+ if (!ref || ref.length > REF_MAX_LENGTH) return null;
+ if (ref.includes(':')) return null;
+ return { kind, ref };
+}
+
+export const isValidKey = (key) => parseKey(key) !== null;
diff --git a/server/routes/mediaAnnotations.js b/server/routes/mediaAnnotations.js
new file mode 100644
index 0000000000..9bf22dc98c
--- /dev/null
+++ b/server/routes/mediaAnnotations.js
@@ -0,0 +1,46 @@
+/**
+ * GET /api/media/annotations → { [key]: { starred, note, updatedAt } }
+ * PATCH /api/media/annotations/:key → updated entry or null (if pruned)
+ * body: { starred?: boolean, note?: string }
+ *
+ * Key shape: `<kind>:<ref>` where kind ∈ {image, video} and ref has no `:`.
+ * Matches the convention enforced by mediaCollections.js and produced by the
+ * client-side normalize.js (`item.key`).
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as svc from '../services/mediaAnnotations.js';
+
+const router = Router();
+
+const SERVICE_ERROR_STATUS = {
+ [svc.ERR_VALIDATION]: 400,
+};
+
+const mapServiceError = (err) => {
+ const status = SERVICE_ERROR_STATUS[err?.code];
+ if (status) return new ServerError(err.message, { status, code: err.code });
+ return err;
+};
+
+const patchSchema = z.object({
+ starred: z.boolean().optional(),
+ note: z.string().max(svc.NOTE_MAX_LENGTH).optional(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include starred and/or note' });
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json({ annotations: await svc.listAnnotations() });
+}));
+
+router.patch('/:key', asyncHandler(async (req, res) => {
+ const body = validateRequest(patchSchema, req.body ?? {});
+ // Express decodes the path param, but the key still has to round-trip through
+ // svc validation so a hand-rolled curl can't sneak past.
+ const updated = await svc.setAnnotation(req.params.key, body).catch((err) => { throw mapServiceError(err); });
+ res.json({ key: req.params.key, entry: updated });
+}));
+
+export default router;
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.js
new file mode 100644
index 0000000000..84164e7838
--- /dev/null
+++ b/server/services/mediaAnnotations.js
@@ -0,0 +1,105 @@
+/**
+ * Media Annotations
+ *
+ * Per-item star + free-text note, keyed by the same `<kind>:<ref>` convention
+ * used by mediaCollections.js and the client-side normalize.js (`item.key`).
+ * Persisted to data/media-annotations.json as a single
+ * `{ annotations: { [key]: { starred, note, updatedAt } } }` document.
+ *
+ * Decoupled from the generation pipeline records (media-jobs.json,
+ * video-history.json) so annotations survive pruning/archival of jobs.
+ */
+
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
+import { isValidKey } from '../lib/mediaItemKey.js';
+
+const STATE_PATH = join(PATHS.data, 'media-annotations.json');
+
+export const ERR_VALIDATION = 'VALIDATION_ERROR';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+export const NOTE_MAX_LENGTH = 2000;
+
+const DEFAULT_STATE = { annotations: {} };
+
+export { isValidKey };
+
+const sanitizeEntry = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const starred = raw.starred === true;
+ const note = typeof raw.note === 'string' ? raw.note.slice(0, NOTE_MAX_LENGTH) : '';
+ if (!starred && !note) return null;
+ const updatedAt = typeof raw.updatedAt === 'string' && !Number.isNaN(Date.parse(raw.updatedAt))
+ ? raw.updatedAt
+ : new Date().toISOString();
+ return { starred, note, updatedAt };
+};
+
+const readAll = async () => {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const annotations = raw && typeof raw.annotations === 'object' && raw.annotations !== null
+ ? raw.annotations
+ : {};
+ const out = {};
+ for (const [key, value] of Object.entries(annotations)) {
+ if (!isValidKey(key)) continue;
+ const s = sanitizeEntry(value);
+ if (s) out[key] = s;
+ }
+ return out;
+};
+
+export async function listAnnotations() {
+ return await readAll();
+}
+
+/**
+ * Partial merge with prune-on-empty.
+ *
+ * Patch may include `starred` (boolean) and/or `note` (string). Fields not in
+ * the patch keep their prior value. If the merged entry ends up with
+ * `starred:false` AND an empty `note`, the entry is removed entirely to keep
+ * the file lean.
+ *
+ * Returns the merged entry, or `null` if it was pruned.
+ */
+export async function setAnnotation(key, patch) {
+ if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
+ if (!patch || typeof patch !== 'object') {
+ throw makeErr('patch must include starred and/or note', ERR_VALIDATION);
+ }
+ const hasStarred = Object.prototype.hasOwnProperty.call(patch, 'starred');
+ const hasNote = Object.prototype.hasOwnProperty.call(patch, 'note');
+ if (!hasStarred && !hasNote) {
+ throw makeErr('patch must include starred and/or note', ERR_VALIDATION);
+ }
+ if (hasStarred && typeof patch.starred !== 'boolean') {
+ throw makeErr('starred must be boolean', ERR_VALIDATION);
+ }
+ if (hasNote && typeof patch.note !== 'string') {
+ throw makeErr('note must be string', ERR_VALIDATION);
+ }
+ if (hasNote && patch.note.length > NOTE_MAX_LENGTH) {
+ throw makeErr(`note exceeds max length (${NOTE_MAX_LENGTH})`, ERR_VALIDATION);
+ }
+
+ const all = await readAll();
+ const prior = all[key] ?? { starred: false, note: '', updatedAt: null };
+ const merged = {
+ starred: hasStarred ? patch.starred : prior.starred,
+ note: hasNote ? patch.note : prior.note,
+ updatedAt: new Date().toISOString(),
+ };
+
+ const next = { ...all };
+ if (!merged.starred && !merged.note) {
+ delete next[key];
+ await atomicWrite(STATE_PATH, { annotations: next });
+ return null;
+ }
+ next[key] = merged;
+ await atomicWrite(STATE_PATH, { annotations: next });
+ return merged;
+}
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
new file mode 100644
index 0000000000..418bf23eca
--- /dev/null
+++ b/server/services/mediaAnnotations.test.js
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => fileStore.has(path) ? fileStore.get(path) : fallback),
+}));
+
+const svc = await import('./mediaAnnotations.js');
+
+describe('mediaAnnotations service', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ });
+
+ it('listAnnotations returns {} for fresh state', async () => {
+ expect(await svc.listAnnotations()).toEqual({});
+ });
+
+ it('setAnnotation persists a starred entry', async () => {
+ const r = await svc.setAnnotation('image:foo.png', { starred: true });
+ expect(r.starred).toBe(true);
+ expect(r.note).toBe('');
+ expect(typeof r.updatedAt).toBe('string');
+ const all = await svc.listAnnotations();
+ expect(all['image:foo.png'].starred).toBe(true);
+ });
+
+ it('setAnnotation persists a note-only entry', async () => {
+ const r = await svc.setAnnotation('video:abc-1', { note: 'reshoot at 24fps' });
+ expect(r.starred).toBe(false);
+ expect(r.note).toBe('reshoot at 24fps');
+ });
+
+ it('setAnnotation partial-merges (note keeps prior starred)', async () => {
+ await svc.setAnnotation('image:a.png', { starred: true });
+ const r = await svc.setAnnotation('image:a.png', { note: 'looks great' });
+ expect(r.starred).toBe(true);
+ expect(r.note).toBe('looks great');
+ });
+
+ it('setAnnotation prunes when both fields become empty', async () => {
+ await svc.setAnnotation('image:a.png', { starred: true, note: 'hi' });
+ const r = await svc.setAnnotation('image:a.png', { starred: false, note: '' });
+ expect(r).toBeNull();
+ const all = await svc.listAnnotations();
+ expect(all['image:a.png']).toBeUndefined();
+ });
+
+ it('setAnnotation rejects invalid key (no colon)', async () => {
+ await expect(svc.setAnnotation('foo.png', { starred: true }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('setAnnotation rejects unknown kind', async () => {
+ await expect(svc.setAnnotation('audio:foo.mp3', { starred: true }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('setAnnotation rejects ref containing `:`', async () => {
+ await expect(svc.setAnnotation('image:foo:bar.png', { starred: true }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('setAnnotation rejects empty patch', async () => {
+ await expect(svc.setAnnotation('image:a.png', {}))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('setAnnotation rejects note over max length', async () => {
+ const long = 'x'.repeat(svc.NOTE_MAX_LENGTH + 1);
+ await expect(svc.setAnnotation('image:a.png', { note: long }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('setAnnotation rejects non-boolean starred', async () => {
+ await expect(svc.setAnnotation('image:a.png', { starred: 'yes' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('listAnnotations filters out invalid keys and entries from disk', async () => {
+ fileStore.set('/mock/data/media-annotations.json', {
+ annotations: {
+ 'image:good.png': { starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },
+ 'badkey': { starred: true },
+ 'audio:foo.mp3': { starred: true },
+ 'image:empty.png': { starred: false, note: '' },
+ },
+ });
+ const all = await svc.listAnnotations();
+ expect(Object.keys(all)).toEqual(['image:good.png']);
+ });
+
+ it('isValidKey accepts image:<ref> and video:<ref>', () => {
+ expect(svc.isValidKey('image:foo.png')).toBe(true);
+ expect(svc.isValidKey('video:uuid-1')).toBe(true);
+ expect(svc.isValidKey('image:')).toBe(false);
+ expect(svc.isValidKey(':foo')).toBe(false);
+ expect(svc.isValidKey('imagefoo')).toBe(false);
+ expect(svc.isValidKey(null)).toBe(false);
+ });
+});
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index e3a6d8502b..fde2a2860b 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -13,6 +13,7 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
+import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';
const STATE_PATH = join(PATHS.data, 'media-collections.json');
@@ -23,12 +24,9 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });
export const NAME_MAX_LENGTH = 80;
export const DESCRIPTION_MAX_LENGTH = 500;
-export const REF_MAX_LENGTH = 256;
export const ITEMS_MAX = 5000;
-const ITEM_KIND = new Set(['image', 'video']);
-
-export const itemKey = (it) => `${it.kind}:${it.ref}`;
+export { REF_MAX_LENGTH, itemKey };
const DEFAULT_STATE = { collections: [] };