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: implement catalog ingredient file upload and voice-memo capture (#2038)

Adam Eivycfc94ef18f15
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 08f0a5e257..307d08f02e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,6 +9,10 @@
- **Switch project workspaces from ⌘K and voice, and CoS now auto-snapshots the workspace it leaves.** A new `workspace_switch` action ("switch workspace to BookLoom", "restore my PortOS context") saves a snapshot of the workspace you're leaving, then reconciles the target project's saved context — git branch, in-repo shell sessions, scoped tasks — and reports what's still live to re-attach; it appears in the ⌘K palette and resolves by voice. When CoS dispatches a coding agent against a different app/repo than it was last working in, it now silently snapshots the previous workspace's context first (snapshot-only — no auto-restore, no LLM calls), so switching between repos preserves what each project looked like, visible on the Workspace Contexts page (#2035).
+## Catalog
+
+- **Catalog ingredient media now accepts file uploads and voice memos, replacing the two "coming soon" stubs.** The ingredient Media panel gained an "Upload file" picker + real drag-and-drop of image/audio/video files (dropping a file, not just an in-app gallery tile, now attaches it) and a "Record memo" button that captures a WAV via the browser, transcribes it through the existing Whisper pipeline, and attaches the audio with its transcript in the caption. Uploads land in the matching federating library dir (images as PNG, audio, video) so a sync peer receives the bytes, not a broken reference — the same two-layer path gallery attachments already use. Audio and video attachments now render inline players in the panel (#2038).
+
## Tribe
- **Tribe touchpoints now auto-log from synced calendar events and messages (#2033).** The Tribe model always supported `source: 'calendar'|'message'` touchpoints but nothing produced them. You can now record known emails/handles on a person (new "Emails & handles" field), and whenever a calendar sync or message sync ingests an event/message involving that person, PortOS logs a touchpoint automatically — deterministic email/handle matching (plus exact unique-name fallback), no LLM calls. Calendar touchpoints dedupe per event id and only count events that have already happened; message touchpoints dedupe per thread + day so a long thread doesn't spam the timeline. Auto-logged touchpoints advance `last_contact_on` so overdue/cadence status reflects them, and the Tribe timeline shows each touchpoint's source with an icon (Calendar / Message / Manual). Matching is pure and unit-tested (`server/lib/tribeMatch.js`); idempotency is enforced by a partial unique index on `(person_id, dedupe_key)`.
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 38bdd2e3c2..45145e9dda 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -7,7 +7,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown } from 'lucide-react';
+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown, Upload, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
getCatalogIngredientDetails,
@@ -22,7 +22,10 @@ import {
attachCatalogIngredientMedia,
setCatalogIngredientPortrait,
detachCatalogIngredientMedia,
+ uploadCatalogIngredientMediaFile,
+ recordCatalogIngredientVoiceMemo,
} from '../services/apiCatalog';
+import { startMemoRecording, arrayBufferToBase64 } from '../lib/audioRecorder';
import { listImageGallery } from '../services/apiImageVideo';
import { generateImage } from '../services/apiSystem';
import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
@@ -275,6 +278,36 @@ export default function CatalogIngredient() {
toast.success(hasPortrait ? 'Generated image attached' : 'Generated portrait set');
}, [record, media, refreshMedia]);
+ // Upload a dropped/picked file straight onto the ingredient. The server picks
+ // the media kind (image→reference, audio, video) from the MIME and stores the
+ // bytes in the matching federating library dir. Reconcile via refreshMedia.
+ const handleUploadFile = useCallback(async (file) => {
+ if (!record || !file) return;
+ const dataBase64 = arrayBufferToBase64(await file.arrayBuffer());
+ const ok = await uploadCatalogIngredientMediaFile(
+ record.id,
+ { dataBase64, mimeType: file.type || 'application/octet-stream', filename: file.name },
+ { silent: true },
+ ).then(() => true).catch((err) => { toast.error(err?.message || 'Upload failed'); return false; });
+ if (!ok) return;
+ refreshMedia();
+ toast.success('File attached');
+ }, [record, refreshMedia]);
+
+ // Attach a recorded voice memo — the server transcribes it via Whisper and
+ // stores the transcript in the audio row's caption.
+ const handleRecordVoiceMemo = useCallback(async (clip) => {
+ if (!record || !clip?.audioBase64) return;
+ const ok = await recordCatalogIngredientVoiceMemo(
+ record.id,
+ { audioBase64: clip.audioBase64, mimeType: clip.mimeType },
+ { silent: true },
+ ).then(() => true).catch((err) => { toast.error(err?.message || 'Voice memo failed'); return false; });
+ if (!ok) return;
+ refreshMedia();
+ toast.success('Voice memo attached');
+ }, [record, refreshMedia]);
+
const handleSave = async () => {
if (!record) return;
const trimmedName = name.trim();
@@ -489,6 +522,8 @@ export default function CatalogIngredient() {
onAttach={handleAttachMedia}
onSetPortrait={handleSetPortrait}
onDetach={handleDetachMedia}
+ onUploadFile={handleUploadFile}
+ onRecordVoice={handleRecordVoiceMemo}
genIngredientId={record.id}
genName={name}
genDescription={genDescription}
@@ -869,10 +904,11 @@ function RelationsPanel({ record, relations, onAdd, onRemove }) {
// the panel scopes its picker to the existing gallery/history. The portrait
// (one per ingredient) renders large at the head; other attachments tile below.
// Drag-and-drop accepts an in-app gallery filename dragged as text (the
-// dashboard/gallery tiles set `dataTransfer.setData('text/plain', filename)`);
-// file-upload + voice-memo capture are intentionally out of scope here and
-// land via the separate `[catalog-source-kinds-url-file-voice]` item — the
-// `onAttach(mediaKey, kind)` seam is all those paths need to reuse.
+// dashboard/gallery tiles set `dataTransfer.setData('text/plain', filename)`) OR
+// a real file dropped from the OS. "Upload file" (image/audio/video) and "Record
+// memo" (MediaRecorder → WAV → Whisper transcript) persist through the catalog
+// media-upload/voice routes into the federating library dirs, then attach via
+// the same media-refs seam gallery picks use.
// "Generate" affordance for the Media panel — turns the ingredient's
// description into an image via the same image-gen queue the Universe canon
// renders use. The generated file lands in the media library as `<jobId>.png`;
@@ -1045,20 +1081,68 @@ function GenerateImageControl({ ingredientId, name, description, universeId, onC
);
}
-function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, genIngredientId, genName, genDescription, genUniverseId, onGenerated }) {
+function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, onUploadFile, onRecordVoice, genIngredientId, genName, genDescription, genUniverseId, onGenerated }) {
const [pickerOpen, setPickerOpen] = useState(false);
const [dragOver, setDragOver] = useState(false);
+ const [busy, setBusy] = useState(false); // upload or transcription in flight
+ const [recording, setRecording] = useState(false);
+ const fileInputRef = useRef(null);
+ const recorderRef = useRef(null);
const list = Array.isArray(media) ? media : [];
const portrait = list.find((m) => m.kind === 'portrait');
const others = list.filter((m) => m.kind !== 'portrait');
+ // Release the mic if the panel unmounts mid-recording (navigating away).
+ useEffect(() => () => { recorderRef.current?.cancel?.(); }, []);
+
+ const doUpload = async (file) => {
+ if (!file || busy) return;
+ setBusy(true);
+ await onUploadFile(file);
+ setBusy(false);
+ };
+
const onDrop = (e) => {
e.preventDefault();
setDragOver(false);
// In-app gallery DnD: the dragged tile carries its filename as text.
const key = (e.dataTransfer.getData('text/plain') || '').trim();
if (key) { onAttach(key, 'reference'); return; }
- toast.error('Drop a gallery image, or use “Pick from gallery”. File upload coming soon.');
+ const file = e.dataTransfer.files?.[0];
+ if (file) { doUpload(file); return; }
+ toast.error('Drop a gallery image, a file, or use “Pick from gallery”.');
+ };
+
+ const onFilePicked = (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = ''; // allow re-picking the same file
+ if (file) doUpload(file);
+ };
+
+ const startRecording = async () => {
+ const handle = await startMemoRecording().catch((err) => {
+ toast.error(err?.message || 'Microphone unavailable');
+ return null;
+ });
+ if (!handle) return;
+ recorderRef.current = handle;
+ setRecording(true);
+ };
+
+ const stopRecording = async () => {
+ const handle = recorderRef.current;
+ if (!handle) return;
+ recorderRef.current = null;
+ setRecording(false);
+ const clip = await handle.stop().catch((err) => { toast.error(err?.message || 'Recording failed'); return null; });
+ if (!clip?.audioBase64) return;
+ if (clip.peak !== undefined && clip.peak < 0.01) {
+ toast.error('That memo was silent — check your microphone and try again.');
+ return;
+ }
+ setBusy(true);
+ await onRecordVoice(clip);
+ setBusy(false);
};
return (
@@ -1067,12 +1151,28 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, ge
<h2 className="text-sm font-semibold text-white flex items-center gap-1.5">
<ImageIcon size={14} aria-hidden="true" /> Media
</h2>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<GenerateImageControl ingredientId={genIngredientId} name={genName} description={genDescription} universeId={genUniverseId} onComplete={onGenerated} />
<button type="button" onClick={() => setPickerOpen(true)}
className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent">
<Plus size={12} aria-hidden="true" /> Pick from gallery
</button>
+ <button type="button" onClick={() => fileInputRef.current?.click()} disabled={busy || recording}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40">
+ <Upload size={12} aria-hidden="true" /> Upload file
+ </button>
+ {!recording ? (
+ <button type="button" onClick={startRecording} disabled={busy}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40">
+ <Mic size={12} aria-hidden="true" /> Record memo
+ </button>
+ ) : (
+ <button type="button" onClick={stopRecording}
+ className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-error text-port-error hover:bg-port-error/10 animate-pulse">
+ <Square size={12} aria-hidden="true" /> Stop &amp; transcribe
+ </button>
+ )}
+ <input ref={fileInputRef} type="file" accept="image/*,audio/*,video/*" onChange={onFilePicked} className="hidden" />
</div>
</div>
@@ -1082,7 +1182,9 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, ge
onDrop={onDrop}
className={`mb-3 rounded-lg border border-dashed p-3 text-center text-xs transition-colors ${dragOver ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-500'}`}
>
- Drag a gallery image here to attach it as a reference.
+ {busy
+ ? (<span className="inline-flex items-center gap-1"><Loader2 size={12} className="animate-spin" aria-hidden="true" /> Uploading…</span>)
+ : 'Drag a gallery image or a file here to attach it (image, audio, or video).'}
</div>
{portrait && (
@@ -1103,7 +1205,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, ge
)}
{list.length === 0 && (
- <p className="text-xs text-gray-500">No media yet. Attach a generated portrait, a mood/reference image, or a recorded memo (memo capture coming soon).</p>
+ <p className="text-xs text-gray-500">No media yet. Attach a generated portrait, a mood/reference image, an uploaded file, or a recorded voice memo.</p>
)}
{pickerOpen && (
@@ -1122,15 +1224,32 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, ge
// One media attachment tile. Images render via <MediaImage> (gracefully shows a
// "syncing" placeholder when the asset hasn't arrived — the same surface the
-// `missing` integrity flag warns about). Non-image kinds render a labeled chip.
+// `missing` integrity flag warns about). Audio/video render inline players
+// (their bytes are served from /data/audio and /data/videos); a voice memo's
+// transcript rides in `caption`. Other kinds render a labeled chip.
function MediaTile({ m, missing, isPortrait = false, onSetPortrait, onDetach }) {
const isImage = m.kind === 'portrait' || m.kind === 'reference';
+ const isAudio = m.kind === 'audio';
+ const isVideo = m.kind === 'video';
return (
<div className="relative group rounded border border-port-border overflow-hidden bg-port-bg">
- {isImage ? (
+ {isImage && (
<MediaImage src={`/data/images/${m.mediaKey}`} alt={m.caption || m.kind}
className={isPortrait ? 'w-full max-w-[180px] aspect-square object-cover' : 'w-full aspect-square object-cover'} />
- ) : (
+ )}
+ {isAudio && (
+ <div className="p-2 flex flex-col gap-1">
+ <div className="text-[10px] uppercase tracking-wider text-gray-400 flex items-center gap-1">
+ <Mic size={10} aria-hidden="true" /> {m.role === 'voice-memo' ? 'voice memo' : 'audio'}
+ </div>
+ <audio controls preload="none" src={`/data/audio/${m.mediaKey}`} className="w-full" />
+ {m.caption && <p className="text-[11px] text-gray-300 whitespace-pre-wrap line-clamp-4">{m.caption}</p>}
+ </div>
+ )}
+ {isVideo && (
+ <video controls preload="none" src={`/data/videos/${m.mediaKey}`} className="w-full aspect-square object-cover bg-black" />
+ )}
+ {!isImage && !isAudio && !isVideo && (
<div className="w-full aspect-square flex items-center justify-center text-[10px] uppercase tracking-wider text-gray-400 px-1 text-center">
{m.kind}<br />{m.mediaKey}
</div>
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index 3fc45ed21f..334f7f2999 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -181,6 +181,16 @@ export const setCatalogIngredientPortrait = (id, body, options) =>
export const detachCatalogIngredientMedia = (id, body, options) =>
request(`/catalog/ingredients/${enc(id)}/media`, { method: 'DELETE', body: JSON.stringify(body), ...options });
+// Upload a raw file (base64 + MIME) onto an ingredient; server picks the media
+// kind + library dir from the MIME and returns the attached media row.
+export const uploadCatalogIngredientMediaFile = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/upload`, { method: 'POST', body: JSON.stringify(body), ...options });
+
+// Attach a recorded voice memo (base64 WAV) — server transcribes via Whisper and
+// returns `{ media, transcript }`.
+export const recordCatalogIngredientVoiceMemo = (id, body, options) =>
+ request(`/catalog/ingredients/${enc(id)}/media/voice`, { method: 'POST', body: JSON.stringify(body), ...options });
+
// --- Bulk import / export ----------------------------------------------
export const bulkImportCatalogIngredients = (body, options) =>
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 3bf657613a..2d22e8159d 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -371,6 +371,28 @@ export const catalogMediaDetachSchema = z.object({
kind: z.enum(MEDIA_KINDS),
}).strict();
+// File-upload attach body: raw base64 bytes + the browser-reported MIME. The
+// server decides the media `kind` (image→reference, audio, video) from the MIME
+// and persists into the matching federating library dir before attaching — the
+// client never picks the storage kind. 32 MB base64 (~24 MB raw) upper-bounds a
+// runaway paste; per-category size is re-checked server-side.
+export const catalogMediaFileUploadSchema = z.object({
+ dataBase64: z.string().min(1).max(32 * 1024 * 1024),
+ mimeType: z.string().trim().min(1).max(128),
+ filename: z.string().trim().max(300).optional().nullable(),
+ role: z.string().trim().max(64).optional().nullable(),
+ caption: z.string().trim().max(2_000).optional().nullable(),
+}).strict();
+
+// Voice-memo body: a recorded WAV (16 kHz mono, base64) the server transcribes
+// via Whisper and attaches as a `kind:'audio'` media row with the transcript in
+// `caption`. 16 MB base64 (~12 MB raw) fits several minutes of 16 kHz mono WAV.
+export const catalogMediaVoiceMemoSchema = z.object({
+ audioBase64: z.string().min(1).max(16 * 1024 * 1024),
+ mimeType: z.string().trim().max(64).optional(),
+ role: z.string().trim().max(64).optional().nullable(),
+}).strict();
+
export const catalogScrapCommitSchema = z.object({
accepted: z.array(catalogIngredientCreateSchema.extend({
// Optional source-span hint (server forwards as-is to linkIngredientToSource).
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 623c640b1e..3dd23b2615 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -18,6 +18,8 @@ import {
catalogRelationLinkSchema,
catalogMediaAttachSchema,
catalogMediaDetachSchema,
+ catalogMediaFileUploadSchema,
+ catalogMediaVoiceMemoSchema,
catalogPortraitSetSchema,
catalogIngredientQuerySchema,
catalogTagQuerySchema,
@@ -45,6 +47,7 @@ import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredientsForScrap } from '../services/catalogExtraction.js';
import { ingestFromUrl, ingestFromFile, ingestFromVoice, ingestFromBrain } from '../services/catalogIngestSources.js';
+import { uploadIngredientMediaFile, recordIngredientVoiceMemo } from '../services/catalogMedia.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
@@ -495,6 +498,24 @@ router.delete('/ingredients/:id/media', asyncHandler(async (req, res) => {
res.status(204).end();
}));
+// Upload a file (drag-drop / picker) straight onto an ingredient: the service
+// stores it in the matching federating library dir (image→data/images as PNG,
+// audio→data/audio, video→data/videos) and attaches the reference. The 404 for a
+// missing ingredient is raised inside the service.
+router.post('/ingredients/:id/media/upload', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogMediaFileUploadSchema, req.body);
+ const media = await uploadIngredientMediaFile({ ingredientId: req.params.id, ...body });
+ res.status(201).json(media);
+}));
+
+// Record a voice memo onto an ingredient: transcribe via Whisper, persist the
+// audio, and attach a kind:'audio' row with the transcript in caption.
+router.post('/ingredients/:id/media/voice', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogMediaVoiceMemoSchema, req.body);
+ const result = await recordIngredientVoiceMemo({ ingredientId: req.params.id, ...body });
+ res.status(201).json(result);
+}));
+
// Bulk-create ingredients from a markdown / CSV / JSON dump — no LLM round
// trip, unlike the scrap → extract → commit path. The whole batch commits
// or rolls back together so a malformed entry can't leave the catalog
diff --git a/server/services/catalogMedia.js b/server/services/catalogMedia.js
new file mode 100644
index 0000000000..75ef339dd6
--- /dev/null
+++ b/server/services/catalogMedia.js
@@ -0,0 +1,134 @@
+// Direct file-upload + voice-memo attachment for catalog ingredients.
+//
+// The existing `catalogIngestSources.ingestFromVoice` runs audio through the
+// scrap → LLM-extraction → review flow (it MINTS new ingredients). This module
+// is the other seam: take a file the user dropped/picked, or a memo they just
+// recorded, and attach it DIRECTLY to an ingredient that already exists.
+//
+// Bytes land in a peer-federating library dir (images/audio/videos) so the
+// `media_key` reference federates through catalogSync while the file itself
+// federates through peerMediaLibrarySync — the same two-layer path gallery
+// attachments already use. Nothing here calls hashImageForManifest; the library
+// replica hashes the file when it federates.
+
+import { randomUUID } from 'crypto';
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { getIngredient, attachMedia } from './catalogDB.js';
+import { saveUploadedGalleryImage } from './imageGen/local.js';
+import { transcribe } from './voice/stt.js';
+
+// media_key caption cap mirrors catalogMediaAttachSchema.caption (2 000 chars).
+const MAX_CAPTION = 2_000;
+
+// MIME → file extension for the non-image library dirs (images always normalize
+// to .png in saveUploadedGalleryImage). Unknown-but-recognized-category MIMEs
+// fall back to a sane container extension.
+const AUDIO_EXT = {
+ 'audio/webm': 'webm', 'audio/ogg': 'ogg', 'audio/wav': 'wav', 'audio/x-wav': 'wav',
+ 'audio/wave': 'wav', 'audio/mpeg': 'mp3', 'audio/mp3': 'mp3', 'audio/mp4': 'm4a', 'audio/aac': 'm4a',
+};
+const VIDEO_EXT = {
+ 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'video/ogg': 'ogv',
+};
+
+/**
+ * Classify a browser-reported MIME into the media library it belongs in. Pure —
+ * unit-tested. Strips any `;codecs=…` parameter first. Returns
+ * `{ category, kind, ext }` or `null` for a MIME we don't federate (documents
+ * have no library dir yet, so attaching one would break references on peers).
+ */
+export function classifyUploadMime(mimeType) {
+ const mime = (mimeType || '').toLowerCase().split(';')[0].trim();
+ if (mime.startsWith('image/')) return { category: 'image', kind: 'reference', ext: 'png' };
+ if (mime.startsWith('audio/')) return { category: 'audio', kind: 'audio', ext: AUDIO_EXT[mime] || 'webm' };
+ if (mime.startsWith('video/')) return { category: 'video', kind: 'video', ext: VIDEO_EXT[mime] || 'mp4' };
+ return null;
+}
+
+// Write raw bytes into a federating library dir under a collision-free
+// `upload-<uuid8>.<ext>` key. Returns the bare filename (the media_key).
+async function persistLibraryFile(buffer, dir, ext) {
+ const filename = `upload-${randomUUID().slice(0, 8)}.${ext}`;
+ await ensureDir(dir);
+ await writeFile(join(dir, filename), buffer);
+ return filename;
+}
+
+async function requireIngredient(getIngredientFn, ingredientId) {
+ const ingredient = await getIngredientFn(ingredientId);
+ if (!ingredient) throw new ServerError('Ingredient not found', { status: 404 });
+ return ingredient;
+}
+
+/**
+ * Persist an uploaded file into the media library and attach it to an
+ * ingredient. Images route through `saveUploadedGalleryImage` (magic-byte
+ * sniffed, re-encoded to PNG, EXIF-baked); audio/video are stored as-is. Returns
+ * the attached media row. `deps` lets tests run without DB/disk.
+ */
+export async function uploadIngredientMediaFile(
+ { ingredientId, dataBase64, mimeType, filename = null, role = null, caption = null } = {},
+ {
+ getIngredientFn = getIngredient,
+ attachMediaFn = attachMedia,
+ saveImageFn = saveUploadedGalleryImage,
+ persistFileFn = persistLibraryFile,
+ } = {},
+) {
+ await requireIngredient(getIngredientFn, ingredientId);
+ const classified = classifyUploadMime(mimeType);
+ if (!classified) {
+ throw new ServerError(`Unsupported file type "${mimeType}" — attach an image, audio, or video file.`, {
+ status: 422, code: 'UNSUPPORTED_MEDIA',
+ });
+ }
+ const meta = { role, caption };
+
+ if (classified.category === 'image') {
+ // saveUploadedGalleryImage validates size + format and 400s on a non-image.
+ const { filename: mediaKey } = await saveImageFn(dataBase64);
+ console.log(`📎 Catalog media upload: image ${mediaKey} → ingredient ${ingredientId}`);
+ return attachMediaFn(ingredientId, mediaKey, classified.kind, meta);
+ }
+
+ const buffer = Buffer.from(dataBase64, 'base64');
+ if (buffer.length === 0) throw new ServerError('Empty file upload', { status: 400, code: 'VALIDATION_ERROR' });
+ const dir = classified.category === 'audio' ? PATHS.audio : PATHS.videos;
+ const mediaKey = await persistFileFn(buffer, dir, classified.ext);
+ console.log(`📎 Catalog media upload: ${classified.kind} ${mediaKey} → ingredient ${ingredientId} (${(buffer.length / 1024).toFixed(0)}KB, ${filename || 'unnamed'})`);
+ return attachMediaFn(ingredientId, mediaKey, classified.kind, meta);
+}
+
+/**
+ * Attach a recorded voice memo: transcribe the WAV via Whisper, persist the
+ * audio into data/audio, and attach a `kind:'audio'` media row with the
+ * transcript in `caption`. Persist happens AFTER transcription so a failed
+ * transcript doesn't orphan a file (mirrors ingestFromVoice). An empty
+ * transcript still attaches the audio (the recording is the primary artifact;
+ * the client already guards against a silent mic). Returns `{ media, transcript }`.
+ */
+export async function recordIngredientVoiceMemo(
+ { ingredientId, audioBase64, mimeType = 'audio/wav', role = 'voice-memo' } = {},
+ {
+ getIngredientFn = getIngredient,
+ attachMediaFn = attachMedia,
+ transcribeFn = transcribe,
+ persistFileFn = persistLibraryFile,
+ } = {},
+) {
+ await requireIngredient(getIngredientFn, ingredientId);
+ const buffer = Buffer.from(audioBase64, 'base64');
+ if (buffer.length === 0) throw new ServerError('Voice memo audio was empty', { status: 400, code: 'VALIDATION_ERROR' });
+
+ const { text } = await transcribeFn(buffer, { mimeType });
+ const transcript = (text || '').trim().slice(0, MAX_CAPTION);
+
+ const ext = AUDIO_EXT[(mimeType || '').toLowerCase().split(';')[0].trim()] || 'wav';
+ const mediaKey = await persistFileFn(buffer, PATHS.audio, ext);
+ console.log(`🎙️ Catalog voice memo: ${mediaKey} → ingredient ${ingredientId} (${transcript.length} chars)`);
+ const media = await attachMediaFn(ingredientId, mediaKey, 'audio', { role, caption: transcript || null });
+ return { media, transcript };
+}
diff --git a/server/services/catalogMedia.test.js b/server/services/catalogMedia.test.js
new file mode 100644
index 0000000000..7fa59ea3b7
--- /dev/null
+++ b/server/services/catalogMedia.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ classifyUploadMime,
+ uploadIngredientMediaFile,
+ recordIngredientVoiceMemo,
+} from './catalogMedia.js';
+
+describe('classifyUploadMime', () => {
+ it('classifies images to the reference kind', () => {
+ expect(classifyUploadMime('image/png')).toEqual({ category: 'image', kind: 'reference', ext: 'png' });
+ expect(classifyUploadMime('image/jpeg')).toEqual({ category: 'image', kind: 'reference', ext: 'png' });
+ });
+
+ it('classifies audio and strips a codecs parameter', () => {
+ expect(classifyUploadMime('audio/wav')).toEqual({ category: 'audio', kind: 'audio', ext: 'wav' });
+ expect(classifyUploadMime('audio/webm;codecs=opus')).toEqual({ category: 'audio', kind: 'audio', ext: 'webm' });
+ expect(classifyUploadMime('audio/mpeg')).toEqual({ category: 'audio', kind: 'audio', ext: 'mp3' });
+ });
+
+ it('classifies video with a container fallback for unknown subtypes', () => {
+ expect(classifyUploadMime('video/mp4')).toEqual({ category: 'video', kind: 'video', ext: 'mp4' });
+ expect(classifyUploadMime('video/x-matroska')).toEqual({ category: 'video', kind: 'video', ext: 'mp4' });
+ });
+
+ it('returns null for unsupported / missing MIME (documents do not federate)', () => {
+ expect(classifyUploadMime('application/pdf')).toBeNull();
+ expect(classifyUploadMime('text/plain')).toBeNull();
+ expect(classifyUploadMime('')).toBeNull();
+ expect(classifyUploadMime(undefined)).toBeNull();
+ });
+});
+
+const okIngredient = () => ({ id: 'ing-1', name: 'Test' });
+const b64 = (s) => Buffer.from(s).toString('base64');
+
+describe('uploadIngredientMediaFile', () => {
+ it('routes an image through the gallery saver and attaches as reference', async () => {
+ const saveImageFn = vi.fn().mockResolvedValue({ filename: 'upload-abcd1234.png' });
+ const attachMediaFn = vi.fn().mockResolvedValue({ mediaKey: 'upload-abcd1234.png', kind: 'reference' });
+ const persistFileFn = vi.fn();
+ const media = await uploadIngredientMediaFile(
+ { ingredientId: 'ing-1', dataBase64: b64('img'), mimeType: 'image/png', filename: 'pic.png' },
+ { getIngredientFn: okIngredient, attachMediaFn, saveImageFn, persistFileFn },
+ );
+ expect(saveImageFn).toHaveBeenCalledWith(b64('img'));
+ expect(persistFileFn).not.toHaveBeenCalled();
+ expect(attachMediaFn).toHaveBeenCalledWith('ing-1', 'upload-abcd1234.png', 'reference', { role: null, caption: null });
+ expect(media).toEqual({ mediaKey: 'upload-abcd1234.png', kind: 'reference' });
+ });
+
+ it('persists audio bytes to the library dir and attaches as audio', async () => {
+ const persistFileFn = vi.fn().mockResolvedValue('upload-11112222.webm');
+ const attachMediaFn = vi.fn().mockImplementation((id, key, kind) => ({ mediaKey: key, kind }));
+ await uploadIngredientMediaFile(
+ { ingredientId: 'ing-1', dataBase64: b64('audiobytes'), mimeType: 'audio/webm', filename: 'clip.webm', role: 'sfx' },
+ { getIngredientFn: okIngredient, attachMediaFn, saveImageFn: vi.fn(), persistFileFn },
+ );
+ expect(persistFileFn).toHaveBeenCalledTimes(1);
+ const [buffer, , ext] = persistFileFn.mock.calls[0];
+ expect(Buffer.isBuffer(buffer)).toBe(true);
+ expect(ext).toBe('webm');
+ expect(attachMediaFn).toHaveBeenCalledWith('ing-1', 'upload-11112222.webm', 'audio', { role: 'sfx', caption: null });
+ });
+
+ it('rejects an unsupported MIME with a 422', async () => {
+ await expect(uploadIngredientMediaFile(
+ { ingredientId: 'ing-1', dataBase64: b64('doc'), mimeType: 'application/pdf' },
+ { getIngredientFn: okIngredient, attachMediaFn: vi.fn(), saveImageFn: vi.fn(), persistFileFn: vi.fn() },
+ )).rejects.toMatchObject({ status: 422 });
+ });
+
+ it('404s when the ingredient is missing', async () => {
+ await expect(uploadIngredientMediaFile(
+ { ingredientId: 'nope', dataBase64: b64('x'), mimeType: 'image/png' },
+ { getIngredientFn: async () => null, attachMediaFn: vi.fn(), saveImageFn: vi.fn(), persistFileFn: vi.fn() },
+ )).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('rejects empty (all-whitespace-decoding) file bytes for non-image kinds', async () => {
+ await expect(uploadIngredientMediaFile(
+ { ingredientId: 'ing-1', dataBase64: '', mimeType: 'audio/wav' },
+ { getIngredientFn: okIngredient, attachMediaFn: vi.fn(), saveImageFn: vi.fn(), persistFileFn: vi.fn() },
+ )).rejects.toMatchObject({ status: 400 });
+ });
+});
+
+describe('recordIngredientVoiceMemo', () => {
+ it('transcribes, persists audio, and attaches with the transcript in caption', async () => {
+ const transcribeFn = vi.fn().mockResolvedValue({ text: ' hello world ' });
+ const persistFileFn = vi.fn().mockResolvedValue('voice-xyz.wav');
+ const attachMediaFn = vi.fn().mockImplementation((id, key, kind, meta) => ({ mediaKey: key, kind, ...meta }));
+ const { media, transcript } = await recordIngredientVoiceMemo(
+ { ingredientId: 'ing-1', audioBase64: b64('wavbytes'), mimeType: 'audio/wav' },
+ { getIngredientFn: okIngredient, attachMediaFn, transcribeFn, persistFileFn },
+ );
+ expect(transcript).toBe('hello world');
+ // Persist happens AFTER transcription.
+ expect(transcribeFn).toHaveBeenCalledTimes(1);
+ expect(persistFileFn).toHaveBeenCalledTimes(1);
+ expect(attachMediaFn).toHaveBeenCalledWith('ing-1', 'voice-xyz.wav', 'audio', { role: 'voice-memo', caption: 'hello world' });
+ expect(media.caption).toBe('hello world');
+ });
+
+ it('still attaches the audio when the transcript is empty (caption null)', async () => {
+ const attachMediaFn = vi.fn().mockImplementation((id, key, kind, meta) => ({ mediaKey: key, kind, ...meta }));
+ await recordIngredientVoiceMemo(
+ { ingredientId: 'ing-1', audioBase64: b64('wav'), mimeType: 'audio/wav' },
+ { getIngredientFn: okIngredient, attachMediaFn, transcribeFn: async () => ({ text: ' ' }), persistFileFn: async () => 'voice-empty.wav' },
+ );
+ expect(attachMediaFn).toHaveBeenCalledWith('ing-1', 'voice-empty.wav', 'audio', { role: 'voice-memo', caption: null });
+ });
+
+ it('does not persist audio when transcription throws (no orphan file)', async () => {
+ const persistFileFn = vi.fn();
+ await expect(recordIngredientVoiceMemo(
+ { ingredientId: 'ing-1', audioBase64: b64('wav'), mimeType: 'audio/wav' },
+ { getIngredientFn: okIngredient, attachMediaFn: vi.fn(), transcribeFn: async () => { throw new Error('whisper down'); }, persistFileFn },
+ )).rejects.toThrow('whisper down');
+ expect(persistFileFn).not.toHaveBeenCalled();
+ });
+
+ it('rejects empty audio with a 400', async () => {
+ await expect(recordIngredientVoiceMemo(
+ { ingredientId: 'ing-1', audioBase64: '', mimeType: 'audio/wav' },
+ { getIngredientFn: okIngredient, attachMediaFn: vi.fn(), transcribeFn: vi.fn(), persistFileFn: vi.fn() },
+ )).rejects.toMatchObject({ status: 400 });
+ });
+});