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

add URL, file, and voice-memo ingest paths to the creative catalog

[._.]/ Adam Eivyae59bc23a6a9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 595fc52b8a..e279823355 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,7 +15,7 @@
- **[catalog-federation-orchestrator] The creative catalog now auto-replicates between peers.** The catalog sync routes existed but nothing pulled from peers — orphan ingredients (ideas / scenes / concepts not attached to a universe) and the universe→ingredient ref links stayed local. The sync orchestrator now runs `catalog` as a delta-based PostgreSQL category alongside Memory: on every peer-online event and on the background interval it pulls `GET /api/catalog/sync` (the seven independent per-kind BIGSERIAL cursors: scraps / ingredients / sources / refs / relations / tags / media) and applies each batch locally with the same last-writer-wins + per-row isolation + schema-version gate as direct sync. A peer ahead on the `catalog` schema records a gap on the Instances page (the existing SchemaGapBadge) and pauses draining instead of looping. Toggle it per peer under Instances → Sync Categories → "Catalog"; Postgres-only (a non-Postgres peer simply never enables it).
- **[catalog-bundled-universe-push] Universe peer-pushes now carry their catalog enrichments.** When peer A pushes a universe to peer B, the push bundles the `catalog_ingredients` rows referenced by that universe's canon plus the universe→ingredient ref links. Previously only the embedded canon replicated, so the receiver re-derived a strictly-lossy view on first backfill — the `tags`, vector `embedding`, and `payload.summary`-style enrichments that live only in the catalog row were dropped. The bundle ships the full enriched rows (including tombstoned ref rows so unlinks propagate), applied through the same catalog-sync path; it rides only universe pushes (never series / mediaCollection), skips tombstone pushes, and is gated by `PORTOS_SCHEMA_VERSIONS.catalog` so a receiver on an older catalog schema rejects a forward-shaped bundle with a clean 409 rather than corrupting local rows. Postgres-only and best-effort — a bundle failure never fails the universe push.
-
+- **[catalog-source-kinds-url-file-voice] Catalog Ingest accepts URLs, text files, and voice memos — not just pasted text.** The `/catalog/ingest` paste box now sits behind a source picker: **URL** fetches the page through the browser service and extracts its main article text server-side (`source_kind: url`, metadata records the URL + fetched title); **File** reads a `.txt`/`.md` you pick and ingests it (`source_kind: file`, metadata records filename + mime); **Voice Memo** records from your mic, transcribes it with Whisper, persists the audio under `data/audio` to mint a `media_key`, and ingests the transcript (`source_kind: voice-memo`, metadata records the audio key so a later commit can attach it via the media-refs table). Every source funnels into the same extract → review → commit flow and streams the same `catalog:extract:progress` stage checklist as a paste. No DB migration or sync-version bump — `catalog_scraps.source_kind` was already a free `VARCHAR(32)` and the sync envelope already accepts any value, so the new kinds federate to peers as-is. PDF text extraction is intentionally deferred (no in-tree PDF-text dependency); picking a `.pdf` surfaces a clear "paste the text instead" message.
- **[catalog-ingredient-media-refs] Catalog ingredients can now carry typed media attachments — a portrait, mood/reference images, and more.** A new "Media" panel on each ingredient detail page lets you set one portrait (rendered large at the head) and attach additional reference images, scoped to your existing media gallery via a "Pick from gallery" picker or by dragging a gallery image onto the panel. Each attachment stores a `media_key` *reference* into your media library (the bytes are never duplicated into the catalog), so a federated peer that receives an ingredient gets its media-key list and matches it against its own library — keys whose asset hasn't arrived yet show a "missing" badge (via the same syncing-asset surface used elsewhere) instead of a broken image. Backed by a new `catalog_ingredient_media` Postgres table (kinds: portrait / reference / audio / video / document) with soft-delete tombstones from day one, so detaches propagate to peers; the rows ride the catalog sync envelope as a new `media` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 6 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every attachment). `POST/DELETE /api/catalog/ingredients/:id/media`, `POST …/media/portrait`, and `GET …/media` + `…/media/missing` are Zod-validated; attaching rejects a key that doesn't resolve against the local library with a 422. Voice-memo capture is intentionally left as a clean seam for the separate source-kinds work.
- **[catalog-ingredient-revisions] Catalog ingredients now keep an edit history with inline diff + restore.** Every time a catalog ingredient's name, payload, or tags change — a manual detail-page save, an ingest commit, or a future AI refinement pass — a revision row is recorded, and a new "Revision history" panel on the ingredient detail page lists them newest-first with a source badge (user / extract / refine / sync) and a relative timestamp. Expand any revision to see a field-by-field diff against the current saved state, and click "Restore" on an older revision to roll back (the restore is itself recorded as a new revision, so it's auditable and reversible). Backed by a new append-only `catalog_ingredient_revisions` Postgres table (foreign-keyed to `catalog_ingredients` with ON DELETE CASCADE); retention is capped at the most recent 50 revisions per ingredient (configurable via the `CATALOG_REVISION_RETENTION` env var) so history can't grow unbounded from rapid edits. The history is local audit data — it is intentionally NOT federated (the synced ingredient row already last-write-wins-merges the latest state across peers), so the catalog sync wire version is unchanged.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 194cbcec94..e1ceca3796 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -59,6 +59,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
+| `audioRecorder.js` | `startMemoRecording()` → `{ stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
diff --git a/client/src/lib/audioRecorder.js b/client/src/lib/audioRecorder.js
new file mode 100644
index 0000000000..ed5f5cae8e
--- /dev/null
+++ b/client/src/lib/audioRecorder.js
@@ -0,0 +1,125 @@
+// Browser audio recording → 16 kHz mono WAV → base64, for one-shot memo
+// capture (catalog voice ingest). whisper.cpp accepts WAV only, so we decode
+// whatever MediaRecorder produced and resample to 16 kHz mono before encoding.
+//
+// This is deliberately NOT coupled to services/voiceClient.js — that module's
+// recorder is wired to the live voice-agent socket pipeline (echo gating, VAD,
+// streaming TTS). This is a standalone "record a clip, get a WAV" helper.
+
+const TARGET_SAMPLE_RATE = 16000;
+
+// Pick a MediaRecorder mime the browser supports; Safari lands on mp4, others
+// on webm/opus. We re-decode to WAV regardless, so the intermediate codec
+// only needs to be recordable + decodable by Web Audio.
+export function pickRecordingMimeType() {
+ const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
+ for (const m of candidates) {
+ if (window.MediaRecorder && window.MediaRecorder.isTypeSupported?.(m)) return m;
+ }
+ return 'audio/webm';
+}
+
+// Encode a mono Float32 PCM buffer to a 16-bit WAV ArrayBuffer.
+export function encodePcmToWav(float32, sampleRate = TARGET_SAMPLE_RATE) {
+ const n = float32.length;
+ const buffer = new ArrayBuffer(44 + n * 2);
+ const view = new DataView(buffer);
+ const writeStr = (off, s) => { for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i)); };
+ writeStr(0, 'RIFF');
+ view.setUint32(4, 36 + n * 2, true);
+ writeStr(8, 'WAVE');
+ writeStr(12, 'fmt ');
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 1, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, sampleRate * 2, true);
+ view.setUint16(32, 2, true);
+ view.setUint16(34, 16, true);
+ writeStr(36, 'data');
+ view.setUint32(40, n * 2, true);
+ let off = 44;
+ for (let i = 0; i < n; i++) {
+ const s = Math.max(-1, Math.min(1, float32[i]));
+ view.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
+ off += 2;
+ }
+ return buffer;
+}
+
+// Decode a recorded blob (any Web-Audio-decodable codec) → 16 kHz mono WAV.
+// Returns `{ wav: ArrayBuffer, peak: number }`; peak amplitude surfaces a
+// dead/too-quiet mic before we waste a Whisper round-trip on silence.
+export async function blobToWav16k(blob) {
+ const bytes = await blob.arrayBuffer();
+ const decodeCtx = new (window.AudioContext || window.webkitAudioContext)();
+ const decoded = await decodeCtx.decodeAudioData(bytes).finally(() => {
+ decodeCtx.close().catch(() => {});
+ });
+ const frames = Math.ceil(decoded.duration * TARGET_SAMPLE_RATE);
+ const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
+ const src = offline.createBufferSource();
+ src.buffer = decoded;
+ src.connect(offline.destination);
+ src.start();
+ const rendered = await offline.startRendering();
+ const pcm = rendered.getChannelData(0);
+ let peak = 0;
+ for (let i = 0; i < pcm.length; i++) {
+ const a = Math.abs(pcm[i]);
+ if (a > peak) peak = a;
+ }
+ return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
+}
+
+// Base64-encode an ArrayBuffer in chunks (avoids the call-stack blowup of
+// String.fromCharCode(...bigArray) on multi-second recordings).
+export function arrayBufferToBase64(buffer) {
+ const bytes = new Uint8Array(buffer);
+ let binary = '';
+ const CHUNK = 0x8000;
+ for (let i = 0; i < bytes.length; i += CHUNK) {
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
+ }
+ return btoa(binary);
+}
+
+/**
+ * Start recording from the default microphone. Returns a handle whose
+ * `stop()` resolves to `{ audioBase64, peak, mimeType, durationMs }` — a
+ * 16 kHz mono WAV base64 string ready to POST. The caller is responsible for
+ * calling `stop()` (or `cancel()` to discard). Throws if mic access is denied.
+ */
+export async function startMemoRecording() {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ const mimeType = pickRecordingMimeType();
+ const recorder = new MediaRecorder(stream, { mimeType });
+ const chunks = [];
+ const startedAt = Date.now();
+ recorder.ondataavailable = (e) => { if (e.data && e.data.size > 0) chunks.push(e.data); };
+ recorder.start();
+
+ const teardown = () => stream.getTracks().forEach((t) => t.stop());
+
+ return {
+ stop: () => new Promise((resolve, reject) => {
+ recorder.onstop = async () => {
+ teardown();
+ try {
+ const blob = new Blob(chunks, { type: mimeType });
+ const { wav, peak } = await blobToWav16k(blob);
+ resolve({
+ audioBase64: arrayBufferToBase64(wav),
+ mimeType: 'audio/wav',
+ peak,
+ durationMs: Date.now() - startedAt,
+ });
+ } catch (err) {
+ reject(err);
+ }
+ };
+ recorder.stop();
+ }),
+ cancel: () => { teardown(); try { recorder.stop(); } catch { /* already stopped */ } },
+ };
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 48870a7000..bbfbe82e28 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -30,6 +30,7 @@ export * from './wrImageDefaults.js';
export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
+export * from './audioRecorder.js';
export * from './clientErrorReporter.js';
export * from './clipboard.js';
export * from './compareHelpers.js';
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index 1389d1a83d..c89da0edae 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -7,14 +7,18 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
-import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload } from 'lucide-react';
+import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload, Link2, FileText, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
+import { startMemoRecording } from '../lib/audioRecorder';
import {
createCatalogScrap,
extractFromCatalogScrap,
commitCatalogScrapDraft,
bulkImportCatalogIngredients,
+ ingestCatalogUrl,
+ ingestCatalogFile,
+ ingestCatalogVoice,
} from '../services/apiCatalog';
// One review section per ingredient type. The first three are bible-shaped
@@ -74,6 +78,14 @@ export default function CatalogIngest() {
const [bulkFormat, setBulkFormat] = useState('markdown');
const [bulkText, setBulkText] = useState('');
const [bulkSubmitting, setBulkSubmitting] = useState(false);
+ // Alternate ingest sources. The paste textarea is the default; 'url' and
+ // 'voice' add their own inputs. File ingest is a one-shot picker that fires
+ // immediately on select, so it has no persistent mode.
+ const [sourceMode, setSourceMode] = useState('paste'); // 'paste' | 'url'
+ const [url, setUrl] = useState('');
+ const [recording, setRecording] = useState(false);
+ const recorderRef = useRef(null);
+ const fileInputRef = useRef(null);
// Track active runId so a stale frame from an earlier scrap can't mutate the
// current stage list (server fans these to all sockets — single-user trust
@@ -105,6 +117,9 @@ export default function CatalogIngest() {
const reset = () => {
activeRunIdRef.current = null;
+ recorderRef.current?.cancel?.();
+ recorderRef.current = null;
+ setRecording(false);
setPhase('paste');
setScrapId(null);
setStages(INITIAL_STAGES);
@@ -112,22 +127,12 @@ export default function CatalogIngest() {
setSelected({ characters: new Set(), places: new Set(), objects: new Set(), ideas: new Set(), scenes: new Set(), concepts: new Set() });
};
- const handleIngest = async (e) => {
- e?.preventDefault?.();
- const text = rawText.trim();
- if (!text) { toast.error('Paste some text first.'); return; }
- setSubmitting(true);
- setPhase('extracting');
- setStages(INITIAL_STAGES);
- // silent: own error handling below — avoids double-toast.
- const created = await createCatalogScrap({ rawText: text, title: title.trim() || undefined }, { silent: true })
- .catch((err) => { toast.error(err?.message || 'Failed to save scrap'); return null; });
- if (!created?.scrap?.id) { setSubmitting(false); setPhase('paste'); return; }
- setScrapId(created.scrap.id);
- const result = await extractFromCatalogScrap(created.scrap.id, {}, { silent: true })
- .catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });
- setSubmitting(false);
- if (!result?.draft) { setPhase('paste'); return; }
+ // Shared review-entry: every ingest path (paste / url / file / voice) yields
+ // a `{ scrap, draft }` response with the same draft shape, so they all funnel
+ // through here to populate the review phase.
+ const enterReviewFromResult = (result) => {
+ if (!result?.draft) { setPhase('paste'); return false; }
+ if (result.scrap?.id) setScrapId(result.scrap.id);
const d = Object.fromEntries(KIND_SECTIONS.map((s) => [
s.key,
Array.isArray(result.draft[s.key]) ? result.draft[s.key] : [],
@@ -146,6 +151,95 @@ export default function CatalogIngest() {
setStages((prev) => prev.map((s) => ({ ...s, status: 'completed', count: countForStage(s.id) })));
}
setPhase('review');
+ return true;
+ };
+
+ const handleIngest = async (e) => {
+ e?.preventDefault?.();
+ const text = rawText.trim();
+ if (!text) { toast.error('Paste some text first.'); return; }
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ // silent: own error handling below — avoids double-toast.
+ const created = await createCatalogScrap({ rawText: text, title: title.trim() || undefined }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Failed to save scrap'); return null; });
+ if (!created?.scrap?.id) { setSubmitting(false); setPhase('paste'); return; }
+ setScrapId(created.scrap.id);
+ const result = await extractFromCatalogScrap(created.scrap.id, {}, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result);
+ };
+
+ const handleUrlIngest = async (e) => {
+ e?.preventDefault?.();
+ const trimmed = url.trim();
+ if (!trimmed) { toast.error('Paste a URL first.'); return; }
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ const result = await ingestCatalogUrl({ url: trimmed }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'URL ingest failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result);
+ };
+
+ const handleFilePicked = async (e) => {
+ const file = e.target.files?.[0];
+ e.target.value = ''; // allow re-picking the same file
+ if (!file) return;
+ const name = (file.name || '').toLowerCase();
+ if (name.endsWith('.pdf')) {
+ toast.error('PDF text extraction is not supported yet — paste the text or upload a .txt/.md file.');
+ return;
+ }
+ const text = await file.text().catch(() => '');
+ if (!text.trim()) { toast.error('That file had no readable text.'); return; }
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ const result = await ingestCatalogFile(
+ { text, filename: file.name, mime: file.type || undefined },
+ { silent: true },
+ ).catch((err) => { toast.error(err?.message || 'File ingest failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result);
+ };
+
+ 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 stopRecordingAndIngest = 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;
+ }
+ setSubmitting(true);
+ setPhase('extracting');
+ setStages(INITIAL_STAGES);
+ const result = await ingestCatalogVoice(
+ { audioBase64: clip.audioBase64, mimeType: clip.mimeType, title: title.trim() || undefined },
+ { silent: true },
+ ).catch((err) => { toast.error(err?.message || 'Voice ingest failed'); return null; });
+ setSubmitting(false);
+ enterReviewFromResult(result);
};
const handleBulkImport = async () => {
@@ -312,31 +406,85 @@ export default function CatalogIngest() {
</div>
)}
- {phase === 'paste' && (
- <form onSubmit={handleIngest} className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
- <div>
- <label htmlFor="ingest-title" className="block text-sm font-medium mb-1 text-white">
- Title <span className="text-gray-500 font-normal">(optional)</span>
- </label>
- <input id="ingest-title" type="text" value={title} onChange={(e) => setTitle(e.target.value)}
- placeholder="e.g. Chapter 3 notes" maxLength={200}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />
- </div>
- <div>
- <label htmlFor="ingest-text" className="block text-sm font-medium mb-1 text-white">Raw text</label>
- <textarea id="ingest-text" rows={12} value={rawText} onChange={(e) => setRawText(e.target.value)}
- placeholder="Paste prose, scene notes, character sketches — anything you want catalogued."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono focus:outline-none focus:border-port-accent" />
- <p className="text-xs text-gray-500 mt-1">{rawText.length.toLocaleString()} chars</p>
- </div>
- <div className="flex items-center justify-end">
- <button type="submit" disabled={submitting || !rawText.trim()}
- className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
- {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
- {submitting ? 'Ingesting…' : 'Ingest'}
+ {phase === 'paste' && !bulkOpen && (
+ <>
+ {/* Source picker — paste / URL / file / voice all funnel into the
+ same review phase. File + voice fire immediately; paste + URL
+ have their own input rows. */}
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={() => setSourceMode('paste')}
+ className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border ${sourceMode === 'paste' ? 'border-port-accent text-white bg-port-accent/10' : 'border-port-border text-gray-300 hover:text-white'}`}>
+ <Sparkles size={14} aria-hidden="true" /> Paste
+ </button>
+ <button type="button" onClick={() => setSourceMode('url')}
+ className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border ${sourceMode === 'url' ? 'border-port-accent text-white bg-port-accent/10' : 'border-port-border text-gray-300 hover:text-white'}`}>
+ <Link2 size={14} aria-hidden="true" /> URL
+ </button>
+ <button type="button" onClick={() => fileInputRef.current?.click()} disabled={submitting}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white disabled:opacity-50">
+ <FileText size={14} aria-hidden="true" /> File
</button>
+ <input ref={fileInputRef} type="file" accept=".txt,.md,.markdown,text/plain,text/markdown"
+ onChange={handleFilePicked} className="hidden" aria-hidden="true" tabIndex={-1} />
+ {!recording ? (
+ <button type="button" onClick={startRecording} disabled={submitting}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white disabled:opacity-50">
+ <Mic size={14} aria-hidden="true" /> Voice Memo
+ </button>
+ ) : (
+ <button type="button" onClick={stopRecordingAndIngest}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-error text-white bg-port-error/10 animate-pulse">
+ <Square size={14} aria-hidden="true" /> Stop &amp; Transcribe
+ </button>
+ )}
</div>
- </form>
+
+ {sourceMode === 'url' && (
+ <form onSubmit={handleUrlIngest} className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
+ <div>
+ <label htmlFor="ingest-url" className="block text-sm font-medium mb-1 text-white">URL</label>
+ <input id="ingest-url" type="url" value={url} onChange={(e) => setUrl(e.target.value)}
+ placeholder="https://example.com/article"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />
+ <p className="text-xs text-gray-500 mt-1">Fetched through the browser service; main article text is extracted server-side.</p>
+ </div>
+ <div className="flex items-center justify-end">
+ <button type="submit" disabled={submitting || !url.trim()}
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
+ {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Link2 className="w-4 h-4" />}
+ {submitting ? 'Fetching…' : 'Fetch & Ingest'}
+ </button>
+ </div>
+ </form>
+ )}
+
+ {sourceMode === 'paste' && (
+ <form onSubmit={handleIngest} className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
+ <div>
+ <label htmlFor="ingest-title" className="block text-sm font-medium mb-1 text-white">
+ Title <span className="text-gray-500 font-normal">(optional)</span>
+ </label>
+ <input id="ingest-title" type="text" value={title} onChange={(e) => setTitle(e.target.value)}
+ placeholder="e.g. Chapter 3 notes" maxLength={200}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent" />
+ </div>
+ <div>
+ <label htmlFor="ingest-text" className="block text-sm font-medium mb-1 text-white">Raw text</label>
+ <textarea id="ingest-text" rows={12} value={rawText} onChange={(e) => setRawText(e.target.value)}
+ placeholder="Paste prose, scene notes, character sketches — anything you want catalogued."
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono focus:outline-none focus:border-port-accent" />
+ <p className="text-xs text-gray-500 mt-1">{rawText.length.toLocaleString()} chars</p>
+ </div>
+ <div className="flex items-center justify-end">
+ <button type="submit" disabled={submitting || !rawText.trim()}
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
+ {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
+ {submitting ? 'Ingesting…' : 'Ingest'}
+ </button>
+ </div>
+ </form>
+ )}
+ </>
)}
{phase === 'extracting' && (
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index f195b761af..02a8675029 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -38,6 +38,19 @@ export const extractFromCatalogScrap = (id, body = {}, options) =>
export const commitCatalogScrapDraft = (id, accepted, options) =>
request(`/catalog/scraps/${enc(id)}/commit`, { method: 'POST', body: JSON.stringify({ accepted }), ...options });
+// --- Alternate ingest sources (url / file / voice) ----------------------
+// Each returns { scrap, draft } — the same shape as extractFromCatalogScrap —
+// so CatalogIngest can drop straight into its review phase.
+
+export const ingestCatalogUrl = (body = {}, options) =>
+ request('/catalog/ingest/url', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const ingestCatalogFile = (body = {}, options) =>
+ request('/catalog/ingest/file', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const ingestCatalogVoice = (body = {}, options) =>
+ request('/catalog/ingest/voice', { method: 'POST', body: JSON.stringify(body), ...options });
+
// --- Ingredients --------------------------------------------------------
export const listCatalogIngredients = ({ type, tag, q, limit, offset, ...options } = {}) => {
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index e120f2cee1..47529e7ca8 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -48,15 +48,63 @@ const payload = z.record(z.string(), z.unknown())
})
.optional();
+// Scrap source kinds. The DB column is a free VARCHAR(32) so peers running a
+// newer build can push kinds an older build doesn't enumerate (the sync-apply
+// path uses the looser `z.string().max(32)` below, NOT this enum). This enum
+// gates the LOCAL ingest routes only — every value here is one a local ingest
+// path actually produces.
+export const SCRAP_SOURCE_KINDS = Object.freeze([
+ 'paste',
+ 'brain-bridge',
+ 'importer-handoff',
+ 'manual',
+ 'url', // POST /catalog/ingest/url — fetched + main-text-extracted page
+ 'file', // POST /catalog/ingest/file — uploaded .txt/.md/.pdf
+ 'voice-memo', // POST /catalog/ingest/voice — recorded memo, Whisper-transcribed
+]);
+
export const catalogScrapCreateSchema = z.object({
title: z.string().trim().max(300).optional().nullable(),
rawText: z.string().min(1).max(2_000_000),
- sourceKind: z.enum(['paste', 'brain-bridge', 'importer-handoff', 'manual']).optional(),
+ sourceKind: z.enum(SCRAP_SOURCE_KINDS).optional(),
metadata: payload,
}).strict();
export const catalogScrapPatchSchema = catalogScrapCreateSchema.partial();
+// --- Source-kind ingest routes (url / file / voice) ---------------------
+// Each ingest route creates a scrap with the matching `sourceKind`, then runs
+// the same extraction pipeline the paste→extract→commit flow uses, so the
+// client lands on the identical review phase. `providerOverride` mirrors
+// catalogExtractRequestSchema below.
+
+export const catalogUrlIngestSchema = z.object({
+ url: z.string().trim().url().max(4_000),
+ providerOverride: z.string().trim().min(1).max(120).optional(),
+}).strict();
+
+// Text-bearing file ingest. The client reads .txt/.md text locally and posts
+// it here with the original filename + mime so the scrap metadata records
+// provenance without the server needing an upload/parse dependency.
+export const catalogFileIngestSchema = z.object({
+ text: z.string().min(1).max(2_000_000),
+ filename: z.string().trim().min(1).max(300),
+ mime: z.string().trim().min(1).max(120).optional(),
+ providerOverride: z.string().trim().min(1).max(120).optional(),
+}).strict();
+
+// Voice-memo ingest. `audioBase64` is a base64-encoded WAV the client records
+// via MediaRecorder (matching the voice agent's STT path). The server decodes
+// it, transcribes via Whisper, persists the audio under data/audio to mint a
+// `media_key`, then ingests the transcript with that key in scrap metadata.
+// 8 MB base64 ≈ 6 MB raw ≈ several minutes of 16 kHz mono WAV.
+export const catalogVoiceIngestSchema = z.object({
+ audioBase64: z.string().min(1).max(8_000_000),
+ mimeType: z.string().trim().min(1).max(64).optional(),
+ title: z.string().trim().max(300).optional(),
+ providerOverride: z.string().trim().min(1).max(120).optional(),
+}).strict();
+
export const catalogIngredientCreateSchema = z.object({
type: z.enum(INGREDIENT_TYPES),
name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index d8c1d4515b..abfb21960e 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -28,11 +28,15 @@ import {
catalogExportQuerySchema,
catalogRevisionQuerySchema,
catalogRevisionRestoreSchema,
+ catalogUrlIngestSchema,
+ catalogFileIngestSchema,
+ catalogVoiceIngestSchema,
} from '../lib/catalogValidation.js';
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredients } from '../services/catalogExtraction.js';
+import { ingestFromUrl, ingestFromFile, ingestFromVoice } from '../services/catalogIngestSources.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
@@ -94,6 +98,30 @@ router.post('/scraps/:id/extract', asyncHandler(async (req, res) => {
res.json({ scrap, draft });
}));
+// --- Alternate ingest sources (url / file / voice) ----------------------
+// Each creates a scrap with a typed `source_kind`, runs the SAME extraction
+// pipeline as the paste flow (emitting the same catalog:extract:progress
+// frames), and returns `{ scrap, draft }` so the client review phase is
+// identical regardless of how the text arrived.
+
+router.post('/ingest/url', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogUrlIngestSchema, req.body);
+ const result = await ingestFromUrl(body);
+ res.status(201).json(result);
+}));
+
+router.post('/ingest/file', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogFileIngestSchema, req.body);
+ const result = await ingestFromFile(body);
+ res.status(201).json(result);
+}));
+
+router.post('/ingest/voice', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogVoiceIngestSchema, req.body);
+ const result = await ingestFromVoice(body);
+ res.status(201).json(result);
+}));
+
router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
validateRequest(catalogScrapCommitSchema, req.body);
const scrap = await catalogDB.getScrap(req.params.id);
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
new file mode 100644
index 0000000000..b8fe13ec0d
--- /dev/null
+++ b/server/services/catalogIngestSources.js
@@ -0,0 +1,176 @@
+/**
+ * Catalog ingest sources — URL / file / voice-memo entry points.
+ *
+ * Each source produces raw text + a scrap with a typed `source_kind`, then
+ * hands off to the SAME extraction pipeline the textarea-paste flow uses
+ * (`extractIngredients`). So they emit identical `catalog:extract:progress`
+ * frames and the client lands on the same paste→review→commit UI.
+ *
+ * url — fetch the page via the browser service, pull main text,
+ * source_kind 'url', metadata { url, title }.
+ * file — text already read client-side (.txt/.md), source_kind 'file',
+ * metadata { filename, mime }.
+ * voice-memo — base64 WAV → Whisper transcript, audio persisted under
+ * data/audio to mint a media_key, source_kind 'voice-memo',
+ * metadata { mediaKey, mimeType, durationApproxMs? }.
+ *
+ * Keeping this orchestration out of the route handlers lets the unit tests
+ * mock the network/Whisper boundaries without spinning up Express.
+ */
+
+import { randomUUID } from 'crypto';
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import * as catalogDB from './catalogDB.js';
+import { extractIngredients } from './catalogExtraction.js';
+import { transcribe } from './voice/stt.js';
+import {
+ findOrOpenPage,
+ navigateToUrl,
+ listCdpPages,
+ evaluateOnPage,
+} from './browserService.js';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+
+// Cap fetched/transcribed bodies at the scrap column boundary (the Zod
+// rawText max). A runaway page or a multi-hour memo can't blow past the DB.
+const RAW_TEXT_MAX = 2_000_000;
+
+// Browser settle delay between navigate and innerText read. The CDP
+// `/json/new` resolves as soon as the tab exists, not when the DOM is ready,
+// so a same-tick innerText read returns an empty/loading body.
+const PAGE_SETTLE_MS = 2_500;
+
+const clampText = (s) => (typeof s === 'string' ? s.slice(0, RAW_TEXT_MAX) : '');
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Fetch a URL through the browser service and return its main text + title.
+ * Uses CDP (the same headed/headless Chrome the rest of PortOS drives) so
+ * JS-rendered pages and login-walled content the user is already signed into
+ * resolve correctly — a bare `fetch()` would only see the server-rendered
+ * HTML shell of an SPA.
+ *
+ * Returns `{ text, title, finalUrl }`. Throws when the browser can't reach
+ * the page or extracts nothing usable, so the route surfaces a clean 4xx/5xx.
+ */
+export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {}) {
+ // Open (or reuse a tab already on this host), then navigate to force the
+ // exact URL — findOrOpenPage matches by hostname so an existing tab on the
+ // same site would otherwise be reused at the wrong path.
+ await findOrOpenPage(url).catch(() => null);
+ const opened = await navigateToUrl(url);
+ await sleep(settleMs);
+
+ // Re-list to get the live webSocketDebuggerUrl for the tab we just drove.
+ const pages = await listCdpPages();
+ const page = pages.find((p) => p.id === opened.id)
+ || pages.find((p) => p.url === opened.url)
+ || pages[0];
+ if (!page) throw new Error('browser tab not found after navigation');
+
+ // Prefer the page's own <article>/<main> if present (skips nav/footer
+ // chrome), falling back to document body text. Runs in the page; returns a
+ // plain string so evaluateOnPage's returnByValue marshals it cleanly.
+ const expression = `(() => {
+ const pick = document.querySelector('article') || document.querySelector('main') || document.body;
+ const title = (document.title || '').trim();
+ const text = (pick && pick.innerText ? pick.innerText : '').trim();
+ return JSON.stringify({ title, text });
+ })()`;
+ const raw = await evaluateOnPage(page, expression);
+ let parsed = null;
+ try { parsed = raw ? JSON.parse(raw) : null; } catch { parsed = null; }
+ const text = clampText(parsed?.text || '');
+ if (!text.trim()) throw new Error('no readable text extracted from page');
+ return { text, title: parsed?.title || page.title || '', finalUrl: page.url || url };
+}
+
+/**
+ * Ingest from a URL: fetch + extract main text, create a 'url' scrap, run the
+ * extraction pipeline. Returns `{ scrap, draft }` — same shape as the existing
+ * /scraps/:id/extract route so the client review flow is unchanged.
+ */
+export async function ingestFromUrl({ url, providerOverride, settleMs } = {}) {
+ const { text, title, finalUrl } = await fetchUrlMainText(url, settleMs !== undefined ? { settleMs } : {});
+ const scrap = await catalogDB.createScrap({
+ title: title || finalUrl,
+ rawText: text,
+ sourceKind: 'url',
+ metadata: { url: finalUrl, title: title || null },
+ });
+ const draft = await extractIngredients({ rawText: text, scrapId: scrap.id, providerOverride });
+ console.log(`🌐 Catalog URL ingest: ${finalUrl} → scrap ${scrap.id} (${text.length} chars)`);
+ return { scrap, draft };
+}
+
+/**
+ * Ingest from an uploaded text file. The client reads .txt/.md text locally
+ * and posts it with the original filename/mime; we record provenance in scrap
+ * metadata and run the pipeline.
+ */
+export async function ingestFromFile({ text, filename, mime, providerOverride } = {}) {
+ const rawText = clampText(text);
+ if (!rawText.trim()) throw new Error('file contained no extractable text');
+ const scrap = await catalogDB.createScrap({
+ title: filename,
+ rawText,
+ sourceKind: 'file',
+ metadata: { filename, mime: mime || null },
+ });
+ const draft = await extractIngredients({ rawText, scrapId: scrap.id, providerOverride });
+ console.log(`📄 Catalog file ingest: ${filename} → scrap ${scrap.id} (${rawText.length} chars)`);
+ return { scrap, draft };
+}
+
+/**
+ * Persist a recorded memo's audio under data/audio and return its filename —
+ * the `media_key` the catalog uses to reference media without storing bytes
+ * in the scrap. Mirrors the audio path PATHS.audio is already used for.
+ */
+async function persistVoiceMemoAudio(audioBuffer, mimeType) {
+ // WAV is the only format the client encodes (whisper.cpp accepts WAV only),
+ // so default the extension to .wav; honor an explicit webm/mp3 mime if the
+ // client ever sends a pre-encoded blob.
+ const ext = mimeType?.includes('webm') ? 'webm' : mimeType?.includes('mpeg') ? 'mp3' : 'wav';
+ const mediaKey = `voice-memo-${randomUUID()}.${ext}`;
+ await ensureDir(PATHS.audio);
+ await writeFile(join(PATHS.audio, mediaKey), audioBuffer);
+ return mediaKey;
+}
+
+/**
+ * Ingest from a recorded voice memo: decode base64 WAV → Whisper transcript →
+ * persist audio (mint media_key) → 'voice-memo' scrap → pipeline. The audio
+ * media_key rides in scrap metadata so a later commit can attach it to the
+ * resulting ingredient via the media-refs table.
+ *
+ * `deps` lets tests inject a fake transcriber / persister without a running
+ * Whisper server or touching disk.
+ */
+export async function ingestFromVoice(
+ { audioBase64, mimeType = 'audio/wav', title, providerOverride } = {},
+ { transcribeFn = transcribe, persistFn = persistVoiceMemoAudio } = {},
+) {
+ const audioBuffer = Buffer.from(audioBase64, 'base64');
+ if (audioBuffer.byteLength === 0) throw new Error('voice memo audio was empty');
+
+ const { text } = await transcribeFn(audioBuffer, { mimeType });
+ const transcript = clampText((text || '').trim());
+ if (!transcript) throw new Error('voice memo produced an empty transcript');
+
+ // Persist the audio AFTER a successful transcription so a failed/empty memo
+ // doesn't litter data/audio with orphan files.
+ const mediaKey = await persistFn(audioBuffer, mimeType);
+
+ const scrap = await catalogDB.createScrap({
+ title: title?.trim() || 'Voice memo',
+ rawText: transcript,
+ sourceKind: 'voice-memo',
+ metadata: { mediaKey, mimeType },
+ });
+ const draft = await extractIngredients({ rawText: transcript, scrapId: scrap.id, providerOverride });
+ console.log(`🎙️ Catalog voice ingest: ${mediaKey} → scrap ${scrap.id} (${transcript.length} chars)`);
+ return { scrap, draft, mediaKey };
+}
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
new file mode 100644
index 0000000000..0ea00f1769
--- /dev/null
+++ b/server/services/catalogIngestSources.test.js
@@ -0,0 +1,168 @@
+/**
+ * Unit tests for catalogIngestSources — the url / file / voice ingest paths.
+ * Every external boundary is mocked (browser CDP, Whisper, DB, extraction,
+ * disk) so the test stays pure. Asserts:
+ * - URL ingest fetches main text, creates a 'url' scrap with url metadata,
+ * and runs the extraction pipeline.
+ * - File ingest records filename/mime on a 'file' scrap.
+ * - Voice ingest transcribes, persists audio to mint a media_key, and stamps
+ * it onto a 'voice-memo' scrap; an empty transcript / empty audio throws
+ * BEFORE any scrap or audio file is written.
+ * - fetchUrlMainText throws when the page yields no readable text.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./catalogDB.js', () => ({
+ createScrap: vi.fn(),
+}));
+vi.mock('./catalogExtraction.js', () => ({
+ extractIngredients: vi.fn(),
+}));
+vi.mock('./voice/stt.js', () => ({
+ transcribe: vi.fn(),
+}));
+vi.mock('./browserService.js', () => ({
+ findOrOpenPage: vi.fn(),
+ navigateToUrl: vi.fn(),
+ listCdpPages: vi.fn(),
+ evaluateOnPage: vi.fn(),
+}));
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn(),
+}));
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { audio: '/tmp/data/audio' },
+ ensureDir: vi.fn(),
+}));
+
+const catalogDB = await import('./catalogDB.js');
+const catalogExtraction = await import('./catalogExtraction.js');
+const browserService = await import('./browserService.js');
+const fsp = await import('fs/promises');
+const {
+ fetchUrlMainText,
+ ingestFromUrl,
+ ingestFromFile,
+ ingestFromVoice,
+} = await import('./catalogIngestSources.js');
+
+const DRAFT = { runId: 'r1', characters: [], stages: [] };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ catalogExtraction.extractIngredients.mockResolvedValue(DRAFT);
+ catalogDB.createScrap.mockImplementation(async (args) => ({ id: 'cat-scrap-1', ...args }));
+});
+
+describe('fetchUrlMainText', () => {
+ it('navigates + reads main text, returning title + text + finalUrl', async () => {
+ browserService.findOrOpenPage.mockResolvedValue({ id: 'p1' });
+ browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
+ browserService.listCdpPages.mockResolvedValue([
+ { id: 'p1', url: 'https://ex.com/a', title: 'A', webSocketDebuggerUrl: 'ws://x' },
+ ]);
+ browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Article A', text: 'Body text here.' }));
+
+ const out = await fetchUrlMainText('https://ex.com/a', { settleMs: 0 });
+ expect(out).toEqual({ text: 'Body text here.', title: 'Article A', finalUrl: 'https://ex.com/a' });
+ expect(browserService.navigateToUrl).toHaveBeenCalledWith('https://ex.com/a');
+ });
+
+ it('throws when the page extracts no readable text', async () => {
+ browserService.findOrOpenPage.mockResolvedValue(null);
+ browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
+ browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: '', webSocketDebuggerUrl: 'ws://x' }]);
+ browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: '', text: ' ' }));
+
+ await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/no readable text/);
+ expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ });
+});
+
+describe('ingestFromUrl', () => {
+ it('creates a url scrap with url metadata and runs extraction', async () => {
+ browserService.findOrOpenPage.mockResolvedValue({ id: 'p1' });
+ browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
+ browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: 'A', webSocketDebuggerUrl: 'ws://x' }]);
+ browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Article A', text: 'Body.' }));
+
+ const { scrap, draft } = await ingestFromUrl({ url: 'https://ex.com/a', settleMs: 0 });
+ expect(draft).toBe(DRAFT);
+ const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ expect(createArgs.sourceKind).toBe('url');
+ expect(createArgs.rawText).toBe('Body.');
+ expect(createArgs.metadata).toEqual({ url: 'https://ex.com/a', title: 'Article A' });
+ expect(catalogExtraction.extractIngredients).toHaveBeenCalledWith(
+ expect.objectContaining({ rawText: 'Body.', scrapId: scrap.id }),
+ );
+ });
+});
+
+describe('ingestFromFile', () => {
+ it('records filename + mime on a file scrap', async () => {
+ const { draft } = await ingestFromFile({ text: 'Notes body', filename: 'notes.md', mime: 'text/markdown' });
+ expect(draft).toBe(DRAFT);
+ const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ expect(createArgs.sourceKind).toBe('file');
+ expect(createArgs.title).toBe('notes.md');
+ expect(createArgs.metadata).toEqual({ filename: 'notes.md', mime: 'text/markdown' });
+ });
+
+ it('throws on empty file text before creating a scrap', async () => {
+ await expect(ingestFromFile({ text: ' ', filename: 'empty.txt' })).rejects.toThrow(/no extractable text/);
+ expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ });
+});
+
+describe('ingestFromVoice', () => {
+ const wavBase64 = Buffer.from('fake-wav-bytes').toString('base64');
+
+ it('transcribes, persists audio to mint a media_key, and stamps it on the scrap', async () => {
+ const transcribeFn = vi.fn().mockResolvedValue({ text: 'spoken memo text' });
+ const persistFn = vi.fn().mockResolvedValue('voice-memo-abc.wav');
+
+ const { scrap, draft, mediaKey } = await ingestFromVoice(
+ { audioBase64: wavBase64, mimeType: 'audio/wav', title: 'My memo' },
+ { transcribeFn, persistFn },
+ );
+
+ expect(transcribeFn).toHaveBeenCalledWith(expect.any(Buffer), { mimeType: 'audio/wav' });
+ expect(persistFn).toHaveBeenCalledTimes(1);
+ expect(mediaKey).toBe('voice-memo-abc.wav');
+ expect(draft).toBe(DRAFT);
+ const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ expect(createArgs.sourceKind).toBe('voice-memo');
+ expect(createArgs.rawText).toBe('spoken memo text');
+ expect(createArgs.metadata).toEqual({ mediaKey: 'voice-memo-abc.wav', mimeType: 'audio/wav' });
+ expect(createArgs.title).toBe('My memo');
+ });
+
+ it('throws on an empty transcript and never persists audio or creates a scrap', async () => {
+ const transcribeFn = vi.fn().mockResolvedValue({ text: ' ' });
+ const persistFn = vi.fn();
+ await expect(
+ ingestFromVoice({ audioBase64: wavBase64 }, { transcribeFn, persistFn }),
+ ).rejects.toThrow(/empty transcript/);
+ expect(persistFn).not.toHaveBeenCalled();
+ expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ });
+
+ it('throws on empty audio before transcription', async () => {
+ const transcribeFn = vi.fn();
+ await expect(
+ ingestFromVoice({ audioBase64: '' }, { transcribeFn }),
+ ).rejects.toThrow(/audio was empty/);
+ expect(transcribeFn).not.toHaveBeenCalled();
+ });
+
+ it('defaults the audio persister to write under PATHS.audio with a wav extension', async () => {
+ const transcribeFn = vi.fn().mockResolvedValue({ text: 'hi' });
+ const { mediaKey } = await ingestFromVoice({ audioBase64: wavBase64 }, { transcribeFn });
+ // Real persistFn ran: it called writeFile under the mocked PATHS.audio.
+ expect(fsp.writeFile).toHaveBeenCalledTimes(1);
+ expect(mediaKey).toMatch(/^voice-memo-.*\.wav$/);
+ const writtenPath = fsp.writeFile.mock.calls[0][0];
+ expect(writtenPath).toContain('/tmp/data/audio');
+ });
+});