The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Call recording player: right length and seeking that holds (PR 2005)
Tim Gutberlet74f0f22c3523
diff --git a/apps/web/src/call/CallView.tsx b/apps/web/src/call/CallView.tsxindex 66ecf7f4..00def865 100644--- a/apps/web/src/call/CallView.tsx+++ b/apps/web/src/call/CallView.tsx@@ -463,7 +463,7 @@ export function CallView({ call, segments, search, side, repeatCount = 1, canRevone of them shows that part alone, with neither the card is not drawn (.cv-sum:empty, app.css). */}<Card className="cv-sum">{!live && call.recording_key && (- <RecordingPlayer callId={call.id} callDurationSec={call.duration_sec} />+ <RecordingPlayer key={call.id} callId={call.id} callDurationSec={call.duration_sec} />)}<SummaryCard call={call} /></Card>diff --git a/apps/web/src/call/RecordingPlayer.tsx b/apps/web/src/call/RecordingPlayer.tsxindex bcb96cfe..e2600ab8 100644--- a/apps/web/src/call/RecordingPlayer.tsx+++ b/apps/web/src/call/RecordingPlayer.tsx@@ -1,16 +1,26 @@-import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react'+import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent, type SyntheticEvent } from 'react'import { clock } from '../time.ts'import { RECORDINGS_NOT_KEPT } from '@linedesk/actions'import { useWorkspaceSettings } from '../settings/settings-api.ts'import { Icon } from '../ui/kit.tsx'-import { nextSpeed, recordingLength, recordingMissing, registerPlayer, SEEK_STEP_SECONDS, seekSeconds } from './playback.ts'+import {+ nextSpeed,+ RELOAD_AFTER_ERROR_MS,+ recordingLength,+ recordingMissing,+ registerPlayer,+ SEEK_STEP_SECONDS,+ seekSeconds,+} from './playback.ts'import { useT } from '@linedesk/i18n/react'type Props = { callId: string; callDurationSec: number | null }/*** Plays the call's recording: play or pause (Space), seek, speed, elapsed and total time. Nothing at all when the call- * turns out to have no recording file (404); "could not be loaded" only for other failures.+ * turns out to have no recording file (404); "could not be loaded" only for other failures. A load error first reloads+ * the recording where it was (an S3 store's link expires after a few minutes, and the next seek then fails).+ * Mount it with `key={callId}`, so no state of another call's recording is carried over.*/export function RecordingPlayer({ callId, callDurationSec }: Props) {const t = useT()@@ -20,6 +30,9 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {const [reportedLength, setReportedLength] = useState(Number.NaN)const [speed, setSpeed] = useState(1)const [dragging, setDragging] = useState(false)+ // Where to go on after a reload: the position and whether it was playing. The time of the last reload.+ const resume = useRef<{ at: number; play: boolean } | null>(null)+ const lastReload = useRef(0)// Why the audio failed, for the call it failed for: 'checking' until the API says whether there is a file at all.const [failure, setFailure] = useState<{ callId: string; kind: 'checking' | 'failed' | 'missing' } | null>(null)const failedAs = failure?.callId === callId ? failure.kind : null@@ -39,9 +52,13 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {const missing = failedAs === 'missing'useEffect(() => (missing ? undefined : registerPlayer(() => toggleRef.current())), [missing])+ const clamp = (seconds: number) => Math.max(0, Math.min(length, seconds))function seek(seconds: number) {- const to = Math.max(0, Math.min(length, seconds))- if (audio.current) audio.current.currentTime = to+ const to = clamp(seconds)+ const el = audio.current+ // Before the metadata is in, the element ignores a new time: it is set once the file is ready.+ if (el && el.readyState >= HTMLMediaElement.HAVE_METADATA) el.currentTime = to+ else resume.current = { at: to, play: resume.current?.play ?? false }setPosition(to)}function changeSpeed() {@@ -49,23 +66,40 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {if (audio.current) audio.current.playbackRate = nextsetSpeed(next)}- const seekTo = (e: PointerEvent<HTMLDivElement>) => {+ const pointerSeconds = (e: PointerEvent<HTMLDivElement>) => {const track = e.currentTarget.getBoundingClientRect()- seek(seekSeconds(e.clientX, track.left, track.width, length))+ return seekSeconds(e.clientX, track.left, track.width, length)}+ // While dragging only the knob moves; the audio seeks once, where the pointer is let go.function onPointerDown(e: PointerEvent<HTMLDivElement>) {+ if (e.button !== 0) returne.currentTarget.setPointerCapture(e.pointerId)setDragging(true)- seekTo(e)+ setPosition(clamp(pointerSeconds(e)))+ }+ function onPointerUp(e: PointerEvent<HTMLDivElement>) {+ if (!dragging) return+ setDragging(false)+ seek(pointerSeconds(e))}function onTrackKey(e: KeyboardEvent) {const step = { ArrowRight: SEEK_STEP_SECONDS, ArrowLeft: -SEEK_STEP_SECONDS }[e.key]- if (step) { e.preventDefault(); e.stopPropagation(); seek(position + step) }- else if (e.key === 'Home') seek(0)+ if (step) {+ e.preventDefault()+ e.stopPropagation()+ seek(position + step)+ } else if (e.key === 'Home') seek(0)else if (e.key === 'End') seek(length)}function onAudioError() {+ const el = audio.current+ if (el && Date.now() - lastReload.current > RELOAD_AFTER_ERROR_MS) {+ lastReload.current = Date.now()+ resume.current = { at: position, play: playing }+ el.load()+ return+ }setPlaying(false)setFailure({ callId, kind: 'checking' })void recordingMissing(src).then(none =>@@ -73,34 +107,95 @@ export function RecordingPlayer({ callId, callDurationSec }: Props) {)}+ function onLoadedMetadata(e: SyntheticEvent<HTMLAudioElement>) {+ const el = e.currentTarget+ setFailure(null)+ setReportedLength(el.duration)+ const next = resume.current+ resume.current = null+ if (!next) return+ if (next.at > 0) el.currentTime = next.at+ if (next.play) void el.play().catch(() => setPlaying(false))+ }++ const shown = Math.min(position, length)const played = length ? Math.min(1, position / length) : 0if (missing) return nullreturn (<section className="vn" aria-label={t('call.recording.label')}>{/* biome-ignore lint/a11y/useMediaCaption: the transcript below is the text of this recording */}- <audio ref={audio} src={src} preload="metadata"- onLoadedMetadata={e => { setFailure(null); setReportedLength(e.currentTarget.duration) }}+ <audio+ ref={audio}+ src={src}+ preload="metadata"+ onLoadedMetadata={onLoadedMetadata}onDurationChange={e => setReportedLength(e.currentTarget.duration)}- onTimeUpdate={e => { if (!dragging) setPosition(e.currentTarget.currentTime) }}- onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)}- onError={onAudioError} />- <button type="button" className="vn-btn" disabled={failed} aria-label={playing ? t('call.recording.pause') : t('call.recording.play')} title={t('common.withKey', { label: playing ? t('call.recording.pause') : t('call.recording.playShort'), key: 'Space' })} onClick={toggle}>+ onTimeUpdate={e => {+ if (!dragging && !e.currentTarget.seeking) setPosition(e.currentTarget.currentTime)+ }}+ onSeeked={e => {+ if (!dragging) setPosition(e.currentTarget.currentTime)+ }}+ onPlay={() => setPlaying(true)}+ onPause={() => {+ if (!resume.current) setPlaying(false)+ }}+ onEnded={() => setPlaying(false)}+ onError={onAudioError}+ />+ <button+ type="button"+ className="vn-btn"+ disabled={failed}+ aria-label={playing ? t('call.recording.pause') : t('call.recording.play')}+ title={t('common.withKey', {+ label: playing ? t('call.recording.pause') : t('call.recording.playShort'),+ key: 'Space',+ })}+ onClick={toggle}+ ><Icon name={playing ? 'pause' : 'play'} size={14} /></button><div className="vn-body">- {failedAs === 'failed' ? <span className="help">{t('call.recording.loadFailed')}</span> : (- <div className="vn-track" role="slider" tabIndex={0} aria-label={t('call.recording.position')} aria-valuemin={0} aria-valuemax={Math.round(length)}- aria-valuenow={Math.round(position)} aria-valuetext={t('call.recording.positionValue', { position: clock(position), length: clock(length) })}- onPointerDown={onPointerDown} onPointerMove={e => { if (dragging && e.buttons & 1) seekTo(e) }}- onPointerUp={() => setDragging(false)} onPointerCancel={() => setDragging(false)} onLostPointerCapture={() => setDragging(false)}- onKeyDown={onTrackKey}>- <span className="vn-line"><span className="vn-played" style={{ width: `${played * 100}%` }} /></span>+ {failedAs === 'failed' ? (+ <span className="help">{t('call.recording.loadFailed')}</span>+ ) : (+ <div+ className="vn-track"+ role="slider"+ tabIndex={0}+ aria-label={t('call.recording.position')}+ aria-valuemin={0}+ aria-valuemax={Math.round(length)}+ aria-valuenow={Math.round(shown)}+ aria-valuetext={t('call.recording.positionValue', { position: clock(shown), length: clock(length) })}+ onPointerDown={onPointerDown}+ onPointerMove={e => {+ if (dragging && e.buttons & 1) setPosition(clamp(pointerSeconds(e)))+ }}+ onPointerUp={onPointerUp}+ onPointerCancel={() => setDragging(false)}+ onLostPointerCapture={() => setDragging(false)}+ onKeyDown={onTrackKey}+ >+ <span className="vn-line">+ <span className="vn-played" style={{ width: `${played * 100}%` }} />+ </span><span className="vn-knob" style={{ left: `${played * 100}%` }} /></div>)}</div>- <span className="vn-time">{clock(position)} / {clock(length)}</span>- <button type="button" className="vn-speed" aria-label={t('call.recording.speed', { speed })} onClick={changeSpeed}>{speed}×</button>+ <span className="vn-time">+ {clock(shown)} / {clock(length)}+ </span>+ <button+ type="button"+ className="vn-speed"+ aria-label={t('call.recording.speed', { speed })}+ onClick={changeSpeed}+ >+ {speed}×+ </button></section>)}diff --git a/apps/web/src/call/playback.test.ts b/apps/web/src/call/playback.test.tsindex 6e36ac89..f5385362 100644--- a/apps/web/src/call/playback.test.ts+++ b/apps/web/src/call/playback.test.ts@@ -1,5 +1,12 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { nextSpeed, recordingLength, recordingMissing, registerPlayer, seekSeconds, togglePlayback } from './playback.ts'+import {+ nextSpeed,+ recordingLength,+ recordingMissing,+ registerPlayer,+ seekSeconds,+ togglePlayback,+} from './playback.ts'describe('recording playback', () => {it('cycles the speed 1, 1.5, 2 and back', () => {@@ -16,6 +23,11 @@ describe('recording playback', () => {expect(recordingLength(Number.POSITIVE_INFINITY, 96)).toBe(96)expect(recordingLength(Number.NaN, null)).toBe(0)})+ it('takes the call duration when the reported length is a wrong guess, far longer than the call', () => {+ expect(recordingLength(1484, 148)).toBe(148)+ expect(recordingLength(150, 148)).toBe(150)+ expect(recordingLength(1484, null)).toBe(1484)+ })it('tells a call without a recording file (404) from a recording that failed to load', async () => {const answering = (status: number) => vi.fn(async () => new Response(null, { status })) as unknown as typeof fetchexpect(await recordingMissing('/v1/calls/c1/recording', answering(404))).toBe(true)diff --git a/apps/web/src/call/playback.ts b/apps/web/src/call/playback.tsindex 7db88c58..74543305 100644--- a/apps/web/src/call/playback.ts+++ b/apps/web/src/call/playback.ts@@ -2,7 +2,8 @@const SPEEDS = [1, 1.5, 2] as constexport const SEEK_STEP_SECONDS = 5-export const nextSpeed = (speed: number): number => SPEEDS[(SPEEDS.indexOf(speed as (typeof SPEEDS)[number]) + 1) % SPEEDS.length]!+export const nextSpeed = (speed: number): number =>+ SPEEDS[(SPEEDS.indexOf(speed as (typeof SPEEDS)[number]) + 1) % SPEEDS.length]!/** Where a pointer at `clientX` is on a track from `left` with `width`, as seconds into the recording. */export function seekSeconds(clientX: number, left: number, width: number, duration: number): number {@@ -10,11 +11,23 @@ export function seekSeconds(clientX: number, left: number, width: number, duratireturn Math.max(0, Math.min(1, (clientX - left) / width)) * duration}-/** The audio element reports no usable length for some streamed files; then the call's own duration is used. */+/** How much longer than the call a reported recording length may be before it counts as a wrong estimate. */+const LENGTH_SLACK_SEC = 5++/**+ * The length the player shows and seeks in. The audio element reports no usable length for some streamed files,+ * and a browser that cannot read the end of an Ogg file guesses one from the bit rate (a 2-minute call showed+ * 24:44); a recording is never longer than its call, so then the call's own duration is used.+ */export function recordingLength(reported: number, callDurationSec: number | null): number {- return Number.isFinite(reported) && reported > 0 ? reported : callDurationSec ?? 0+ const usable = Number.isFinite(reported) && reported > 0+ if (!usable) return callDurationSec ?? 0+ return callDurationSec && reported > callDurationSec + LENGTH_SLACK_SEC ? callDurationSec : reported}+/** The least time between two reloads of a recording after a load error (an expired storage link, a network drop). */+export const RELOAD_AFTER_ERROR_MS = 10_000+/*** After the audio element failed: whether the call simply has no recording file (the API answers 404: the recording* never arrived or is gone from the store) rather than a recording that could not be played. Asks for one byte; a@@ -35,7 +48,9 @@ let toggleMounted: (() => void) | null = null/** The mounted player registers its toggle here; returns how to unregister. */export function registerPlayer(toggle: () => void): () => void {toggleMounted = toggle- return () => { if (toggleMounted === toggle) toggleMounted = null }+ return () => {+ if (toggleMounted === toggle) toggleMounted = null+ }}/** Play or pause the recording on screen. False when there is none, so the key keeps its normal meaning. */