From 18ea696d1b5259d09bccc2751220a6587cbdef30 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 17:59:36 -0500 Subject: [PATCH] feat(npc-dialogue): voice clips on dialogue lines A line can now carry a recorded voice, played when it lands with the text paced to the clip so speech and text finish together. Clips live in media and flowData keeps only a pointer, so a deleted file goes quiet instead of breaking the line; resolveVoiceClip turns it into a URL per read. Authors get two sources in the node editor: a direct upload, and an accepted voiceover take imported from the existing submission flow. Both convert to mono MP3 through the voiceover transcoder, because browser recordings are WebM and iOS will not always play them, and a failed transcode stores the original rather than losing the take. Players control it twice: users.preferences.dialogue.voice (default on) is the durable choice, and the speaker button in the conversation header mutes for that conversation. Autoplay is not guaranteed, so a rejected play() shows a Play voice button on the line rather than failing silently. --- src/app/(frontend)/account/actions.ts | 2 + src/app/(frontend)/account/page.tsx | 1 + .../personnel/contacts/[id]/actions.ts | 189 +- .../personnel/contacts/[id]/page.tsx | 5 + src/collections/users/Users.ts | 10 + .../admin/npc-dialogue/NodeEditDialog.tsx | 182 +- .../command-palette/CommandPalette.tsx | 3 + .../frontend/account/PreferencesForm.tsx | 24 + src/components/frontend/blocks/AppSidebar.tsx | 1 + .../frontend/personnel/NpcConversation.tsx | 170 +- src/lib/npc-dialogue/AGENTS.md | 28 + src/lib/npc-dialogue/attachments.ts | 38 +- src/lib/npc-dialogue/dialogue.ts | 28 + src/lib/npc-dialogue/interpolate.ts | 7 +- ...400_add_conversation_voice_preference.json | 47135 ++++++++++++++++ ...25400_add_conversation_voice_preference.ts | 11 + src/migrations/index.ts | 8 +- src/payload-types.ts | 5 + .../int/npc-dialogue-attachments.int.spec.ts | 42 +- tests/int/preferences-form.int.spec.ts | 3 + 20 files changed, 47870 insertions(+), 22 deletions(-) create mode 100644 src/migrations/20261124_225400_add_conversation_voice_preference.json create mode 100644 src/migrations/20261124_225400_add_conversation_voice_preference.ts diff --git a/src/app/(frontend)/account/actions.ts b/src/app/(frontend)/account/actions.ts index 7962fbed..abc0c32b 100644 --- a/src/app/(frontend)/account/actions.ts +++ b/src/app/(frontend)/account/actions.ts @@ -211,6 +211,7 @@ export async function updatePreferences(input: { discordMutedTypes: string[]; xpDisplayMini: boolean; conversationTypewriter: "default" | "on" | "off"; + conversationVoice: boolean; }): Promise { try { const { payload, user } = await authenticate(); @@ -249,6 +250,7 @@ export async function updatePreferences(input: { }, dialogue: { typewriter: input.conversationTypewriter, + voice: input.conversationVoice, }, discord: { enabled: input.discordEnabled, diff --git a/src/app/(frontend)/account/page.tsx b/src/app/(frontend)/account/page.tsx index de50014c..58aa48ee 100644 --- a/src/app/(frontend)/account/page.tsx +++ b/src/app/(frontend)/account/page.tsx @@ -182,6 +182,7 @@ export default async function AccountPage() { showCallsign={fullUser.preferences?.display?.showCallsign ?? false} showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true} conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"} + conversationVoice={fullUser.preferences?.dialogue?.voice !== false} showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true} leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"} discordEnabled={discord?.enabled ?? false} diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts index 4e9d1f10..41a39688 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -11,7 +11,8 @@ import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpol import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags"; import { markNodeRead } from "@/lib/npc-dialogue/states"; -import { resolveAttachments } from "@/lib/npc-dialogue/attachments"; +import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments"; +import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode"; import { hasPermission } from "@/utils/access-control/hasPermission"; import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation"; import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings"; @@ -312,6 +313,9 @@ export async function resolveNpcDialogueTexts( // files simply drop off instead of rendering dead chips. const attachments = await resolveAttachments(payload, node.data.attachments); if (attachments.length > 0) resolved.attachments = attachments; + // Voice clips resolve the same way: a pointer in flowData, a URL per read. + const voice = await resolveVoiceClip(payload, node.data.voice); + if (voice) resolved.voice = voice; return { success: true, data: resolved }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; @@ -414,6 +418,189 @@ export async function uploadNpcDialogueAttachment( } } +/** Audio container types a browser recording or an audio editor produces. */ +const VOICE_INPUT_TYPES = new Set([ + "audio/mpeg", + "audio/mp3", + "audio/wav", + "audio/x-wav", + "audio/webm", + "audio/ogg", + "audio/mp4", + "audio/aac", + "audio/flac", + "video/webm", // Chrome reports MediaRecorder output as video/webm. +]); + +/** Hard cap on a raw upload; a line read is seconds, not minutes. */ +const VOICE_MAX_BYTES = 12 * 1024 * 1024; + +/** + * Store an audio file in `media` for a conversation line. + * + * Recordings arrive as WebM/Opus (or AAC in Safari), which iOS will not always + * play and which bloats the page, so anything that is not already MP3 goes + * through ffmpeg first. If transcoding fails the original is stored as-is + * rather than losing the take, and the browser falls back to its own decoder. + * + * Gated like dialogue authoring: this stores a file the whole unit will hear. + */ +export async function uploadNpcDialogueVoice( + formData: FormData, +): Promise> { + try { + const { payload, user } = await authenticate(); + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You are not allowed to edit conversations." }; + } + + const file = formData.get("file"); + if (!(file instanceof File)) { + return { success: false, error: "No file was provided." }; + } + if (!VOICE_INPUT_TYPES.has(file.type)) { + return { success: false, error: "Voice clips must be audio files." }; + } + if (file.size > VOICE_MAX_BYTES) { + return { success: false, error: "Voice clips must be 12 MB or smaller." }; + } + + const original = Buffer.from(await file.arrayBuffer()); + const isMp3 = file.type === "audio/mpeg" || file.type === "audio/mp3"; + const mp3 = isMp3 ? null : await transcodeToMp3(original, file.name); + + const bytes = mp3?.buffer ?? original; + const mimetype = mp3?.mimetype ?? file.type; + const name = mp3?.name ?? file.name; + + const doc = await payload.create({ + collection: "media", + data: { alt: file.name.replace(/\.[^/.]+$/, "").slice(0, 80) || "Voice clip" }, + file: { data: bytes, mimetype, name, size: bytes.length }, + overrideAccess: true, + }); + if (!doc.filename) { + return { success: false, error: "Upload failed: no file was stored." }; + } + return { success: true, data: { mediaId: doc.id, filename: doc.filename, mimeType: mimetype } }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} + +/** One accepted recording a line can borrow. */ +export interface AcceptedVoiceTake { + id: number; + label: string; +} + +/** + * Accepted voiceover submissions, for the "import an accepted take" picker. + * Recruiting is the existing flow: staff write a VoiceScript, players record + * it, staff accept it, and the accepted audio becomes a candidate here. + */ +export async function listAcceptedVoiceTakes(): Promise> { + try { + const { payload, user } = await authenticate(); + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You are not allowed to edit conversations." }; + } + + const res = await payload.find({ + collection: "voice-submissions", + where: { status: { equals: "accepted" } }, + limit: 100, + depth: 1, + sort: "-createdAt", + overrideAccess: true, + }); + + return { + success: true, + data: res.docs.map((doc) => { + const script = doc.script as unknown as { title?: string } | number | null; + const title = typeof script === "object" && script ? (script.title ?? "Script") : "Script"; + const submitter = doc.user as unknown as { username?: string } | number | null; + const who = + typeof submitter === "object" && submitter ? submitter.username ?? "unknown" : "unknown"; + return { id: doc.id, label: `${title} - @${who} (#${doc.id})` }; + }), + }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + return { success: false, error: message }; + } +} + +/** + * Copy an accepted voiceover take into `media` so a line can play it. + * + * The copy (rather than pointing at the submission) keeps one playback path and + * one permission story: `media` is publicly readable, while `voice-submissions` + * access is owner-scoped. Reviewer replays of the original keep working because + * the submission itself is untouched. + */ +export async function importNpcDialogueVoice( + submissionId: number, +): Promise> { + try { + const { payload, user } = await authenticate(); + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You are not allowed to edit conversations." }; + } + + const submission = await payload.findByID({ + collection: "voice-submissions", + id: submissionId, + depth: 1, + overrideAccess: true, + }); + if (!submission) return { success: false, error: "That take no longer exists." }; + if (submission.status !== "accepted") { + return { success: false, error: "Only accepted takes can be imported." }; + } + const filename = submission.filename; + if (!filename) return { success: false, error: "That take has no audio file." }; + + const { readFile } = await import("node:fs/promises"); + const path = await import("node:path"); + const filePath = path.resolve(process.cwd(), "media", "voice-submissions", filename); + let bytes: Buffer; + try { + bytes = await readFile(filePath); + } catch { + return { success: false, error: "That take's audio file is missing on disk." }; + } + + // Normalise to MP3 so every line plays the same way on every device. + const mp3 = submission.mimeType === MP3_MIMETYPE ? null : await transcodeToMp3(bytes, filename); + const stored = mp3?.buffer ?? bytes; + const mimetype = mp3?.mimetype ?? submission.mimeType ?? MP3_MIMETYPE; + const name = mp3?.name ?? filename; + + const doc = await payload.create({ + collection: "media", + data: { alt: `Voice take #${submissionId}` }, + file: { data: stored, mimetype, name, size: stored.length }, + overrideAccess: true, + }); + if (!doc.filename) { + return { success: false, error: "Import failed: no file was stored." }; + } + return { success: true, data: { mediaId: doc.id, filename: doc.filename, mimeType: mimetype } }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} + /** What a successful draft hands back to the editor. */ export interface GeneratedDialogueDraft { /** The graph to drop into the canvas. Never persisted by the server action. */ diff --git a/src/app/(frontend)/personnel/contacts/[id]/page.tsx b/src/app/(frontend)/personnel/contacts/[id]/page.tsx index 41ac50c9..aa363c32 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/page.tsx +++ b/src/app/(frontend)/personnel/contacts/[id]/page.tsx @@ -179,6 +179,10 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) { (await loadDialogueSettings(payload)).typewriterDefault, ) : false; + // Sound is on unless the player turned voice clips off in their account. + const voiceEnabled = dialogue + ? (isPayloadUser(user) ? user.preferences?.dialogue?.voice : undefined) !== false + : false; return (
@@ -191,6 +195,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) { dialogue={dialogue} initialSeenNodeIds={seenNodeIds} typewriter={typewriterEnabled} + voice={voiceEnabled} /> } employmentSlot={ diff --git a/src/collections/users/Users.ts b/src/collections/users/Users.ts index 5a436cee..cfa25b65 100644 --- a/src/collections/users/Users.ts +++ b/src/collections/users/Users.ts @@ -342,6 +342,16 @@ export const Users: CollectionConfig = { "NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.", }, }, + { + name: "voice", + label: "Play voice clips in conversations", + type: "checkbox", + defaultValue: true, + admin: { + description: + "Recorded lines play as they arrive. You can also mute for the rest of a conversation with the speaker button in its header.", + }, + }, ], }, { diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx index 8f51d731..b2047714 100644 --- a/src/components/admin/npc-dialogue/NodeEditDialog.tsx +++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx @@ -24,6 +24,7 @@ import type { DialogueNext, DialogueNode, DialogueNodeData, + DialogueVoiceClip, NpcDialogueEffect, NpcDialogueNodeType, } from "@/lib/npc-dialogue/dialogue"; @@ -36,7 +37,13 @@ import { import { reorderChoice } from "@/lib/npc-dialogue/reorder"; import { MarkupEditor } from "./MarkupEditor"; import { LineAssist } from "./LineAssist"; -import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions"; +import { + importNpcDialogueVoice, + listAcceptedVoiceTakes, + uploadNpcDialogueAttachment, + uploadNpcDialogueVoice, +} from "@/app/(frontend)/personnel/contacts/[id]/actions"; +import type { AcceptedVoiceTake } from "@/app/(frontend)/personnel/contacts/[id]/actions"; interface NodeEditDialogProps { readonly node: DialogueNode | null; @@ -851,6 +858,13 @@ export function NodeEditDialog({ /> )} + {(node.type === "dialogue" || node.type === "event" || node.type === "end") && ( + patch({ voice })} + /> + )} + {(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
+ + diff --git a/src/components/frontend/blocks/AppSidebar.tsx b/src/components/frontend/blocks/AppSidebar.tsx index e931fe63..cd71eaba 100644 --- a/src/components/frontend/blocks/AppSidebar.tsx +++ b/src/components/frontend/blocks/AppSidebar.tsx @@ -178,6 +178,7 @@ export function AppSidebar({ discordMutedTypes: preferences?.discord?.mutedTypes ?? [], xpDisplayMini: !isMiniMode, conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", + conversationVoice: preferences?.dialogue?.voice !== false, }); setIsMiniMode(!isMiniMode); } catch (error) { diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 22d1817f..a50bb757 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect, useMemo, useRef, useState, Fragment } from "react"; -import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react"; +import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react"; import type { GameNpc } from "@/payload-types"; import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue"; @@ -41,6 +41,8 @@ interface NpcConversationProps { /** Type lines out character by character. Resolved server-side from the * player's preference and the unit default; reduced-motion always wins. */ readonly typewriter?: boolean; + /** Play recorded voice clips. The header button mutes for the session. */ + readonly voice?: boolean; } interface ResolvedFlow { @@ -62,6 +64,10 @@ type LogEntry = /** Visible characters revealed so far while typing; undefined = whole * line is showing. */ reveal?: number; + /** Playable voice clip for this line, when it has one. */ + voiceUrl?: string; + /** The browser refused autoplay; the line shows a play button instead. */ + voiceBlocked?: boolean; } | { kind: "player"; id: string; text: string }; @@ -91,6 +97,22 @@ function prefersReducedMotion(): boolean { ); } +/** Seconds in a clip, or 0 when the browser has not read the metadata yet. + * Bounded so an unreadable file cannot stall the reveal. */ +async function clipDuration(audio: HTMLAudioElement): Promise { + if (Number.isFinite(audio.duration) && audio.duration > 0) return audio.duration; + return await new Promise((resolve) => { + const done = (value: number) => { + audio.removeEventListener("loadedmetadata", onMeta); + clearTimeout(timer); + resolve(value); + }; + const onMeta = () => done(Number.isFinite(audio.duration) ? audio.duration : 0); + const timer = setTimeout(() => done(0), 1200); + audio.addEventListener("loadedmetadata", onMeta); + }); +} + /** The line a node displays, resolved text first (flag tokens interpolated). * Single source of truth for both the reveal length and the rendered line. */ function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string { @@ -115,6 +137,7 @@ export function NpcConversation({ dialogue, initialSeenNodeIds, typewriter = true, + voice = true, }: NpcConversationProps) { const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const [open, setOpen] = useState(false); @@ -128,6 +151,13 @@ export function NpcConversation({ const [streamingId, setStreamingId] = useState(null); /** Set by clicking the log: finish the line instead of waiting. */ const skipRevealRef = useRef(null); + /** One element reused for every clip: a line's audio stops when the next + * starts, and the browser keeps its autoplay permission for the session. */ + const audioRef = useRef(null); + /** Sound is on unless the player turned it off or muted this session. */ + const [soundOn, setSoundOn] = useState(voice); + const soundOnRef = useRef(soundOn); + soundOnRef.current = soundOn; /** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation. * Purely local: it resets on every `begin()`, so a choice hidden here * reappears the next time the conversation is opened. Persist across @@ -217,7 +247,11 @@ export function NpcConversation({ * Nodes without tokens skip the round trip and use their authored text. */ const typeIn = async (node: DialogueNode, token: number) => { let resolved: ResolvedNodeTexts | undefined; - if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) { + if ( + collectNodeTokens(node).length > 0 || + (node.data.attachments?.length ?? 0) > 0 || + node.data.voice + ) { const res = await resolveNpcDialogueTexts(Number(npc.id), node.id); if (sessionRef.current !== token) return; if (res.success && res.data) resolved = res.data; @@ -226,13 +260,48 @@ export function NpcConversation({ const text = displayText(node, resolved); const id = nextId(); const total = visibleLength(text); + + // Start the clip before the line lands so the first word is not late. A + // rejected play() (autoplay policy) marks the entry so it can offer a + // button instead of failing silently. + const voiceUrl = resolved?.voice?.url; + let voiceStarted = false; + let clipSeconds = 0; + if (voiceUrl && soundOnRef.current && audioRef.current) { + const audio = audioRef.current; + audio.src = voiceUrl; + audio.currentTime = 0; + try { + await audio.play(); + voiceStarted = true; + clipSeconds = await clipDuration(audio); + } catch { + voiceStarted = false; + } + } + // Nothing to animate for an empty line, and a reduced-motion device skips // the animation outright. const animate = typewriter && total > 0 && !prefersReducedMotion(); + // A clip paces the reveal: the text finishes with the read, so the two do + // not drift apart on a long line. + const durationMs = + voiceStarted && clipSeconds > 0.4 + ? Math.min(60_000, clipSeconds * 1000) + : revealDurationMs(total); setLog((prev) => [ ...prev, - { kind: "node", id, node, resolved, text, reveal: animate ? 0 : undefined }, + { + kind: "node", + id, + node, + resolved, + text, + reveal: animate ? 0 : undefined, + voiceUrl, + voiceBlocked: Boolean(voiceUrl && !voiceStarted && soundOnRef.current), + }, ]); markSeen(node.id); if (!animate) return; @@ -246,7 +315,7 @@ export function NpcConversation({ setStreamingId(id); skipRevealRef.current = null; - const msPerUnit = revealDurationMs(total) / total; + const msPerUnit = durationMs / total; const startedAt = performance.now(); try { for (;;) { @@ -271,6 +340,7 @@ export function NpcConversation({ // line arrives after its own typing delay. const begin = () => { const token = ++sessionRef.current; + audioRef.current?.pause(); setLog([]); setTyping(null); setPlayerTyping(false); @@ -334,6 +404,7 @@ export function NpcConversation({ const close = () => { sessionRef.current += 1; + audioRef.current?.pause(); setTyping(null); setPlayerTyping(false); setStreamingId(null); @@ -445,14 +516,34 @@ export function NpcConversation({ Conversation // {npc.name} - +
+ + +
+ {/* One element for every clip: starting a line stops the previous one + and keeps the browser's autoplay permission for the session. */} +