1
0
Fork 0

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.
This commit is contained in:
Jason Fraley 2026-11-24 17:59:36 -05:00
parent 66a4337ba5
commit 18ea696d1b
20 changed files with 47870 additions and 22 deletions

View file

@ -211,6 +211,7 @@ export async function updatePreferences(input: {
discordMutedTypes: string[]; discordMutedTypes: string[];
xpDisplayMini: boolean; xpDisplayMini: boolean;
conversationTypewriter: "default" | "on" | "off"; conversationTypewriter: "default" | "on" | "off";
conversationVoice: boolean;
}): Promise<ActionResult> { }): Promise<ActionResult> {
try { try {
const { payload, user } = await authenticate(); const { payload, user } = await authenticate();
@ -249,6 +250,7 @@ export async function updatePreferences(input: {
}, },
dialogue: { dialogue: {
typewriter: input.conversationTypewriter, typewriter: input.conversationTypewriter,
voice: input.conversationVoice,
}, },
discord: { discord: {
enabled: input.discordEnabled, enabled: input.discordEnabled,

View file

@ -182,6 +182,7 @@ export default async function AccountPage() {
showCallsign={fullUser.preferences?.display?.showCallsign ?? false} showCallsign={fullUser.preferences?.display?.showCallsign ?? false}
showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true} showVersionOverlay={fullUser.preferences?.display?.showVersionOverlay ?? true}
conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"} conversationTypewriter={fullUser.preferences?.dialogue?.typewriter ?? "default"}
conversationVoice={fullUser.preferences?.dialogue?.voice !== false}
showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true} showBackgroundTexture={fullUser.preferences?.display?.showBackgroundTexture ?? true}
leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"} leadOrActual={fullUser.preferences?.display?.leadOrActual ?? "lead"}
discordEnabled={discord?.enabled ?? false} discordEnabled={discord?.enabled ?? false}

View file

@ -11,7 +11,8 @@ import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpol
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags"; import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
import { markNodeRead } from "@/lib/npc-dialogue/states"; 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 { hasPermission } from "@/utils/access-control/hasPermission";
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation"; import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings"; import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
@ -312,6 +313,9 @@ export async function resolveNpcDialogueTexts(
// files simply drop off instead of rendering dead chips. // files simply drop off instead of rendering dead chips.
const attachments = await resolveAttachments(payload, node.data.attachments); const attachments = await resolveAttachments(payload, node.data.attachments);
if (attachments.length > 0) resolved.attachments = 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 }; return { success: true, data: resolved };
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : "Unknown 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<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
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<ActionResult<AcceptedVoiceTake[]>> {
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<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
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. */ /** What a successful draft hands back to the editor. */
export interface GeneratedDialogueDraft { export interface GeneratedDialogueDraft {
/** The graph to drop into the canvas. Never persisted by the server action. */ /** The graph to drop into the canvas. Never persisted by the server action. */

View file

@ -179,6 +179,10 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
(await loadDialogueSettings(payload)).typewriterDefault, (await loadDialogueSettings(payload)).typewriterDefault,
) )
: false; : 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 ( return (
<div className="p-5 flex flex-col gap-6"> <div className="p-5 flex flex-col gap-6">
@ -191,6 +195,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
dialogue={dialogue} dialogue={dialogue}
initialSeenNodeIds={seenNodeIds} initialSeenNodeIds={seenNodeIds}
typewriter={typewriterEnabled} typewriter={typewriterEnabled}
voice={voiceEnabled}
/> />
} }
employmentSlot={ employmentSlot={

View file

@ -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.", "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.",
},
},
], ],
}, },
{ {

View file

@ -24,6 +24,7 @@ import type {
DialogueNext, DialogueNext,
DialogueNode, DialogueNode,
DialogueNodeData, DialogueNodeData,
DialogueVoiceClip,
NpcDialogueEffect, NpcDialogueEffect,
NpcDialogueNodeType, NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue"; } from "@/lib/npc-dialogue/dialogue";
@ -36,7 +37,13 @@ import {
import { reorderChoice } from "@/lib/npc-dialogue/reorder"; import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { MarkupEditor } from "./MarkupEditor"; import { MarkupEditor } from "./MarkupEditor";
import { LineAssist } from "./LineAssist"; 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 { interface NodeEditDialogProps {
readonly node: DialogueNode | null; readonly node: DialogueNode | null;
@ -851,6 +858,13 @@ export function NodeEditDialog({
/> />
)} )}
{(node.type === "dialogue" || node.type === "event" || node.type === "end") && (
<VoiceEditor
voice={draft.voice}
onChange={(voice) => patch({ voice })}
/>
)}
{(node.type === "dialogue" || node.type === "event" || node.type === "delay") && ( {(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50"> <Label className="text-[10px] uppercase tracking-wider text-white/50">
@ -907,6 +921,172 @@ export function NodeEditDialog({
); );
} }
/**
* Recorded voice for one line. Two sources land in the same place: a direct
* upload (transcoded to MP3 server-side) and an accepted voiceover submission
* (copied into `media`), so playback has a single path. Only the media pointer
* and its filename live in flowData; removing a clip never deletes the file.
*/
function VoiceEditor({
voice,
onChange,
}: {
voice: DialogueVoiceClip | undefined;
onChange: (next: DialogueVoiceClip | undefined) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [takes, setTakes] = useState<AcceptedVoiceTake[] | null>(null);
const [takeId, setTakeId] = useState<string>("");
const upload = async (file: File) => {
setBusy(true);
setError(null);
try {
const formData = new FormData();
formData.append("file", file);
const result = await uploadNpcDialogueVoice(formData);
if (result.success && result.data) {
onChange({ mediaId: result.data.mediaId, filename: result.data.filename });
} else {
setError(result.error ?? "Upload failed.");
}
} finally {
setBusy(false);
}
};
const importTake = async () => {
const id = Number(takeId);
if (!Number.isInteger(id) || id <= 0) return;
setBusy(true);
setError(null);
try {
const result = await importNpcDialogueVoice(id);
if (result.success && result.data) {
onChange({ mediaId: result.data.mediaId, filename: result.data.filename });
setTakeId("");
} else {
setError(result.error ?? "Import failed.");
}
} finally {
setBusy(false);
}
};
const loadTakes = async () => {
setError(null);
const result = await listAcceptedVoiceTakes();
if (result.success && result.data) setTakes(result.data);
else setError(result.error ?? "Could not list takes.");
};
return (
<div className="flex flex-col gap-1.5 rounded border border-zinc-700 bg-zinc-900 p-2.5">
<div className="flex items-center justify-between">
<Label className="text-[10px] uppercase tracking-wider text-zinc-400">Voice</Label>
<Button
type="button"
variant="outline"
size="sm"
disabled={busy}
onClick={() => inputRef.current?.click()}
className="h-6 border-zinc-600 text-xs text-zinc-100 hover:text-white"
>
{busy ? "Working…" : voice ? "Replace clip" : "Upload clip"}
</Button>
</div>
<input
ref={inputRef}
type="file"
className="hidden"
accept="audio/*"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void upload(file);
e.target.value = "";
}}
/>
{voice ? (
<div className="flex flex-col gap-1.5 rounded border border-zinc-700 bg-zinc-800 p-2">
<audio
controls
preload="none"
src={`/api/media/file/${voice.filename ?? ""}`}
className="h-8 w-full"
/>
<div className="flex items-center justify-between">
<span className="truncate font-mono text-[10px] text-zinc-400">
#{voice.mediaId} {voice.filename ?? ""}
</span>
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove voice clip"
onClick={() => onChange(undefined)}
className="h-6 shrink-0 border-red-900/50 px-2 text-xs text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
</div>
</div>
) : (
<p className="text-xs text-zinc-400">No voice on this line.</p>
)}
<div className="flex items-center gap-1.5">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void loadTakes()}
className="h-6 shrink-0 border-zinc-600 text-xs text-zinc-100 hover:text-white"
>
{takes ? "Refresh takes" : "Import accepted take"}
</Button>
{takes && (
<>
<select
value={takeId}
onChange={(e) => setTakeId(e.target.value)}
className="min-w-0 flex-1 rounded border border-zinc-600 bg-zinc-800 px-2 py-1 text-xs text-white"
>
<option value="">
{takes.length === 0 ? "No accepted takes yet" : "Choose a take"}
</option>
{takes.map((take) => (
<option key={take.id} value={take.id}>
{take.label}
</option>
))}
</select>
<Button
type="button"
variant="outline"
size="sm"
disabled={busy || !takeId}
onClick={() => void importTake()}
className="h-6 shrink-0 border-zinc-600 text-xs text-zinc-100 hover:text-white"
>
Use
</Button>
</>
)}
</div>
{error && <p className="text-[10px] text-red-400">{error}</p>}
<p className="text-[10px] text-zinc-400">
Plays when the line lands, and the text paces itself to the clip. Uploads are converted to
MP3 so phones play them reliably. Importing an accepted take copies the audio; the
submission stays as it was.
</p>
</div>
);
}
/** /**
* Attachment list for a dialogue/event node. Uploads go to the `media` * Attachment list for a dialogue/event node. Uploads go to the `media`
* collection through the conversation upload action (which gates on * collection through the conversation upload action (which gates on

View file

@ -118,6 +118,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false, xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {
toast.success("Background texture toggled"); toast.success("Background texture toggled");
@ -139,6 +140,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: preferences?.display?.xpDisplayMini ?? false, xpDisplayMini: preferences?.display?.xpDisplayMini ?? false,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {
toast.success("Callsign display toggled"); toast.success("Callsign display toggled");
@ -160,6 +162,7 @@ export function CommandPalette({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false), xpDisplayMini: !(preferences?.display?.xpDisplayMini ?? false),
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationVoice: preferences?.dialogue?.voice !== false,
}); });
if (result.success) { if (result.success) {
toast.success("XP display toggled"); toast.success("XP display toggled");

View file

@ -24,6 +24,8 @@ interface PreferencesFormProps {
readonly xpDisplayMini: boolean; readonly xpDisplayMini: boolean;
/** Stored choice for the NPC conversation typing animation. */ /** Stored choice for the NPC conversation typing animation. */
readonly conversationTypewriter: "default" | "on" | "off"; readonly conversationTypewriter: "default" | "on" | "off";
/** Whether recorded voice clips play in conversations. */
readonly conversationVoice: boolean;
} }
export function PreferencesForm({ export function PreferencesForm({
@ -37,6 +39,7 @@ export function PreferencesForm({
discordMutedTypes: initialDiscordMutedTypes, discordMutedTypes: initialDiscordMutedTypes,
xpDisplayMini: initialXPDisplayMini, xpDisplayMini: initialXPDisplayMini,
conversationTypewriter: initialConversationTypewriter, conversationTypewriter: initialConversationTypewriter,
conversationVoice: initialConversationVoice,
}: PreferencesFormProps) { }: PreferencesFormProps) {
const router = useRouter(); const router = useRouter();
const [mutedAll, setMutedAll] = useState(initialMutedAll); const [mutedAll, setMutedAll] = useState(initialMutedAll);
@ -53,6 +56,7 @@ export function PreferencesForm({
const [conversationTypewriter, setConversationTypewriter] = useState< const [conversationTypewriter, setConversationTypewriter] = useState<
"default" | "on" | "off" "default" | "on" | "off"
>(initialConversationTypewriter); >(initialConversationTypewriter);
const [conversationVoice, setConversationVoice] = useState(initialConversationVoice);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null); const [success, setSuccess] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -87,6 +91,7 @@ export function PreferencesForm({
discordMutedTypes, discordMutedTypes,
xpDisplayMini, xpDisplayMini,
conversationTypewriter, conversationTypewriter,
conversationVoice,
}); });
if (!result.success) { if (!result.success) {
@ -242,6 +247,25 @@ export function PreferencesForm({
</Label> </Label>
</div> </div>
</RadioGroup> </RadioGroup>
<Label
htmlFor="conversationVoice"
className="mt-2 flex items-center justify-between gap-4 text-sm"
>
<span className="flex min-w-0 flex-col gap-1">
<span>Play voice clips</span>
<span className="text-sm font-normal text-muted-foreground">
Lines with recorded voice play as they arrive. The speaker button in a
conversation header mutes it for that conversation.
</span>
</span>
<Switch
id="conversationVoice"
checked={conversationVoice}
onCheckedChange={setConversationVoice}
aria-label="Play voice clips in conversations"
/>
</Label>
</CardContent> </CardContent>
</Card> </Card>

View file

@ -178,6 +178,7 @@ export function AppSidebar({
discordMutedTypes: preferences?.discord?.mutedTypes ?? [], discordMutedTypes: preferences?.discord?.mutedTypes ?? [],
xpDisplayMini: !isMiniMode, xpDisplayMini: !isMiniMode,
conversationTypewriter: preferences?.dialogue?.typewriter ?? "default", conversationTypewriter: preferences?.dialogue?.typewriter ?? "default",
conversationVoice: preferences?.dialogue?.voice !== false,
}); });
setIsMiniMode(!isMiniMode); setIsMiniMode(!isMiniMode);
} catch (error) { } catch (error) {

View file

@ -1,7 +1,7 @@
"use client"; "use client";
import { useEffect, useMemo, useRef, useState, Fragment } from "react"; 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 { GameNpc } from "@/payload-types";
import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue"; 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 /** Type lines out character by character. Resolved server-side from the
* player's preference and the unit default; reduced-motion always wins. */ * player's preference and the unit default; reduced-motion always wins. */
readonly typewriter?: boolean; readonly typewriter?: boolean;
/** Play recorded voice clips. The header button mutes for the session. */
readonly voice?: boolean;
} }
interface ResolvedFlow { interface ResolvedFlow {
@ -62,6 +64,10 @@ type LogEntry =
/** Visible characters revealed so far while typing; undefined = whole /** Visible characters revealed so far while typing; undefined = whole
* line is showing. */ * line is showing. */
reveal?: number; 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 }; | { 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<number> {
if (Number.isFinite(audio.duration) && audio.duration > 0) return audio.duration;
return await new Promise<number>((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). /** The line a node displays, resolved text first (flag tokens interpolated).
* Single source of truth for both the reveal length and the rendered line. */ * Single source of truth for both the reveal length and the rendered line. */
function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string { function displayText(node: DialogueNode, resolved?: ResolvedNodeTexts): string {
@ -115,6 +137,7 @@ export function NpcConversation({
dialogue, dialogue,
initialSeenNodeIds, initialSeenNodeIds,
typewriter = true, typewriter = true,
voice = true,
}: NpcConversationProps) { }: NpcConversationProps) {
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@ -128,6 +151,13 @@ export function NpcConversation({
const [streamingId, setStreamingId] = useState<string | null>(null); const [streamingId, setStreamingId] = useState<string | null>(null);
/** Set by clicking the log: finish the line instead of waiting. */ /** Set by clicking the log: finish the line instead of waiting. */
const skipRevealRef = useRef<string | null>(null); const skipRevealRef = useRef<string | null>(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<HTMLAudioElement | null>(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. /** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation.
* Purely local: it resets on every `begin()`, so a choice hidden here * Purely local: it resets on every `begin()`, so a choice hidden here
* reappears the next time the conversation is opened. Persist across * 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. */ * Nodes without tokens skip the round trip and use their authored text. */
const typeIn = async (node: DialogueNode, token: number) => { const typeIn = async (node: DialogueNode, token: number) => {
let resolved: ResolvedNodeTexts | undefined; 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); const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
if (sessionRef.current !== token) return; if (sessionRef.current !== token) return;
if (res.success && res.data) resolved = res.data; if (res.success && res.data) resolved = res.data;
@ -226,13 +260,48 @@ export function NpcConversation({
const text = displayText(node, resolved); const text = displayText(node, resolved);
const id = nextId(); const id = nextId();
const total = visibleLength(text); 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 // Nothing to animate for an empty line, and a reduced-motion device skips
// the animation outright. // the animation outright.
const animate = typewriter && total > 0 && !prefersReducedMotion(); 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) => [ setLog((prev) => [
...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); markSeen(node.id);
if (!animate) return; if (!animate) return;
@ -246,7 +315,7 @@ export function NpcConversation({
setStreamingId(id); setStreamingId(id);
skipRevealRef.current = null; skipRevealRef.current = null;
const msPerUnit = revealDurationMs(total) / total; const msPerUnit = durationMs / total;
const startedAt = performance.now(); const startedAt = performance.now();
try { try {
for (;;) { for (;;) {
@ -271,6 +340,7 @@ export function NpcConversation({
// line arrives after its own typing delay. // line arrives after its own typing delay.
const begin = () => { const begin = () => {
const token = ++sessionRef.current; const token = ++sessionRef.current;
audioRef.current?.pause();
setLog([]); setLog([]);
setTyping(null); setTyping(null);
setPlayerTyping(false); setPlayerTyping(false);
@ -334,6 +404,7 @@ export function NpcConversation({
const close = () => { const close = () => {
sessionRef.current += 1; sessionRef.current += 1;
audioRef.current?.pause();
setTyping(null); setTyping(null);
setPlayerTyping(false); setPlayerTyping(false);
setStreamingId(null); setStreamingId(null);
@ -445,14 +516,34 @@ export function NpcConversation({
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60"> <DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Conversation // {npc.name} Conversation // {npc.name}
</DialogTitle> </DialogTitle>
<button <div className="flex shrink-0 items-center gap-3">
type="button" <button
onClick={close} type="button"
aria-label="Close conversation" onClick={() => {
className="shrink-0 text-white/40 transition-colors hover:text-white/90" const next = !soundOn;
> setSoundOn(next);
<XIcon className="size-4" /> if (!next) {
</button> // Muting mid-line silences the clip immediately; the reveal
// keeps its current pace.
audioRef.current?.pause();
}
}}
aria-pressed={!soundOn}
aria-label={soundOn ? "Mute voice clips" : "Unmute voice clips"}
title={soundOn ? "Mute voice clips" : "Unmute voice clips"}
className="text-white/40 transition-colors hover:text-white/90"
>
{soundOn ? <Volume2Icon className="size-4" /> : <VolumeXIcon className="size-4" />}
</button>
<button
type="button"
onClick={close}
aria-label="Close conversation"
className="text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
</div>
<span <span
aria-hidden aria-hidden
className="pointer-events-none absolute inset-0 opacity-[0.04]" className="pointer-events-none absolute inset-0 opacity-[0.04]"
@ -460,6 +551,10 @@ export function NpcConversation({
/> />
</div> </div>
{/* One element for every clip: starting a line stops the previous one
and keeps the browser's autoplay permission for the session. */}
<audio ref={audioRef} preload="none" className="hidden" />
{flow.startId === null ? ( {flow.startId === null ? (
<div className="p-5 text-sm text-white/50"> <div className="p-5 text-sm text-white/50">
This conversation has no start node. Ask staff to configure it. This conversation has no start node. Ask staff to configure it.
@ -476,7 +571,30 @@ export function NpcConversation({
className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5" className="max-h-[55vh] min-h-32 space-y-3 overflow-y-auto p-5"
> >
{log.map((entry) => ( {log.map((entry) => (
<TimelineEntry key={entry.id} entry={entry} speakerDefault={npc.name} /> <TimelineEntry
key={entry.id}
entry={entry}
speakerDefault={npc.name}
onPlayVoice={(url) => {
// Explicit click: always allowed, and clears the notice.
const audio = audioRef.current;
if (!audio) return;
audio.src = url;
audio.currentTime = 0;
void audio
.play()
.then(() =>
setLog((prev) =>
prev.map((e) =>
e.kind === "node" && e.id === entry.id
? { ...e, voiceBlocked: false }
: e,
),
),
)
.catch(() => undefined);
}}
/>
))} ))}
{typing !== null && <TypingIndicator speaker={typing} />} {typing !== null && <TypingIndicator speaker={typing} />}
{playerTyping && <TypingIndicator player />} {playerTyping && <TypingIndicator player />}
@ -555,9 +673,11 @@ export function NpcConversation({
function TimelineEntry({ function TimelineEntry({
entry, entry,
speakerDefault, speakerDefault,
onPlayVoice,
}: { }: {
entry: LogEntry; entry: LogEntry;
speakerDefault: string; speakerDefault: string;
onPlayVoice?: (url: string) => void;
}) { }) {
if (entry.kind === "player") { if (entry.kind === "player") {
return ( return (
@ -571,6 +691,18 @@ function TimelineEntry({
} }
const { node, resolved, text, reveal } = entry; const { node, resolved, text, reveal } = entry;
/** A clip the browser refused to autoplay gets a button rather than nothing. */
const voiceFallback =
entry.voiceBlocked && entry.voiceUrl && onPlayVoice ? (
<button
type="button"
onClick={() => onPlayVoice(entry.voiceUrl as string)}
className="mt-1 inline-flex items-center gap-1.5 self-start rounded-sm border border-white/20 bg-black/40 px-2 py-1 font-mono text-[10px] uppercase tracking-wider text-white/70 transition-colors hover:border-cyan-500/60 hover:text-cyan-300"
>
<Volume2Icon className="size-3" />
Play voice
</button>
) : null;
if (node.type === "event") { if (node.type === "event") {
if (node.data.presentation === "narration") { if (node.data.presentation === "narration") {
@ -582,6 +714,7 @@ function TimelineEntry({
<p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55"> <p className="max-w-[42rem] text-sm italic leading-relaxed text-white/55">
<DialogueText text={text} reveal={reveal} /> <DialogueText text={text} reveal={reveal} />
</p> </p>
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} /> <DialogueAttachments attachments={resolved?.attachments} />
</div> </div>
); );
@ -592,6 +725,7 @@ function TimelineEntry({
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80"> <p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} reveal={reveal} /> <DialogueText text={text} reveal={reveal} />
</p> </p>
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} /> <DialogueAttachments attachments={resolved?.attachments} />
</div> </div>
); );
@ -599,9 +733,12 @@ function TimelineEntry({
if (node.type === "end") { if (node.type === "end") {
return ( return (
<p className="text-sm italic text-white/50"> <div className="flex flex-col gap-1">
<DialogueText text={text} reveal={reveal} /> <p className="text-sm italic text-white/50">
</p> <DialogueText text={text} reveal={reveal} />
</p>
{voiceFallback}
</div>
); );
} }
@ -626,6 +763,7 @@ function TimelineEntry({
<span className="italic text-white/30">…</span> <span className="italic text-white/30">…</span>
)} )}
</p> </p>
{voiceFallback}
<DialogueAttachments attachments={resolved?.attachments} /> <DialogueAttachments attachments={resolved?.attachments} />
</div> </div>
); );

View file

@ -109,6 +109,34 @@ list prefixes, `{{flag}}`, `{{countdown:key}}`, and ternaries
pass server-side, so a flag value can never smuggle in another token. pass server-side, so a flag value can never smuggle in another token.
`DialogueText.tsx` is the only renderer; don't hand-roll one. `DialogueText.tsx` is the only renderer; don't hand-roll one.
## Voice clips
A line can carry `data.voice = { mediaId, filename? }` (dialogue, event and end
nodes). Like attachments, flowData stores only a pointer and
`resolveVoiceClip()` turns it into a URL per read, so a deleted file goes quiet
instead of breaking the line.
- **Storage is always `media`.** Two sources feed it: a direct upload
(`uploadNpcDialogueVoice`) and an accepted voiceover take
(`importNpcDialogueVoice`, which copies the submission's audio because
`voice-submissions` is owner-scoped while `media` is publicly readable). Both
normalise to mono MP3 through `src/lib/voiceover/transcode.ts`, because browser
recordings are WebM/Opus and iOS will not always play them. Transcode failure
stores the original rather than losing the take.
- **Playback paces the reveal.** The clip starts before the line lands and
`clipDuration()` supplies the reveal length, so text and speech finish
together; with no clip (or a muted player) the default cadence applies.
- **Autoplay is not guaranteed.** A rejected `play()` marks the entry and the
line offers a Play voice button. One `<audio>` element serves the whole
conversation: a new line stops the previous clip and the session keeps its
playback permission.
- **Controls**: `users.preferences.dialogue.voice` (default on) is the durable
choice; the speaker button in the dialog header mutes for that conversation
only, read through a ref so a cascade in flight sees the change.
- **Recruiting readers is the existing voiceover flow**: staff write a
VoiceScript, players record it, staff accept it, then the line picks it up from
the "Import accepted take" list. There is no automatic script-to-line link.
## Typing animation ## Typing animation
Lines type themselves out. `DialogueText` takes a `reveal` count and truncates the Lines type themselves out. `DialogueText` takes a `reveal` count and truncates the

View file

@ -1,5 +1,10 @@
import type { Payload } from "payload"; import type { Payload } from "payload";
import type { DialogueAttachment, ResolvedAttachment } from "./dialogue"; import type {
DialogueAttachment,
DialogueVoiceClip,
ResolvedAttachment,
ResolvedVoiceClip,
} from "./dialogue";
/** /**
* Resolve flowData attachment pointers into renderable file references. * Resolve flowData attachment pointers into renderable file references.
@ -41,3 +46,34 @@ export async function resolveAttachments(
} }
return out; return out;
} }
/**
* Resolve a node's voice clip into a playable file reference. Returns null when
* the node has no clip or the media document is gone, so the conversation
* simply plays nothing instead of erroring on a dead pointer. Payload-dependent,
* server only.
*/
export async function resolveVoiceClip(
payload: Payload,
voice: DialogueVoiceClip | undefined,
): Promise<ResolvedVoiceClip | null> {
const id = Number(voice?.mediaId);
if (!Number.isFinite(id) || id <= 0) return null;
try {
const doc = await payload.findByID({
collection: "media",
id,
depth: 0,
overrideAccess: true,
select: { filename: true, mimeType: true },
});
if (!doc?.filename) return null;
return {
url: `/api/media/file/${doc.filename}`,
filename: doc.filename,
mimeType: doc.mimeType ?? "audio/mpeg",
};
} catch {
return null;
}
}

View file

@ -199,6 +199,28 @@ export interface ResolvedAttachment {
sizeBytes?: number; sizeBytes?: number;
} }
/**
* Voice clip recorded for one line. Only the media pointer is stored in
* flowData; the runtime resolves it to a URL per read, the same way
* attachments work, so a deleted file simply stops playing.
*/
export interface DialogueVoiceClip {
/** `media` document holding the audio. */
mediaId: number;
/**
* Stored filename, for the editor's inline preview. Playback still resolves
* through `mediaId`, so a stale name cannot break the line.
*/
filename?: string;
}
/** A voice clip resolved for playback. */
export interface ResolvedVoiceClip {
url: string;
filename: string;
mimeType: string;
}
export type DialogueNodeData = { export type DialogueNodeData = {
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */ /** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
speaker?: string; speaker?: string;
@ -221,6 +243,12 @@ export type DialogueNodeData = {
closing?: string; closing?: string;
/** Files attached to this node's message (dialogue/event/end nodes). */ /** Files attached to this node's message (dialogue/event/end nodes). */
attachments?: DialogueAttachment[]; attachments?: DialogueAttachment[];
/**
* Recorded voice for this line (dialogue/event/end nodes). Plays when the
* line lands and paces the reveal to the clip, so the text finishes with the
* read. Omitted = a silent line.
*/
voice?: DialogueVoiceClip;
/** Marks this node as the conversation start. */ /** Marks this node as the conversation start. */
isStart?: boolean; isStart?: boolean;
/** Single continuation (dialogue / event / end nodes). */ /** Single continuation (dialogue / event / end nodes). */

View file

@ -11,7 +11,7 @@
* Pure module: client-safe (no Payload imports). * Pure module: client-safe (no Payload imports).
*/ */
import type { DialogueNode, ResolvedAttachment } from "./dialogue"; import type { DialogueNode, ResolvedAttachment, ResolvedVoiceClip } from "./dialogue";
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys /** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
* are documented as lowercase-with-underscores. */ * are documented as lowercase-with-underscores. */
@ -233,6 +233,11 @@ export interface ResolvedNodeTexts {
* "unresolved"). * "unresolved").
*/ */
attachments?: ResolvedAttachment[]; attachments?: ResolvedAttachment[];
/**
* Recorded voice for this line, resolved to a playable URL. Absent means the
* line is silent (or its file is gone).
*/
voice?: ResolvedVoiceClip;
} }
/** Every distinct flag key referenced by `text`, lowercased. */ /** Every distinct flag key referenced by `text`, lowercased. */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "users" ADD COLUMN "preferences_dialogue_voice" boolean DEFAULT true;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "users" DROP COLUMN "preferences_dialogue_voice";`)
}

View file

@ -168,6 +168,7 @@ import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './2
import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections'; import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections';
import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops'; import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops';
import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting'; import * as migration_20261124_223724_add_conversation_typewriter_setting from './20261124_223724_add_conversation_typewriter_setting';
import * as migration_20261124_225400_add_conversation_voice_preference from './20261124_225400_add_conversation_voice_preference';
export const migrations = [ export const migrations = [
{ {
@ -1018,6 +1019,11 @@ export const migrations = [
{ {
up: migration_20261124_223724_add_conversation_typewriter_setting.up, up: migration_20261124_223724_add_conversation_typewriter_setting.up,
down: migration_20261124_223724_add_conversation_typewriter_setting.down, down: migration_20261124_223724_add_conversation_typewriter_setting.down,
name: '20261124_223724_add_conversation_typewriter_setting' name: '20261124_223724_add_conversation_typewriter_setting',
},
{
up: migration_20261124_225400_add_conversation_voice_preference.up,
down: migration_20261124_225400_add_conversation_voice_preference.down,
name: '20261124_225400_add_conversation_voice_preference'
}, },
]; ];

View file

@ -557,6 +557,10 @@ export interface User {
* NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly. * NPC dialogue lines type out letter by letter. Click a line to finish it immediately. Reduced-motion devices always show lines instantly.
*/ */
typewriter?: ('default' | 'on' | 'off') | null; typewriter?: ('default' | 'on' | 'off') | null;
/**
* Recorded lines play as they arrive. You can also mute for the rest of a conversation with the speaker button in its header.
*/
voice?: boolean | null;
}; };
discord?: { discord?: {
enabled?: boolean | null; enabled?: boolean | null;
@ -10489,6 +10493,7 @@ export interface UsersSelect<T extends boolean = true> {
| T | T
| { | {
typewriter?: T; typewriter?: T;
voice?: T;
}; };
discord?: discord?:
| T | T

View file

@ -3,7 +3,7 @@ import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments"; import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
let payload: Payload; let payload: Payload;
@ -94,3 +94,43 @@ describe("resolveAttachments", () => {
TIMEOUT, TIMEOUT,
); );
}); });
describe("resolveVoiceClip", () => {
beforeAll(async () => {
payload = await getTestPayload();
}, TIMEOUT);
it(
"returns a playable reference for a stored clip",
async () => {
const id = await createMedia("b2-int-line.mp3");
try {
const clip = await resolveVoiceClip(payload, { mediaId: id });
expect(clip).toMatchObject({
url: "/api/media/file/b2-int-line.mp3",
filename: "b2-int-line.mp3",
});
} finally {
await payload.delete({ collection: "media", id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"stays silent rather than erroring on absent, deleted, or malformed pointers",
async () => {
expect(await resolveVoiceClip(payload, undefined)).toBeNull();
const doomed = await createMedia("b2-int-doomed.mp3");
await payload.delete({ collection: "media", id: doomed, overrideAccess: true });
expect(await resolveVoiceClip(payload, { mediaId: doomed })).toBeNull();
expect(await resolveVoiceClip(payload, { mediaId: 0 })).toBeNull();
expect(
await resolveVoiceClip(payload, { mediaId: "nope" as unknown as number }),
).toBeNull();
},
TIMEOUT,
);
});

View file

@ -44,6 +44,7 @@ describe("PreferencesForm", () => {
discordMutedTypes: [], discordMutedTypes: [],
xpDisplayMini: false, xpDisplayMini: false,
conversationTypewriter: "default", conversationTypewriter: "default",
conversationVoice: true,
}), }),
); );
@ -52,6 +53,7 @@ describe("PreferencesForm", () => {
fireEvent.click(screen.getByRole("switch", { name: "Mute all in-app notifications" })); fireEvent.click(screen.getByRole("switch", { name: "Mute all in-app notifications" }));
fireEvent.click(screen.getByRole("radio", { name: "Actual" })); fireEvent.click(screen.getByRole("radio", { name: "Actual" }));
fireEvent.click(screen.getByRole("radio", { name: "Show instantly" })); fireEvent.click(screen.getByRole("radio", { name: "Show instantly" }));
fireEvent.click(screen.getByRole("switch", { name: "Play voice clips in conversations" }));
fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" })); fireEvent.click(screen.getByRole("switch", { name: "Enable Discord notifications" }));
const discordMarketOffer = document.getElementById("discord-market-offer"); const discordMarketOffer = document.getElementById("discord-market-offer");
if (!(discordMarketOffer instanceof HTMLElement)) { if (!(discordMarketOffer instanceof HTMLElement)) {
@ -72,6 +74,7 @@ describe("PreferencesForm", () => {
discordMutedTypes: ["market:offer"], discordMutedTypes: ["market:offer"],
xpDisplayMini: true, xpDisplayMini: true,
conversationTypewriter: "off", conversationTypewriter: "off",
conversationVoice: false,
}); });
}); });
}); });