/** * The recorder on the Meetings page. Idle, it is one row: a title, whether to * include the other people (other apps' audio in the desktop app, a tab's audio * in a browser), and Start recording. Live, the same panel shows the * clock, a level meter per track, Pause and Stop, and where the audio is (on * this device, uploading, or waiting for the connection). */ import { useOpenGeniText, createOpenGeniText, type OpenGeniText } from "../messages/runtime"; import { useEffect, useId, useMemo, useRef, useState, type ReactNode, type ComponentProps, } from "react"; import { ChevronDownIcon, CircleIcon, InfoIcon, LanguagesIcon, MicIcon, NotebookPenIcon, PauseIcon, PencilIcon, PlayIcon, SquareIcon, } from "lucide-react"; import { toast } from "sonner"; import { userErrorText } from "../ui/api-error"; import { Button } from "../ui/button"; import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuLabel, DropdownMenuNote, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "../ui/dropdown-menu"; import { Checkbox } from "../ui/field"; import { Input } from "../ui/input"; import { Notice } from "../ui/notice"; import { cn } from "../app/lib/utils"; import { formatClock, ownerLiveLaneName } from "../recordings"; import type { MeetingRecorder } from "./recorder-context"; import { canStartRecording } from "./recorder-state"; import { LiveTranscript, liveStatus, type LiveTranscriptLine } from "./live-transcript"; import { DETECT_LANGUAGE, meetingLanguageOptions } from "./meeting-languages"; import { MeetingsOverlayScope } from "./overlay-scope"; const defaultText = createOpenGeniText(); type RecorderError = NonNullable; /** What went wrong and what to do, in the browser's terms. */ export function recorderErrorText( error: RecorderError, systemAudioKind: MeetingRecorder["systemAudioKind"] = "display", msg: OpenGeniText = defaultText, ): { title: string; body: string } { if (systemAudioKind === "desktop" && error.code === "system_audio_unavailable") { return desktopSystemAudioErrorText(error.reason, msg); } switch (error.code) { case "microphone_denied": return { title: msg("meetings.recorderPanel.microphoneBlocked"), body: systemAudioKind === "desktop" ? msg("meetings.recorderPanel.allowThisAppToUse") : msg("meetings.recorderPanel.allowMicrophoneAccessForThis"), }; case "microphone_unavailable": return { title: msg("meetings.recorderPanel.noMicrophoneFound"), body: msg("meetings.recorderPanel.connectAMicrophoneOrCheck"), }; case "system_audio_not_shared": return { title: msg("meetings.recorderPanel.theTabSAudioWasn"), body: msg("meetings.recorderPanel.whenYourBrowserAsksWhat"), }; case "system_audio_unavailable": return { title: msg("meetings.recorderPanel.canTRecordATab"), body: msg("meetings.recorderPanel.thisBrowserCanTShare"), }; case "unsupported": return { title: msg("meetings.recorderPanel.thisBrowserCanTRecord"), body: msg("meetings.recorderPanel.useACurrentVersionOf"), }; case "upload_failed": return { title: msg("meetings.recorderPanel.uploadStopped"), body: msg("meetings.recorderPanel.uploadfailurereasonTheRecordingIsSaved", { uploadFailureReason: uploadFailureReason(error.message, msg), }), }; default: return { title: msg("meetings.recorderPanel.recordingStopped"), body: error.message }; } } /** Why the desktop app couldn't record computer audio, and what to do on this computer. */ function desktopSystemAudioErrorText( reason: RecorderError["reason"], msg: OpenGeniText, ): { title: string; body: string } { const title = msg("meetings.recorderPanel.canTRecordComputerAudio"); switch (reason) { case "permission_denied": return { title: msg("meetings.recorderPanel.computerAudioIsnTAllowed"), body: msg("meetings.recorderPanel.allowThisAppToRecordComputerAudio"), }; case "sound_server_unavailable": return { title, body: msg("meetings.recorderPanel.noSoundServerIsRunning") }; case "unavailable": return { title, body: msg("meetings.recorderPanel.thisComputerCanTRecordItsOwnAudio") }; default: return { title, body: msg("meetings.recorderPanel.computerAudioDidnTStart") }; } } /** Why the server refused the audio, as a sentence; the server's own words when it's not a known case. */ export function uploadFailureReason(message: string, msg: OpenGeniText = defaultText): string { const text = message.trim(); if (/not.?found|\b404\b/i.test(text)) { return msg("meetings.recorderPanel.theMeetingWasDeletedOr"); } if (/forbidden|permission|\b403\b/i.test(text)) { return msg("meetings.recorderPanel.youNoLongerHavePermission"); } if (/too large|\b413\b/i.test(text)) return msg("meetings.recorderPanel.aPieceOfTheAudio"); if (/usage allowance|\b402\b/i.test(text)) { return msg("meetings.recorderPanel.theUsageAllowanceIsUsed"); } if (!text) return msg("meetings.recorderPanel.theServerRefusedTheAudio"); return msg("meetings.recorderPanel.theServerRefusedTheAudio2", { value: text.replace(/[.\s]+$/, ""), }); } /** Where the audio is right now, in one short line. */ export function uploadLine( recorder: MeetingRecorder, online: boolean, msg: OpenGeniText = defaultText, ): string | null { const upload = recorder.upload; const capturing = recorder.state === "recording" || recorder.state === "paused"; if (upload?.failed) return msg("meetings.recorderPanel.uploadFailedMessage", { message: upload.failed.message }); if (upload?.finalized) return msg("meetings.recorderPanel.uploaded"); if (upload?.discarded) return msg("meetings.recorderPanel.nothingWasRecordedSoNo"); if (!online || upload?.retryingAfterError) { return capturing ? msg("meetings.recorderPanel.notUploadingNoConnectionRecording") : msg("meetings.recorderPanel.notUploadingNoConnectionThe"); } if (recorder.state === "paused") return msg("meetings.recorderPanel.nothingIsRecordedWhilePaused"); if (capturing) { // In a browser, closing the tab ends the recording; an app keeps recording. return recorder.systemAudioKind === "desktop" ? capturingWhat(recorder, msg) : msg("meetings.recorderPanel.capturingwhatValue", { capturingWhat: capturingWhat(recorder, msg), value: msg("meetings.recorderPanel.youCanUseOtherPages"), }); } if (!upload || recorder.state === "starting") return null; // After Stop: the audio uploaded while it recorded, so usually only its end // is left; after a dropped connection it can be more. return msg("meetings.recorderPanel.savingTheRestOfTheAudio"); } /** What this recording captures, as a sentence. */ function capturingWhat(recorder: MeetingRecorder, msg: OpenGeniText = defaultText): string { const sources = new Set(recorder.tracks.map((track) => track.source)); const system = sources.has("system"); if (!sources.has("microphone")) { return system ? recorder.systemAudioKind === "desktop" ? msg("meetings.recorderPanel.recordingYourComputerSAudio") : msg("meetings.recorderPanel.recordingTheTabSAudio") : msg("meetings.recorderPanel.recording"); } return system ? recorder.systemAudioKind === "desktop" ? msg("meetings.recorderPanel.recordingYourMicrophoneAndComputerAudio") : msg("meetings.recorderPanel.recordingYourMicrophoneAndTabAudio") : msg("meetings.recorderPanel.recordingYourMicrophoneOnly"); } /** True while audio is waiting on this device because the connection is down. */ export function uploadStalled(recorder: MeetingRecorder, online: boolean): boolean { const upload = recorder.upload; if (upload?.failed || upload?.finalized || upload?.discarded) return false; return !online || Boolean(upload?.retryingAfterError); } /** Whether the browser says it's online, kept current. */ export function useOnline(): boolean { const [online, setOnline] = useState(() => typeof navigator === "undefined" ? true : navigator.onLine, ); useEffect(() => { const update = () => setOnline(navigator.onLine); window.addEventListener("online", update); window.addEventListener("offline", update); return () => { window.removeEventListener("online", update); window.removeEventListener("offline", update); }; }, []); return online; } /** A level bar fed from the analyser every frame, without re-rendering React. */ function LevelMeter({ recorder, trackNumber, label, paused, }: { recorder: MeetingRecorder; trackNumber: number; label: string; paused: boolean; }) { const barRef = useRef(null); const levels = recorder.levels; useEffect(() => { let frame = 0; let smoothed = 0; const tick = () => { const level = paused ? 0 : (levels()[trackNumber] ?? 0); // Fast attack, slow release, so speech reads as steady movement. smoothed = level > smoothed ? level : smoothed * 0.88 + level * 0.12; if (barRef.current) barRef.current.style.transform = `scaleX(${Math.max(0.02, smoothed)})`; frame = requestAnimationFrame(tick); }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); }, [levels, trackNumber, paused]); return ( // Label and bar are cells of the parent grid, so every label fits its // column and the bars line up.
{label}
); } function trackLabel( source: string, systemAudioKind: MeetingRecorder["systemAudioKind"], msg: OpenGeniText = defaultText, ): string { if (source === "microphone") return msg("meetings.recorderPanel.microphone"); if (source === "system") return systemAudioKind === "desktop" ? msg("meetings.recorderPanel.computerAudio") : msg("meetings.recorderPanel.tabAudio"); return msg("meetings.recorderPanel.audio"); } /** * Who a track's live text is from. Beside computer or tab audio the * microphone is the person recording (`ownerName`, else "You") and the other * track is "Others". A microphone alone may pick up a whole room, so it is * named like its level meter. */ export function liveSpeakerName( recorder: Pick, trackNumber: number, msg: OpenGeniText = defaultText, ownerName?: string | null, ): string { const owned = ownerLiveLaneName( recorder.tracks, trackNumber, ownerName?.trim() || msg("meetings.liveTranscript.you"), msg, ); if (owned) return owned; const source = recorder.tracks.find((track) => track.trackNumber === trackNumber)?.source; return trackLabel(source ?? "", recorder.systemAudioKind, msg); } /** The live text the recorder has heard, as lines for {@link LiveTranscript}. */ export function recorderLiveLines(recorder: Pick): LiveTranscriptLine[] { return (recorder.live ?? []).flatMap((track) => track.segments); } /** Why live text stopped, in the recorder's terms, from the first track's reason. */ export function liveUnavailableText( tracks: readonly { error: { code: string; message: string } | null }[], msg: OpenGeniText = defaultText, ): string { const code = tracks.find((track) => track.error)?.error?.code; const reason = code === "quota_exceeded" ? msg("meetings.recorderPanel.theLiveTranscriptionAccountHas") : code === "auth_error" ? msg("meetings.recorderPanel.theLiveTranscriptionProviderRefused") : code === "credential_unavailable" ? msg("meetings.recorderPanel.noLiveTranscriptionProviderIs") : code === "rate_limited" || code === "resource_exhausted" || code === "queue_overflow" ? msg("meetings.recorderPanel.theLiveTranscriptionProviderIs") : null; return msg("meetings.recorderPanel.liveTextIsnTAvailable", { value: reason ? ` ${reason}` : "" }); } /** The meeting's name while it records, and renaming it without stopping. */ function RecordingTitle({ recorder }: { recorder: MeetingRecorder }) { const msg = useOpenGeniText(); const inputId = useId(); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(""); const [saving, setSaving] = useState(false); const title = recorder.title?.trim() || null; if (editing) { const save = async () => { const next = draft.trim(); if (!next || next === title) { setEditing(false); return; } setSaving(true); try { await recorder.rename(next); setEditing(false); } catch (error) { toast.error(msg("meetings.recorderPanel.couldnTRenameThisMeeting"), { description: error instanceof Error ? userErrorText(error) : undefined, }); } finally { setSaving(false); } }; return (
{ event.preventDefault(); void save(); }} > setDraft(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") setEditing(false); }} className="h-9 min-w-0 flex-1 max-sm:basis-full" />
); } return (

{title ?? msg("meetings.recorderPanel.namedForYou")}

); } function RecorderLiveTranscript({ recorder, viewerName, }: { recorder: MeetingRecorder; viewerName: string | null; }) { const msg = useOpenGeniText(); const live = recorder.live; const lines = useMemo(() => recorderLiveLines({ live: live ?? null }), [live]); if (!live || live.length === 0) return null; const status = liveStatus(live, msg); if (lines.length === 0 && live.every((track) => track.state === "unavailable")) { // Nothing to read, so no empty box: one line says it and that nothing is lost. return (

); } return ( ({ trackNumber: track.trackNumber, text: track.partial }))} tracks={recorder.tracks} speakerName={(trackNumber) => liveSpeakerName(recorder, trackNumber, msg, viewerName)} status={status} empty={ recorder.state === "paused" ? msg("meetings.recorderPanel.pausedNothingIsHeardUntil") : msg("meetings.recorderPanel.listeningWhatSSaidShows") } /> ); } /** The pulsing dot, the state in a word and the clock of a recording under way. */ function RecordingClock({ recorder, stalled }: { recorder: MeetingRecorder; stalled: boolean }) { const msg = useOpenGeniText(); const paused = recorder.state === "paused"; return (
); } /** Pause or Resume, and Stop. */ function RecordingControls({ recorder, onStopped, }: { recorder: MeetingRecorder; onStopped?: ((recordingId: string) => void) | undefined; }) { const msg = useOpenGeniText(); const paused = recorder.state === "paused"; const stopping = recorder.state === "stopping"; const recordingId = recorder.recordingId; return ( <> ); } /** * The recording on the meeting's own page while this device records it, so * taking notes there never hides that it is still recording or how to end it: * the state and clock with Pause and Stop. Says so only when the connection * keeps the audio on this device. */ export function RecordingBar({ recorder, onStopped, }: { recorder: MeetingRecorder; /** After Stop, with the recording that stopped. */ onStopped?: ((recordingId: string) => void) | undefined; }) { const msg = useOpenGeniText(); const online = useOnline(); const stalled = uploadStalled(recorder, online); return (
{stalled ? (

{uploadLine(recorder, online, msg)}

) : null}
); } function RecorderPanelContent({ recorder, onStopped, onOpenNotes, liveTranscript = null, defaultLanguage, autoStart = null, externalRef = null, notice = null, viewerName = null, }: { /** Null while the capture code loads. */ recorder: MeetingRecorder | null; /** After Stop, with the recording to open. */ onStopped?: ((recordingId: string) => void) | undefined; /** Opens the meeting being recorded, where its notepad is. */ onOpenNotes?: ((recordingId: string) => void) | undefined; /** Offer the live transcript preview; null when the workspace has no live model. */ liveTranscript?: { defaultOn: boolean; usdPerHour?: number | null } | null; /** * The workspace's meeting language; null detects it. Undefined while it * isn't known: a meeting started then names no language, and the server * uses the workspace's. */ defaultLanguage?: string | null | undefined; /** * Start recording as soon as the recorder is ready, with this panel's * defaults, as a desktop call notification asked. `take` returns the * request once, so it starts one recording. */ autoStart?: { pending: boolean; take: () => { title: string; titleSource?: "person" | "app" } | null; } | null; /** The host's own id for what new recordings belong to, such as a project. */ externalRef?: string | null | undefined; /** A short line shown before every start, such as a reminder to tell the people present. */ notice?: ReactNode; /** The person recording's name, for their microphone's live text beside computer or tab audio. */ viewerName?: string | null | undefined; }) { const msg = useOpenGeniText(); const titleId = useId(); const tabAudioId = useId(); const [title, setTitle] = useState(""); const [languageChoice, setLanguage] = useState(null); const language = languageChoice ?? defaultLanguage ?? DETECT_LANGUAGE; const desktopAudio = recorder?.systemAudioKind === "desktop"; // In the desktop app computer audio is on unless turned off; a browser's // share prompt is something to opt into. const [tabAudioChoice, setTabAudio] = useState(null); const tabAudio = tabAudioChoice ?? desktopAudio; const [liveChoice, setLiveChoice] = useState(null); const liveOn = liveTranscript ? (liveChoice ?? liveTranscript.defaultOn) : false; const [errorDismissed, setErrorDismissed] = useState(false); const online = useOnline(); const state = recorder?.state ?? "idle"; const live = state === "recording" || state === "paused" || state === "stopping"; /** `guess` is the app's name for the meeting, used only when nobody typed one. */ const start = async (titleText: string = title, guess?: string) => { if (!recorder) return; setErrorDismissed(false); const name = titleText.trim(); const guessed = guess?.trim(); await recorder.start({ // Unnamed, Opengeni names it: after the calendar event at the time, or // from the conversation once its notes are written. ...(name ? { title: name } : guessed ? { title: guessed, titleSource: "app" as const } : {}), systemAudio: tabAudio, ...(liveOn ? { liveTranscript: true } : {}), ...(externalRef ? { externalRef } : {}), // Names their microphone in the transcript when Opengeni has no name for them. ...(viewerName?.trim() ? { ownerName: viewerName } : {}), // Sent even when it's the workspace's, so this meeting keeps it. transcription: languageChoice === null && defaultLanguage === undefined ? {} : { language: language === DETECT_LANGUAGE ? null : language }, }); }; // After an earlier recording stopped or failed too, as a click on Start would. const autoStartReady = Boolean( autoStart?.pending && recorder?.supported && canStartRecording(state), ); const startRef = useRef(start); startRef.current = start; useEffect(() => { if (!autoStartReady) return; const request = autoStart?.take(); if (!request) return; // The call app's name is a guess: a title already typed wins over it. if (request.titleSource === "app") { void startRef.current(undefined, request.title); return; } // A start without a title (the Start recording key) keeps one already typed, as the button does. if (request.title) setTitle(request.title); void startRef.current(request.title || undefined); }, [autoStart, autoStartReady]); if (recorder && !recorder.supported) { return ( {msg("meetings.recorderPanel.useACurrentVersionOf2")} ); } if (recorder && live) { const stalled = uploadStalled(recorder, online); const recordingId = recorder.recordingId; const line = uploadLine(recorder, online, msg); return (
{recorder.tracks.map((track) => ( ))}
{onOpenNotes && recordingId && recorder.upload?.created ? ( ) : null}
{line ? (

{line}

) : null}
); } const starting = state === "starting"; const error = recorder?.error && !errorDismissed ? recorder.error : null; const startHint = recorderHint( { desktopAudio, starting, tabAudio, systemAudioSupported: Boolean(recorder?.systemAudioSupported), }, msg, ); return (
{ event.preventDefault(); void start(); }} >
); } /** * The meeting's language and the live transcript: set once in Meetings * settings, so they wait in one small menu beside Start instead of crowding it. */ export function RecorderOptions({ language, onLanguageChange, live, disabled, defaultOpen = false, }: { language: string; onLanguageChange: (language: string) => void; live: { on: boolean; usdPerHour: number | null; onChange: (on: boolean) => void } | null; disabled: boolean; /** Tests open it without a pointer. */ defaultOpen?: boolean; }) { const msg = useOpenGeniText(); const options = meetingLanguageOptions( language, msg("meetings.recorderPanel.detectLanguage"), msg, ); const current = options.find((option) => option.value === language)?.label ?? language; return ( {/* The live transcript first, so it never hides below the languages. */} {live ? ( <> live.onChange(checked === true)} onSelect={(event) => event.preventDefault()} > {msg("meetings.recorderPanel.liveTranscript")} {[msg("meetings.recorderPanel.showsWhatSSaidAs"), liveCostHint(live.usdPerHour, msg)] .filter(Boolean) .join(" ")} ) : null} {msg("meetings.recorderPanel.meetingLanguage")} {options.map((option) => ( {option.label} ))} ); } /** * What the live preview adds to the bill, where it's switched on; empty when * this workspace isn't charged by the hour for it. */ export function liveCostHint(usdPerHour: number | null, msg: OpenGeniText = defaultText): string { return usdPerHour !== null ? msg("meetings.recorderPanel.theLiveTranscriptAddsAbout", { value: usdPerHour.toFixed(2) }) : ""; } function recorderHint( { desktopAudio, starting, tabAudio, systemAudioSupported, }: { desktopAudio: boolean; starting: boolean; tabAudio: boolean; systemAudioSupported: boolean; }, msg: OpenGeniText = defaultText, ): string { return desktopAudio ? starting ? msg("meetings.recorderPanel.startingAllowTheMicrophoneAnd") : tabAudio ? msg("meetings.recorderPanel.recordsYourMicrophoneAndEverything") : msg("meetings.recorderPanel.microphoneOnlySoPeopleOn") : starting ? tabAudio ? msg("meetings.recorderPanel.startingAllowTheMicrophoneIf") : msg("meetings.recorderPanel.startingAllowTheMicrophoneIf2") : tabAudio ? msg("meetings.recorderPanel.yourBrowserAsksWhatTo") : systemAudioSupported ? msg("meetings.recorderPanel.recordsYourMicrophoneForA") : msg("meetings.recorderPanel.recordsYourMicrophoneTellEveryone"); } export function RecorderPanel(props: ComponentProps) { return ( ); }