From 4bfa34a775c1f612b9224f36473023ae729ab515 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 20:22:06 -0500 Subject: [PATCH] feat(npc-dialogue): preload, replay and a progress hairline for voice clips Clips were fetched the moment their line started, so every spoken line paid for the download at the worst possible moment. The next node's clip is now fetched into an object-URL cache while the current line is still being read: the URL comes from the node's own voice.filename, so no server round trip is needed. Each voiced line has a Replay control beside the speaker label, and a cyan hairline fills under the line from audio timeupdate while it plays, keyed by log entry id so only the line actually playing shows progress. Measured with two 2s clips: the second file was requested 2.8s before its line appeared, hairline widths climbed 0 to 123px, two Replay buttons rendered, and a replay restarted the clip (currentTime 2.0 to 0.56, unpaused) and brought the hairline back. The cache is bounded at 8 object URLs, revoked on eviction and on unmount. --- .../frontend/personnel/NpcConversation.tsx | 121 +++++++++++++++++- src/lib/npc-dialogue/AGENTS.md | 25 ++++ 2 files changed, 142 insertions(+), 4 deletions(-) diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx index 8f58bc5f..1885f7b1 100644 --- a/src/components/frontend/personnel/NpcConversation.tsx +++ b/src/components/frontend/personnel/NpcConversation.tsx @@ -172,6 +172,14 @@ export function NpcConversation({ const [soundOn, setSoundOn] = useState(voice); const soundOnRef = useRef(soundOn); soundOnRef.current = soundOn; + + /** Which line's clip is playing, and how far through it is, for the progress + * hairline under that line. */ + const [playing, setPlaying] = useState<{ id: string; ratio: number } | null>(null); + /** Fetched clips, keyed by their server URL, as object URLs so the next line + * starts from memory instead of the network. Bounded, and revoked on eviction. */ + const clipCacheRef = useRef>(new Map()); + const clipPendingRef = useRef>(new Set()); /** `${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 @@ -208,6 +216,47 @@ export function NpcConversation({ const nextId = () => `entry-${seq.current++}`; + /** The URL to hand the audio element: the in-memory copy when it has been + * fetched, the server URL otherwise. */ + const playableUrl = (url: string) => clipCacheRef.current.get(url) ?? url; + + /** Fetch a clip before its line arrives. Failure is silent: the line then + * loads its clip the old way, one request later. */ + const preloadClip = (url: string | undefined) => { + if (!url || !soundOnRef.current) return; + if (clipCacheRef.current.has(url) || clipPendingRef.current.has(url)) return; + clipPendingRef.current.add(url); + void fetch(url) + .then((res) => (res.ok ? res.blob() : null)) + .then((blob) => { + if (!blob) return; + const objectUrl = URL.createObjectURL(blob); + const cache = clipCacheRef.current; + cache.set(url, objectUrl); + // Eight clips is a few hundred kB and covers the usual branch depth. + while (cache.size > 8) { + const [oldest, value] = [...cache.entries()][0] ?? []; + if (!oldest) break; + URL.revokeObjectURL(value); + cache.delete(oldest); + } + }) + .catch(() => undefined) + .finally(() => clipPendingRef.current.delete(url)); + }; + + // Release the prefetched clips when the dialog goes away. Object URLs are not + // collected on their own, so without this every opened conversation would + // leave a few hundred kB behind. + useEffect( + () => () => { + const cache = clipCacheRef.current; + for (const value of cache.values()) URL.revokeObjectURL(value); + cache.clear(); + }, + [], + ); + // Invalidate pending typing timers when the component unmounts. useEffect( () => () => { @@ -294,14 +343,16 @@ export function NpcConversation({ let clipSeconds = 0; if (voiceUrl && soundOnRef.current && audioRef.current) { const audio = audioRef.current; - audio.src = voiceUrl; + audio.src = playableUrl(voiceUrl); audio.currentTime = 0; try { await audio.play(); voiceStarted = true; + setPlaying({ id, ratio: 0 }); clipSeconds = await clipDuration(audio); } catch { voiceStarted = false; + setPlaying(null); } } @@ -337,6 +388,13 @@ export function NpcConversation({ }, ]); markSeen(node.id); + + // Fetch the next line's clip now, while this one is still being read. + const nextTarget = node.data.next?.target; + const nextNode = nextTarget ? flow?.nodes.find((candidate) => candidate.id === nextTarget) : null; + const nextFilename = nextNode?.data.voice?.filename; + if (nextFilename) preloadClip(`/api/media/file/${nextFilename}`); + if (!animate) return; const setReveal = (shown: number | undefined) => @@ -759,6 +817,7 @@ export function NpcConversation({ // Muting mid-line silences the clip immediately; the reveal // keeps its current pace. audioRef.current?.pause(); + setPlaying(null); } }} aria-pressed={!soundOn} @@ -786,7 +845,18 @@ export function NpcConversation({ {/* One element for every clip: starting a line stops the previous one and keeps the browser's autoplay permission for the session. */} -