Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(meeting): improve live speaker diarization
Gabriel Stein10fb4adbfff2
diff --git a/src/components/notes/MeetingTranscriptChat.tsx b/src/components/notes/MeetingTranscriptChat.tsxindex 510517593..cf28dc324 100644--- a/src/components/notes/MeetingTranscriptChat.tsx+++ b/src/components/notes/MeetingTranscriptChat.tsx@@ -1,9 +1,18 @@-import { useState, useEffect, useRef } from "react";+import { useState, useEffect, useLayoutEffect, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";-import { Check, X } from "lucide-react";+import { Check, Lock, Sparkles, X } from "lucide-react";import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";import { cn } from "../lib/utils";import type { TranscriptSegment } from "../../hooks/useMeetingTranscription";+import {+ isTranscriptSpeakerLocked,+ type TranscriptSpeakerStatus,+} from "../../utils/transcriptSpeakerState";++interface SpeakerOption {+ speakerId: string;+ label: string;+}const BUBBLE_STYLES = {mic: {@@ -42,6 +51,8 @@ const SPEAKER_BORDER_COLORS = ["border-l-red-400/50",];+const STICKY_SCROLL_THRESHOLD_PX = 80;+const getSpeakerKey = (segment: TranscriptSegment) => segment.speaker || segment.source;const getSpeakerColorIndex = (speaker: string): number => {@@ -49,31 +60,81 @@ const getSpeakerColorIndex = (speaker: string): number => {return match ? Number(match[1]) % SPEAKER_COLORS.length : 0;};-function PartialBubble({ text, source }: { text: string; source: "mic" | "system" }) {+const getSpeakerNumber = (speakerId: string) => {+ const match = speakerId.match(/speaker_(\d+)/);+ return match ? Number(match[1]) + 1 : 1;+};++function PartialBubble({+ text,+ source,+ speakerLabel,+ speakerState,+ t,+}: {+ text: string;+ source: "mic" | "system";+ speakerLabel?: string;+ speakerState?: TranscriptSpeakerStatus;+ t: (key: string, opts?: Record<string, unknown>) => string;+}) {const s = BUBBLE_STYLES[source];return (<divclassName={cn("flex", s.align)}style={{ animation: "agent-message-in 150ms ease-out both" }}>- <div- className={cn(- "max-w-[80%] px-3 py-1.5 rounded-lg",- s.radius,- s.bg,- "text-[13px] leading-relaxed italic"+ <div className="max-w-[80%] flex flex-col">+ {speakerLabel && (+ <div className="mb-0.5 flex items-center gap-1 px-1">+ <span className="text-[11px] font-medium text-muted-foreground/70">{speakerLabel}</span>+ {speakerState === "provisional" && (+ <span className="inline-flex items-center gap-0.5 text-[10px] font-medium text-muted-foreground/40">+ <Sparkles size={9} />+ {getSpeakerStateLabel("provisional", t)}+ </span>+ )}+ {speakerState === "locked" && (+ <span className="inline-flex items-center gap-0.5 text-[10px] font-medium text-muted-foreground/40">+ <Lock size={9} />+ {getSpeakerStateLabel("locked", t)}+ </span>+ )}+ </div>)}- >- {text}- <span- className={cn("inline-block w-[2px] h-[13px] align-middle ml-0.5", s.cursor)}- style={{ animation: "agent-cursor-blink 800ms steps(1) infinite" }}- />+ <div+ className={cn(+ "px-3 py-1.5 rounded-lg",+ s.radius,+ s.bg,+ "text-[13px] leading-relaxed italic"+ )}+ >+ {text}+ <span+ className={cn("inline-block w-[2px] h-[13px] align-middle ml-0.5", s.cursor)}+ style={{ animation: "agent-cursor-blink 800ms steps(1) infinite" }}+ />+ </div></div></div>);}+const getSpeakerStateLabel = (state: TranscriptSpeakerStatus, t: (key: string) => string) => {+ switch (state) {+ case "locked":+ return t("notes.speaker.state.locked");+ case "provisional":+ return t("notes.speaker.state.provisional");+ case "suggested":+ return t("notes.speaker.state.suggested");+ case "confirmed":+ default:+ return t("notes.speaker.state.confirmed");+ }+};+function SpeakerLabel({speakerId,segment,@@ -82,7 +143,10 @@ function SpeakerLabel({participants,colorIdx,isYou,+ availableSpeakers,onMap,+ onReassignBubble,+ onReassignRun,onConfirm,onDismiss,t,@@ -94,13 +158,27 @@ function SpeakerLabel({participants?: Array<{ email: string; displayName: string | null }>;colorIdx: number;isYou: boolean;+ availableSpeakers?: SpeakerOption[];onMap?: (speakerId: string, name: string, email?: string | null, profileId?: number) => void;+ onReassignBubble?: (segmentId: string, targetSpeakerId: string) => void;+ onReassignRun?: (segmentId: string, targetSpeakerId: string) => void;onConfirm?: (speakerId: string, name: string, profileId: number) => void;onDismiss?: (speakerId: string) => void;t: (key: string, opts?: Record<string, unknown>) => string;}) {const [open, setOpen] = useState(false);const [search, setSearch] = useState("");+ const speakerState =+ segment.speakerLocked || isTranscriptSpeakerLocked(segment)+ ? "locked"+ : segment.speakerStatus ||+ (segment.suggestedName && !mappedName+ ? "suggested"+ : segment.speakerName || mappedName+ ? "confirmed"+ : segment.speakerIsPlaceholder+ ? "provisional"+ : undefined);if (isYou) {return (@@ -136,18 +214,17 @@ function SpeakerLabel({);}- const speakerNumber = (() => {- const match = speakerId.match(/speaker_(\d+)/);- return match ? Number(match[1]) + 1 : 1;- })();-- const displayLabel = mappedName || segment.speakerName || t("notes.speaker.label", { n: speakerNumber });+ const displayLabel =+ mappedName ||+ segment.speakerName ||+ t("notes.speaker.label", { n: getSpeakerNumber(speakerId) });const isUnmapped = !mappedName && !segment.speakerName;+ const reassignmentTargets = (availableSpeakers || []).filter(+ (candidate) => candidate.speakerId !== speakerId+ );const filteredParticipants = participants?.filter(- (p) =>- search === "" ||- (p.displayName || p.email).toLowerCase().includes(search.toLowerCase())+ (p) => search === "" || (p.displayName || p.email).toLowerCase().includes(search.toLowerCase()));const filteredProfiles = speakerProfiles?.filter(@@ -181,13 +258,27 @@ function SpeakerLabel({<PopoverTrigger asChild><buttonclassName={cn(- "text-[11px] font-medium mb-0.5 px-1 transition-colors duration-100 cursor-pointer rounded-sm outline-none focus-visible:ring-1 focus-visible:ring-ring",+ "group inline-flex items-center gap-1 text-[11px] font-medium mb-0.5 px-1 transition-colors duration-100 cursor-pointer rounded-sm outline-none focus-visible:ring-1 focus-visible:ring-ring",SPEAKER_COLORS[colorIdx],isUnmapped && "border-b border-dotted border-current",+ speakerState === "provisional" && "italic text-foreground/55",+ speakerState === "locked" && "text-foreground/70","hover:bg-muted/50")}>- {displayLabel}+ <span>{displayLabel}</span>+ {speakerState === "provisional" && (+ <span className="inline-flex items-center gap-0.5 rounded border border-border/50 bg-background/80 px-1 py-0.5 text-[10px] font-medium text-muted-foreground/50">+ <Sparkles size={8} />+ {t("notes.speaker.state.provisional")}+ </span>+ )}+ {speakerState === "locked" && (+ <span className="inline-flex items-center gap-0.5 rounded border border-border/50 bg-background/80 px-1 py-0.5 text-[10px] font-medium text-muted-foreground/50">+ <Lock size={8} />+ {t("notes.speaker.state.locked")}+ </span>+ )}</button></PopoverTrigger><PopoverContent className="w-72 p-0">@@ -219,7 +310,9 @@ function SpeakerLabel({</div>)}{filteredProfiles && filteredProfiles.length > 0 && (- <div className="p-1">+ <div+ className={cn("p-1", reassignmentTargets.length > 0 && "border-b border-border/30")}+ ><div className="px-2 py-1 text-[11px] font-medium text-muted-foreground">{t("notes.speaker.knownSpeakers")}</div>@@ -237,8 +330,43 @@ function SpeakerLabel({))}</div>)}+ {reassignmentTargets.length > 0 && (+ <div className="p-1">+ <div className="px-2 py-1 text-[11px] font-medium text-muted-foreground">+ {t("notes.speaker.moveBubble")}+ </div>+ {reassignmentTargets.map((candidate) => (+ <button+ key={`bubble-${candidate.speakerId}`}+ onClick={() => {+ onReassignBubble?.(segment.id, candidate.speakerId);+ setOpen(false);+ }}+ className="flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer"+ >+ <span className="truncate">{candidate.label}</span>+ </button>+ ))}+ <div className="px-2 pt-2 pb-1 text-[11px] font-medium text-muted-foreground">+ {t("notes.speaker.moveRun")}+ </div>+ {reassignmentTargets.map((candidate) => (+ <button+ key={`run-${candidate.speakerId}`}+ onClick={() => {+ onReassignRun?.(segment.id, candidate.speakerId);+ setOpen(false);+ }}+ className="flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-xs text-foreground/70 hover:bg-foreground/5 transition-colors cursor-pointer"+ >+ <span className="truncate">{candidate.label}</span>+ </button>+ ))}+ </div>+ )}{(!filteredParticipants || filteredParticipants.length === 0) &&(!filteredProfiles || filteredProfiles.length === 0) &&+ reassignmentTargets.length === 0 &&!search && (<div className="px-3 py-4 text-center text-[11px] text-foreground/30">{t("notes.speaker.typeNamePlaceholder")}@@ -254,6 +382,8 @@ interface MeetingTranscriptChatProps {segments: TranscriptSegment[];micPartial?: string;systemPartial?: string;+ systemPartialSpeakerId?: string | null;+ systemPartialSpeakerName?: string | null;speakerMappings?: Record<string, string>;speakerProfiles?: Array<{ id: number; display_name: string; email: string | null }>;participants?: Array<{ email: string; displayName: string | null }>;@@ -263,6 +393,8 @@ interface MeetingTranscriptChatProps {email?: string | null,profileId?: number) => void;+ onReassignBubble?: (segmentId: string, targetSpeakerId: string) => void;+ onReassignRun?: (segmentId: string, targetSpeakerId: string) => void;onConfirmSuggestion?: (speakerId: string, suggestedName: string, profileId: number) => void;onDismissSuggestion?: (speakerId: string) => void;}@@ -271,26 +403,73 @@ export function MeetingTranscriptChat({segments,micPartial,systemPartial,+ systemPartialSpeakerId,+ systemPartialSpeakerName,speakerMappings,speakerProfiles,participants,onMapSpeaker,+ onReassignBubble,+ onReassignRun,onConfirmSuggestion,onDismissSuggestion,}: MeetingTranscriptChatProps) {const { t } = useTranslation();const scrollRef = useRef<HTMLDivElement>(null);+ const shouldStickToBottomRef = useRef(true);+ const availableSpeakers = useMemo(+ () =>+ segments.reduce<SpeakerOption[]>((acc, segment) => {+ if (!segment.speaker || segment.speaker === "you") {+ return acc;+ }++ if (acc.some((candidate) => candidate.speakerId === segment.speaker)) {+ return acc;+ }++ acc.push({+ speakerId: segment.speaker,+ label:+ speakerMappings?.[segment.speaker] ||+ segment.speakerName ||+ t("notes.speaker.label", { n: getSpeakerNumber(segment.speaker) }),+ });+ return acc;+ }, []),+ [segments, speakerMappings, t]+ );useEffect(() => {const el = scrollRef.current;if (!el) return;- const isNearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 80;- if (isNearBottom) {- el.scrollTop = el.scrollHeight;- }+ const updateStickyScroll = () => {+ shouldStickToBottomRef.current =+ el.scrollHeight - el.scrollTop - el.clientHeight < STICKY_SCROLL_THRESHOLD_PX;+ };++ updateStickyScroll();+ el.addEventListener("scroll", updateStickyScroll);+ return () => el.removeEventListener("scroll", updateStickyScroll);+ }, []);++ useLayoutEffect(() => {+ const el = scrollRef.current;+ if (!el || !shouldStickToBottomRef.current) return;+ el.scrollTop = el.scrollHeight;}, [segments, micPartial, systemPartial]);const hasContent = segments.length > 0 || micPartial || systemPartial;+ const systemPartialSpeakerLabel =+ systemPartialSpeakerName ||+ (systemPartialSpeakerId+ ? t("notes.speaker.label", { n: getSpeakerNumber(systemPartialSpeakerId) })+ : undefined);+ const systemPartialSpeakerState = systemPartialSpeakerId+ ? systemPartialSpeakerName+ ? "confirmed"+ : "provisional"+ : undefined;if (!hasContent) {return (@@ -338,7 +517,10 @@ export function MeetingTranscriptChat({participants={participants}colorIdx={colorIdx}isYou={isYou}+ availableSpeakers={availableSpeakers}onMap={onMapSpeaker}+ onReassignBubble={onReassignBubble}+ onReassignRun={onReassignRun}onConfirm={onConfirmSuggestion}onDismiss={onDismissSuggestion}t={t}@@ -367,10 +549,24 @@ export function MeetingTranscriptChat({})}{[- { text: micPartial, source: "mic" as const },- { text: systemPartial, source: "system" as const },+ { text: micPartial, source: "mic" as const, speakerLabel: undefined },+ {+ text: systemPartial,+ source: "system" as const,+ speakerLabel: systemPartialSpeakerLabel,+ },].map(- ({ text, source }) => text && <PartialBubble key={source} text={text} source={source} />+ ({ text, source, speakerLabel }) =>+ text && (+ <PartialBubble+ key={source}+ text={text}+ source={source}+ speakerLabel={speakerLabel}+ speakerState={source === "system" ? systemPartialSpeakerState : undefined}+ t={t}+ />+ ))}</div>);diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 60ee6ef9b..e6d2cc6d9 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -34,23 +34,15 @@ import EmbeddedChat, { type EmbeddedChatMode } from "./EmbeddedChat";import { useEmbeddedChat } from "../../hooks/useEmbeddedChat";import { normalizeDbDate } from "../../utils/dateFormatting";import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";+import {+ applyTranscriptSpeakerPatch,+ lockTranscriptSpeaker,+ mergeTranscriptSegments,+ serializeTranscriptSegments,+} from "../../utils/transcriptSpeakerState";import NoteParticipants from "./NoteParticipants";import type { CalendarAttendee } from "../../types/calendar";-function serializeTranscript(segments: TranscriptSegment[]): string {- return JSON.stringify(- segments.map((s) => ({- text: s.text,- source: s.source,- timestamp: s.timestamp,- speaker: s.speaker,- speakerName: s.speakerName,- suggestedName: s.suggestedName,- suggestedProfileId: s.suggestedProfileId,- }))- );-}-function formatNoteDate(dateStr: string): string {const date = normalizeDbDate(dateStr);if (Number.isNaN(date.getTime())) return "";@@ -97,6 +89,8 @@ interface NoteEditorProps {meetingSegments?: TranscriptSegment[];meetingMicPartial?: string;meetingSystemPartial?: string;+ meetingSystemPartialSpeakerId?: string | null;+ meetingSystemPartialSpeakerName?: string | null;onStopMeetingRecording?: () => void;liveTranscript?: string;folderName?: string | null;@@ -126,6 +120,8 @@ export default function NoteEditor({meetingSegments,meetingMicPartial,meetingSystemPartial,+ meetingSystemPartialSpeakerId,+ meetingSystemPartialSpeakerName,onStopMeetingRecording,liveTranscript,folderName,@@ -147,6 +143,7 @@ export default function NoteEditor({Array<{ id: number; display_name: string; email: string | null }>>([]);const editorRef = useRef<Editor | null>(null);+ const displaySegmentsRef = useRef<TranscriptSegment[]>([]);const embeddedChat = useEmbeddedChat({noteId: note.id,@@ -174,10 +171,17 @@ export default function NoteEditor({);const displaySegments = useMemo<TranscriptSegment[]>(() => {+ if (isMeetingRecording) {+ return meetingSegments ?? [];+ }if (diarizedSegments && diarizedSegments.length > 0) return diarizedSegments;if (meetingSegments && meetingSegments.length > 0) return meetingSegments;return parseTranscriptSegments(note.transcript || "");- }, [diarizedSegments, meetingSegments, note.transcript]);+ }, [diarizedSegments, isMeetingRecording, meetingSegments, note.transcript]);++ useEffect(() => {+ displaySegmentsRef.current = displaySegments;+ }, [displaySegments]);const hasChatSegments = displaySegments.length > 0;@@ -189,6 +193,18 @@ export default function NoteEditor({}}, [note.id, note.participants]);+ const refreshSpeakerProfiles = useCallback(() => {+ window.electronAPI?.getSpeakerProfiles?.().then((profiles) => {+ setSpeakerProfiles(+ (profiles || []).map((profile) => ({+ id: profile.id,+ display_name: profile.display_name,+ email: profile.email,+ }))+ );+ });+ }, []);+const updateSegmentIndicator = useCallback(() => {const container = segmentContainerRef.current;if (!container) return;@@ -249,14 +265,9 @@ export default function NoteEditor({for (const m of mappings || []) map[m.speaker_id] = m.display_name;setSpeakerMappings(map);});- window.electronAPI?.getSpeakerProfiles?.().then((profiles) => {- setSpeakerProfiles(- (profiles || []).map((p) => ({ id: p.id, display_name: p.display_name, email: p.email }))- );- });- }, [note.id]);+ refreshSpeakerProfiles();+ }, [note.id, refreshSpeakerProfiles]);- // Auto-show chat when hook loads an existing conversation with messagesuseEffect(() => {if (!autoShowDoneRef.current &&@@ -291,13 +302,16 @@ export default function NoteEditor({if (!data?.segments?.length) return;- const enriched = data.segments.map((s: any, i: number) => ({- ...s,- id: s.id || `diarized-${i}`,- }));+ const enriched = mergeTranscriptSegments(+ displaySegmentsRef.current,+ data.segments.map((s: any, i: number) => ({+ ...s,+ id: s.id || `diarized-${i}`,+ }))+ );setDiarizedSegments(enriched);- window.electronAPI.updateNote(note.id, { transcript: serializeTranscript(enriched) });+ window.electronAPI.updateNote(note.id, { transcript: serializeTranscriptSegments(enriched) });if (data.speakerEmbeddings) {window.electronAPI?.saveNoteSpeakerEmbeddings?.(note.id, data.speakerEmbeddings);@@ -308,12 +322,36 @@ export default function NoteEditor({if (s.speakerName && s.speaker) autoMappings[s.speaker] = s.speakerName;}if (Object.keys(autoMappings).length > 0) {- setSpeakerMappings((prev) => ({ ...prev, ...autoMappings }));+ setSpeakerMappings((prev) => ({ ...autoMappings, ...prev }));}});return () => cleanup?.();}, [note.id, diarizationSessionId]);+ const persistDisplaySegments = useCallback(+ async (nextSegments: TranscriptSegment[], updateOverlay = true) => {+ if (updateOverlay) {+ setDiarizedSegments(nextSegments);+ }+ await window.electronAPI?.updateNote(note.id, {+ transcript: serializeTranscriptSegments(nextSegments),+ });+ },+ [note.id]+ );++ const getSpeakerAssignmentState = useCallback(+ (speakerId: string, sourceSegments: TranscriptSegment[]) => {+ const representativeSegment = sourceSegments.find((segment) => segment.speaker === speakerId);+ const speakerName = speakerMappings[speakerId] || representativeSegment?.speakerName;+ return {+ speakerName,+ speakerIsPlaceholder: !speakerName && !!representativeSegment?.speakerIsPlaceholder,+ };+ },+ [speakerMappings]+ );+const handleMapSpeaker = useCallback(async (speakerId: string,@@ -330,29 +368,34 @@ export default function NoteEditor({profileId);+ if (isMeetingRecording) {+ refreshSpeakerProfiles();+ return;+ }+const currentSegments = displaySegments.map((s) =>s.speaker === speakerId- ? {- ...s,+ ? lockTranscriptSpeaker(s, {speakerName: displayName,+ speaker: speakerId,+ speakerIsPlaceholder: false,suggestedName: undefined,suggestedProfileId: undefined,- }+ }): s);- window.electronAPI?.updateNote(note.id, { transcript: serializeTranscript(currentSegments) });-- window.electronAPI?.getSpeakerProfiles?.().then((profiles) => {- setSpeakerProfiles(- (profiles || []).map((p) => ({- id: p.id,- display_name: p.display_name,- email: p.email,- }))- );- });+ await persistDisplaySegments(currentSegments, !!diarizedSegments || !isMeetingRecording);++ refreshSpeakerProfiles();},- [note.id, displaySegments]+ [+ diarizedSegments,+ displaySegments,+ isMeetingRecording,+ note.id,+ persistDisplaySegments,+ refreshSpeakerProfiles,+ ]);const handleConfirmSuggestion = useCallback(@@ -366,15 +409,81 @@ export default function NoteEditor({async (speakerId: string) => {const currentSegments = displaySegments.map((s) =>s.speaker === speakerId- ? { ...s, suggestedName: undefined, suggestedProfileId: undefined }+ ? applyTranscriptSpeakerPatch(s, {+ suggestedName: undefined,+ suggestedProfileId: undefined,+ }): s);- if (diarizedSegments) {- setDiarizedSegments(currentSegments);+ await persistDisplaySegments(currentSegments, !!diarizedSegments || !isMeetingRecording);+ },+ [displaySegments, diarizedSegments, isMeetingRecording, persistDisplaySegments]+ );++ const handleReassignBubble = useCallback(+ async (segmentId: string, targetSpeakerId: string) => {+ const targetState = getSpeakerAssignmentState(targetSpeakerId, displaySegments);+ const nextSegments = displaySegments.map((segment) =>+ segment.id === segmentId+ ? lockTranscriptSpeaker(segment, {+ speaker: targetSpeakerId,+ speakerName: targetState.speakerName,+ speakerIsPlaceholder: targetState.speakerIsPlaceholder,+ suggestedName: undefined,+ suggestedProfileId: undefined,+ })+ : segment+ );+ await persistDisplaySegments(nextSegments);+ },+ [displaySegments, getSpeakerAssignmentState, persistDisplaySegments]+ );++ const handleReassignRun = useCallback(+ async (segmentId: string, targetSpeakerId: string) => {+ const segmentIndex = displaySegments.findIndex((segment) => segment.id === segmentId);+ if (segmentIndex === -1) {+ return;}- window.electronAPI?.updateNote(note.id, { transcript: serializeTranscript(currentSegments) });++ const sourceSegment = displaySegments[segmentIndex];+ const sourceSpeaker = sourceSegment.speaker;+ if (!sourceSpeaker) {+ return;+ }++ let runStart = segmentIndex;+ while (runStart > 0 && displaySegments[runStart - 1].speaker === sourceSpeaker) {+ runStart -= 1;+ }++ let runEnd = segmentIndex;+ while (+ runEnd + 1 < displaySegments.length &&+ displaySegments[runEnd + 1].speaker === sourceSpeaker+ ) {+ runEnd += 1;+ }++ const runSegmentIds = new Set(+ displaySegments.slice(runStart, runEnd + 1).map((segment) => segment.id)+ );+ const targetState = getSpeakerAssignmentState(targetSpeakerId, displaySegments);+ const nextSegments = displaySegments.map((segment) =>+ runSegmentIds.has(segment.id)+ ? lockTranscriptSpeaker(segment, {+ speaker: targetSpeakerId,+ speakerName: targetState.speakerName,+ speakerIsPlaceholder: targetState.speakerIsPlaceholder,+ suggestedName: undefined,+ suggestedProfileId: undefined,+ })+ : segment+ );++ await persistDisplaySegments(nextSegments);},- [note.id, displaySegments, diarizedSegments]+ [displaySegments, getSpeakerAssignmentState, persistDisplaySegments]);const handleTitleInput = useCallback(() => {@@ -397,7 +506,6 @@ export default function NoteEditor({document.execCommand("insertText", false, text);}, []);- // Auto-switch to transcript view after recording stops and transcript is readyconst prevRecordingRef = useRef(false);const pendingTranscriptSwitchRef = useRef(false);@@ -464,7 +572,6 @@ export default function NoteEditor({role="textbox"aria-label={t("notes.editor.noteTitle")}/>- {/* Metadata + toolbar row */}<div className="flex items-center gap-2 mt-1.5">{shortDate && (<span@@ -686,10 +793,18 @@ export default function NoteEditor({segments={displaySegments}micPartial={isMeetingRecording ? meetingMicPartial : undefined}systemPartial={isMeetingRecording ? meetingSystemPartial : undefined}+ systemPartialSpeakerId={+ isMeetingRecording ? meetingSystemPartialSpeakerId : undefined+ }+ systemPartialSpeakerName={+ isMeetingRecording ? meetingSystemPartialSpeakerName : undefined+ }speakerMappings={speakerMappings}speakerProfiles={speakerProfiles}participants={parsedParticipants}onMapSpeaker={handleMapSpeaker}+ onReassignBubble={!isMeetingRecording ? handleReassignBubble : undefined}+ onReassignRun={!isMeetingRecording ? handleReassignRun : undefined}onConfirmSuggestion={handleConfirmSuggestion}onDismissSuggestion={handleDismissSuggestion}/>diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 5bff1e433..0e4ff8c2b 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -116,6 +116,8 @@ export default function PersonalNotesView({segments: realtimeSegments,micPartial,systemPartial,+ systemPartialSpeakerId,+ systemPartialSpeakerName,diarizationSessionId,prepareTranscription,startTranscription,@@ -884,6 +886,12 @@ export default function PersonalNotesView({meetingSegments={isActiveNoteRecording ? realtimeSegments : []}meetingMicPartial={isActiveNoteRecording ? micPartial : ""}meetingSystemPartial={isActiveNoteRecording ? systemPartial : ""}+ meetingSystemPartialSpeakerId={+ isActiveNoteRecording ? systemPartialSpeakerId : undefined+ }+ meetingSystemPartialSpeakerName={+ isActiveNoteRecording ? systemPartialSpeakerName : undefined+ }onStopMeetingRecording={stopTranscription}liveTranscript={isActiveNoteRecording ? realtimeTranscript : ""}folderName={activeFolderName}diff --git a/src/helpers/diarization.js b/src/helpers/diarization.jsindex ae8d5522f..dd0dc7f39 100644--- a/src/helpers/diarization.js+++ b/src/helpers/diarization.js@@ -8,6 +8,7 @@ const { resolveBinaryPath, gracefulStopProcess } = require("../utils/serverUtilsconst { getModelsDirForService } = require("./modelDirUtils");const { convertToWav } = require("./ffmpegUtils");const { getSafeTempDir } = require("./safeTempDir");+const { applyProvisionalSpeaker, applyConfirmedSpeaker } = require("./speakerAssignmentPolicy");const DIARIZATION_TIMEOUT_MS = 300000; // 5 minutes@@ -395,31 +396,68 @@ class DiarizationManager {idx++;}- return transcriptSegments.map((seg) => {+ const nextSystemTimestampAt = (startIndex) => {+ for (let i = startIndex + 1; i < transcriptSegments.length; i += 1) {+ const candidate = transcriptSegments[i];+ if (candidate.source === "system" && candidate.timestamp != null) {+ return candidate.timestamp;+ }+ }+ return null;+ };++ let fallbackSpeakerIndex = 0;++ return transcriptSegments.map((seg, index) => {const enriched = { ...seg };if (seg.source === "mic") {- enriched.speaker = "you";+ applyConfirmedSpeaker(enriched, {+ speaker: "you",+ speakerIsPlaceholder: false,+ });return enriched;}if (seg.source === "system" && seg.timestamp != null) {- const ts = seg.timestamp;+ const segStart = seg.timestamp;+ const segEnd = nextSystemTimestampAt(index) ?? segStart + 2.5;+ const midpoint = segStart + (segEnd - segStart) / 2;let bestSpeaker = null;let bestOverlap = 0;+ let bestDistance = Number.POSITIVE_INFINITY;for (const dSeg of diarizationSegments) {- if (ts >= dSeg.start && ts <= dSeg.end) {- const overlap = dSeg.end - dSeg.start;- if (overlap > bestOverlap) {- bestOverlap = overlap;- bestSpeaker = dSeg.speaker;- }+ const overlap = Math.min(segEnd, dSeg.end) - Math.max(segStart, dSeg.start);+ if (overlap > bestOverlap) {+ bestOverlap = overlap;+ bestSpeaker = dSeg.speaker;+ }++ const distance =+ midpoint < dSeg.start+ ? dSeg.start - midpoint+ : midpoint > dSeg.end+ ? midpoint - dSeg.end+ : 0;++ if (!bestSpeaker && distance < bestDistance) {+ bestDistance = distance;+ bestSpeaker = dSeg.speaker;}}if (bestSpeaker) {- enriched.speaker = speakerMap.get(bestSpeaker) || bestSpeaker;+ applyConfirmedSpeaker(enriched, {+ speaker: speakerMap.get(bestSpeaker) || bestSpeaker,+ speakerIsPlaceholder: false,+ });+ } else if (!enriched.speaker) {+ applyProvisionalSpeaker(enriched, {+ speaker: `speaker_${fallbackSpeakerIndex}`,+ speakerIsPlaceholder: true,+ });+ fallbackSpeakerIndex += 1;}}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 1d9a9201b..24f22c339 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -12,6 +12,13 @@ const DeepgramStreaming = require("./deepgramStreaming");const OpenAIRealtimeStreaming = require("./openaiRealtimeStreaming");const AudioStorageManager = require("./audioStorage");const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");+const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");+const {+ applyConfirmedSpeaker,+ applySuggestedSpeaker,+ canAutoRelabelSpeaker,+ isSpeakerLocked,+} = require("./speakerAssignmentPolicy");const { downsample24kTo16k, pcm16ToWav } = require("../utils/audioUtils");const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";@@ -2806,6 +2813,60 @@ class IPCHandlers {let meetingTranscriptionPrepareInProgress = false;let meetingTranscriptionPreparePromise = null;+ const normalizeTranscriptForComparison = (text) =>+ String(text || "")+ .toLowerCase()+ .replace(/[^\p{L}\p{N}\s]/gu, " ")+ .replace(/\s+/g, " ")+ .trim();++ const hasNearbyTranscriptMatch = (targetSource, text, timestamp) => {+ const normalizedText = normalizeTranscriptForComparison(text);+ if (!normalizedText) {+ return false;+ }++ for (let i = meetingDiarizationSegments.length - 1; i >= 0; i -= 1) {+ const candidate = meetingDiarizationSegments[i];+ if (candidate.source !== targetSource || candidate.timestamp == null) {+ continue;+ }++ if (timestamp != null && Math.abs(candidate.timestamp - timestamp) > 4000) {+ if (candidate.timestamp < timestamp) {+ break;+ }+ continue;+ }++ const normalizedCandidate = normalizeTranscriptForComparison(candidate.text);+ if (!normalizedCandidate) {+ continue;+ }++ if (+ normalizedCandidate === normalizedText ||+ normalizedCandidate.includes(normalizedText) ||+ normalizedText.includes(normalizedCandidate)+ ) {+ return true;+ }+ }++ return false;+ };++ const shouldSkipDuplicateSystemSegment = (text, timestamp) =>+ hasNearbyTranscriptMatch("mic", text, timestamp);++ const shouldSkipDuplicateMicSegment = (text, timestamp, suppression = null) => {+ if (!suppression?.likelyRenderBleed || suppression.reason === "double_talk") {+ return false;+ }++ return hasNearbyTranscriptMatch("system", text, timestamp);+ };+const attachMeetingStreamingHandlers = (streaming, win, source) => {const send = (channel, data) => {if (!win || win.isDestroyed()) {@@ -2820,11 +2881,46 @@ class IPCHandlers {};streaming.onPartialTranscript = (text) => {+ if (source === "mic" && meetingEchoLeakDetector.isMicProbablyRenderBleed()) {+ send("meeting-transcription-segment", { text: "", source, type: "partial" });+ return;+ }+send("meeting-transcription-segment", { text, source, type: "partial" });};streaming.onFinalTranscript = (text, timestamp) => {const segments = streaming.completedSegments;const latestSegment = segments.length > 0 ? segments[segments.length - 1] : text;+ if (source === "mic") {+ const suppression = shouldSuppressMicTranscriptSegment(timestamp, Date.now());+ if (suppression.suppress) {+ debugLogger.debug("Suppressing contaminated mic segment", {+ reason: suppression.reason,+ averageCorrelation: suppression.averageCorrelation?.toFixed(3),+ averageResidual: suppression.averageResidual?.toFixed(3),+ text: latestSegment.slice(0, 80),+ });+ send("meeting-transcription-segment", { text: "", source, type: "partial" });+ return;+ }++ if (shouldSkipDuplicateMicSegment(latestSegment, timestamp, suppression)) {+ debugLogger.debug("Skipping duplicate mic segment that matches recent system audio", {+ text: latestSegment.slice(0, 80),+ averageCorrelation: suppression.averageCorrelation?.toFixed(3),+ averageResidual: suppression.averageResidual?.toFixed(3),+ });+ send("meeting-transcription-segment", { text: "", source, type: "partial" });+ return;+ }+ }++ if (source === "system" && shouldSkipDuplicateSystemSegment(latestSegment, timestamp)) {+ debugLogger.debug("Skipping duplicate system segment that matches recent mic audio", {+ text: latestSegment.slice(0, 80),+ });+ return;+ }debugLogger.debug("Meeting segment sending to renderer", {source,text: latestSegment.slice(0, 80),@@ -2936,7 +3032,9 @@ class IPCHandlers {return win;};+ const MEETING_MIC_REFERENCE_ALIGNMENT_MS = 180;let meetingSendCounts = { mic: 0, system: 0 };+ const meetingEchoLeakDetector = new MeetingEchoLeakDetector();const fs = require("fs");let meetingDiarizationStream = null;@@ -2944,6 +3042,7 @@ class IPCHandlers {let meetingDiarizationSegments = [];let meetingLiveSpeakerActive = false;let meetingLiveSpeakerState = null;+ let meetingLiveSpeakerStartedAt = null;let meetingLocalMode = false;let meetingLocalBuffers = { mic: [], system: [] };@@ -2953,17 +3052,72 @@ class IPCHandlers {let meetingLocalProvider = null;let meetingLocalModel = null;let meetingLocalTranscribing = false;+ let meetingPendingMicChunks = [];const getLiveSpeakerProfiles = () => this.databaseManager.getSpeakerProfiles(true);+ const shouldSuppressMicTranscriptSegment = (startedAt, endedAt = Date.now()) =>+ meetingEchoLeakDetector.shouldSuppressMicSegment(startedAt, endedAt);++ const dispatchMeetingAudioBuffer = (buffer, source) => {+ if (meetingLocalMode) {+ meetingLocalBuffers[source].push(buffer);+ return;+ }++ const streaming = source === "mic" ? this._meetingMicStreaming : this._meetingSystemStreaming;+ if (!streaming) {+ if (meetingSendCounts[source] === 0) {+ debugLogger.error("Meeting audio send: no streaming instance", { source });+ }+ return;+ }++ const sent = streaming.sendAudio(buffer);+ meetingSendCounts[source]++;+ if (meetingSendCounts[source] <= 5 || meetingSendCounts[source] % 100 === 0) {+ debugLogger.debug("Meeting audio send", {+ source,+ bytes: buffer.length,+ sent,+ wsReady: streaming.ws?.readyState,+ totalSent: streaming.audioBytesSent,+ count: meetingSendCounts[source],+ });+ }+ };++ const flushPendingMeetingMicChunks = (force = false) => {+ if (!meetingPendingMicChunks.length) {+ return;+ }++ const now = Date.now();+ while (meetingPendingMicChunks.length > 0) {+ const next = meetingPendingMicChunks[0];+ if (!force && now - next.queuedAt < MEETING_MIC_REFERENCE_ALIGNMENT_MS) {+ break;+ }++ meetingPendingMicChunks.shift();+ const analysis = meetingEchoLeakDetector.analyzeMicChunk(next.buffer);+ if (analysis?.shouldMute) {+ if (!meetingLocalMode) {+ dispatchMeetingAudioBuffer(Buffer.alloc(next.buffer.length), "mic");+ }+ continue;+ }++ dispatchMeetingAudioBuffer(next.buffer, "mic");+ }+ };const stopLiveSpeakerIdentification = async () => {if (!meetingLiveSpeakerActive) {return null;}- meetingLiveSpeakerState = liveSpeakerIdentifier.getTransientMap();meetingLiveSpeakerActive = false;- liveSpeakerIdentifier.stop();+ meetingLiveSpeakerState = await liveSpeakerIdentifier.stop();return meetingLiveSpeakerState;};@@ -2975,17 +3129,42 @@ class IPCHandlers {}meetingLiveSpeakerState = null;+ meetingLiveSpeakerStartedAt = Date.now();const started = await liveSpeakerIdentifier.start((identification) => {if (!win || win.isDestroyed()) {return;}- win.webContents.send("meeting-speaker-identified", identification);+ const startTime = Math.max(+ meetingLiveSpeakerStartedAt || 0,+ (meetingLiveSpeakerStartedAt || 0) + identification.startTime * 1000+ );+ const endTime = Math.max(+ startTime,+ (meetingLiveSpeakerStartedAt || 0) + identification.endTime * 1000+ );+ const enrichedIdentification = {+ ...identification,+ startTime,+ endTime,+ };++ win.webContents.send("meeting-speaker-identified", enrichedIdentification);for (const seg of meetingDiarizationSegments) {- if (seg.source === "system" && !seg.speaker) {- seg.speaker = identification.speakerId;+ if (+ seg.source === "system" &&+ seg.timestamp != null &&+ seg.timestamp >= startTime &&+ seg.timestamp <= endTime &&+ (!seg.speaker || seg.speakerIsPlaceholder)+ ) {+ applyConfirmedSpeaker(seg, {+ speaker: identification.speakerId,+ speakerName: identification.displayName || seg.speakerName,+ speakerIsPlaceholder: false,+ });}}},@@ -2996,6 +3175,8 @@ class IPCHandlers {if (started) {meetingLiveSpeakerActive = true;+ } else {+ meetingLiveSpeakerStartedAt = null;}return started;@@ -3036,9 +3217,34 @@ class IPCHandlers {if (result?.success && result.text?.trim()) {const text = result.text.trim();- meetingLocalTranscript += (meetingLocalTranscript ? " " : "") + text;-const segTimestamp = Date.now();+ if (source === "mic") {+ const chunkDurationMs = (pcm24k.length / 2 / 24000) * 1000;+ const suppression = shouldSuppressMicTranscriptSegment(+ segTimestamp - chunkDurationMs,+ segTimestamp+ );+ if (suppression.suppress) {+ debugLogger.debug("Suppressing contaminated local mic segment", {+ reason: suppression.reason,+ averageCorrelation: suppression.averageCorrelation?.toFixed(3),+ averageResidual: suppression.averageResidual?.toFixed(3),+ text: text.slice(0, 80),+ });+ return;+ }++ if (shouldSkipDuplicateMicSegment(text, segTimestamp, suppression)) {+ debugLogger.debug("Skipping duplicate local mic segment that matches system audio", {+ text: text.slice(0, 80),+ averageCorrelation: suppression.averageCorrelation?.toFixed(3),+ averageResidual: suppression.averageResidual?.toFixed(3),+ });+ return;+ }+ }++ meetingLocalTranscript += (meetingLocalTranscript ? " " : "") + text;meetingDiarizationSegments.push({ text, source, timestamp: segTimestamp });if (meetingLocalWin && !meetingLocalWin.isDestroyed()) {@@ -3079,6 +3285,7 @@ class IPCHandlers {}void stopLiveSpeakerIdentification();meetingLiveSpeakerState = null;+ meetingLiveSpeakerStartedAt = null;meetingLocalMode = false;meetingLocalBuffers = { mic: [], system: [] };if (meetingDiarizationStream) {@@ -3095,12 +3302,17 @@ class IPCHandlers {meetingLocalProvider = null;meetingLocalModel = null;meetingLocalTranscribing = false;+ meetingPendingMicChunks = [];+ meetingEchoLeakDetector.reset();};const resetMeetingStreamingState = () => {this._meetingMicStreaming = null;this._meetingSystemStreaming = null;meetingSendCounts = { mic: 0, system: 0 };+ meetingLiveSpeakerStartedAt = null;+ meetingPendingMicChunks = [];+ meetingEchoLeakDetector.reset();};const disconnectMeetingStreaming = async () => {@@ -3205,6 +3417,7 @@ class IPCHandlers {meetingTranscriptionStartInProgress = true;try {const systemAudioMode = getMeetingSystemAudioMode();+ meetingEchoLeakDetector.reset();// If already prepared (warm connections from prepare), just re-attach handlersif (!meetingLocalMode && isMeetingStreamingConnected()) {@@ -3250,7 +3463,10 @@ class IPCHandlers {}await connectRealtimeStreaming(event, options);- await startLiveSpeakerIdentification(BrowserWindow.fromWebContents(event.sender), systemAudioMode);+ await startLiveSpeakerIdentification(+ BrowserWindow.fromWebContents(event.sender),+ systemAudioMode+ );if (systemAudioMode === "native") {await startNativeMeetingSystemAudio(event);}@@ -3265,11 +3481,14 @@ class IPCHandlers {});const sendMeetingAudio = (audioBuffer, source) => {+ const outboundBuffer = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);+if (source === "system") {- const buf = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);+ meetingEchoLeakDetector.recordSystemChunk(outboundBuffer);+ flushPendingMeetingMicChunks();if (meetingLiveSpeakerActive) {- void liveSpeakerIdentifier.feedAudio(buf);+ void liveSpeakerIdentifier.feedAudio(outboundBuffer);}if (!meetingDiarizationStream) {@@ -3277,34 +3496,31 @@ class IPCHandlers {meetingDiarizationPath = path.join(os.tmpdir(), `ow-diarize-raw-${Date.now()}.pcm`);meetingDiarizationStream = fs.createWriteStream(meetingDiarizationPath);}- meetingDiarizationStream.write(buf);- }-- if (meetingLocalMode) {- const buf = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);- meetingLocalBuffers[source].push(buf);+ meetingDiarizationStream.write(outboundBuffer);+ dispatchMeetingAudioBuffer(outboundBuffer, "system");return;}- const streaming = source === "mic" ? this._meetingMicStreaming : this._meetingSystemStreaming;- if (!streaming) {- if (meetingSendCounts[source] === 0) {- debugLogger.error("Meeting audio send: no streaming instance", { source });+ if (source === "mic") {+ if (!hasNativeMeetingSystemAudio()) {+ const analysis = meetingEchoLeakDetector.analyzeMicChunk(outboundBuffer);+ if (analysis?.shouldMute) {+ if (!meetingLocalMode) {+ dispatchMeetingAudioBuffer(Buffer.alloc(outboundBuffer.length), "mic");+ }+ return;+ }++ dispatchMeetingAudioBuffer(outboundBuffer, "mic");+ return;}- return;- }- const buf = Buffer.isBuffer(audioBuffer) ? audioBuffer : Buffer.from(audioBuffer);- const sent = streaming.sendAudio(buf);- meetingSendCounts[source]++;- if (meetingSendCounts[source] <= 5 || meetingSendCounts[source] % 100 === 0) {- debugLogger.debug("Meeting audio send", {- source,- bytes: buf.length,- sent,- wsReady: streaming.ws?.readyState,- totalSent: streaming.audioBytesSent,- count: meetingSendCounts[source],++ meetingPendingMicChunks.push({+ buffer: outboundBuffer,+ queuedAt: Date.now(),});+ flushPendingMeetingMicChunks();+ return;}};@@ -3332,6 +3548,8 @@ class IPCHandlers {await this.audioTapManager.stop();}+ flushPendingMeetingMicChunks(true);+const liveSpeakerState = await stopLiveSpeakerIdentification().catch(() => null);const diarizationSessionId = `diar-${Date.now()}`;@@ -3355,7 +3573,11 @@ class IPCHandlers {} catch (err) {debugLogger.error("Local meeting final transcription failed", { error: err.message });}- const transcript = meetingLocalTranscript;+ const transcript =+ diarizationSegments+ .map((segment) => segment.text)+ .join(" ")+ .trim() || meetingLocalTranscript;resetMeetingLocalState();// Fire-and-forget background diarization (or notify skip)@@ -3371,7 +3593,11 @@ class IPCHandlers {}const results = await disconnectMeetingStreaming();- const transcript = [results[0]?.text, results[1]?.text].filter(Boolean).join(" ");+ const transcript =+ diarizationSegments+ .map((segment) => segment.text)+ .join(" ")+ .trim() || [results[0]?.text, results[1]?.text].filter(Boolean).join(" ");// Fire-and-forget background diarization (or notify skip)this._startOrSkipDiarization(@@ -5137,8 +5363,9 @@ class IPCHandlers {const embeddings = this.databaseManager.getNoteSpeakerEmbeddings(noteId);const noteSpeakerEmbedding = embeddings.find((e) => e.speaker_id === speakerId);const liveSpeakerEmbedding = liveSpeakerIdentifier.getSpeakerEmbedding(speakerId);- const speakerEmbeddingBuffer = noteSpeakerEmbedding?.embedding- || (liveSpeakerEmbedding ? Buffer.from(liveSpeakerEmbedding.buffer) : null);+ const speakerEmbeddingBuffer =+ noteSpeakerEmbedding?.embedding ||+ (liveSpeakerEmbedding ? Buffer.from(liveSpeakerEmbedding.buffer) : null);let resolvedProfileId = profileId ?? null;if (speakerEmbeddingBuffer) {@@ -5183,20 +5410,33 @@ class IPCHandlers {const speakerEmbeddings = require("./speakerEmbeddings");const noteIds = this.databaseManager.getNotesWithUnmappedSpeakers();- const profileEmb = new Float32Array(profile.embedding.buffer, profile.embedding.byteOffset, profile.embedding.byteLength / 4);+ const profileEmb = new Float32Array(+ profile.embedding.buffer,+ profile.embedding.byteOffset,+ profile.embedding.byteLength / 4+ );for (const noteId of noteIds) {const embeddings = this.databaseManager.getNoteSpeakerEmbeddings(noteId);const existing = this.databaseManager.getSpeakerMappings(noteId);- const mappedSpeakers = new Set(existing.map(m => m.speaker_id));+ const mappedSpeakers = new Set(existing.map((m) => m.speaker_id));for (const emb of embeddings) {if (mappedSpeakers.has(emb.speaker_id)) continue;- const speakerEmb = new Float32Array(emb.embedding.buffer, emb.embedding.byteOffset, emb.embedding.byteLength / 4);+ const speakerEmb = new Float32Array(+ emb.embedding.buffer,+ emb.embedding.byteOffset,+ emb.embedding.byteLength / 4+ );const similarity = speakerEmbeddings.cosineSimilarity(profileEmb, speakerEmb);- if (similarity > 0.70) {- this.databaseManager.setSpeakerMapping(noteId, emb.speaker_id, profile.id, profile.display_name);+ if (similarity > 0.7) {+ this.databaseManager.setSpeakerMapping(+ noteId,+ emb.speaker_id,+ profile.id,+ profile.display_name+ );const note = this.databaseManager.getNote(noteId);if (note?.transcript) {@@ -5205,12 +5445,22 @@ class IPCHandlers {let changed = false;for (const seg of segments) {if (seg.speaker === emb.speaker_id && !seg.speakerName) {- seg.speakerName = profile.display_name;+ if (canAutoRelabelSpeaker(seg)) {+ applyConfirmedSpeaker(seg, {+ speakerName: profile.display_name,+ speakerIsPlaceholder: false,+ });+ } else {+ seg.speakerName = profile.display_name;+ seg.speakerIsPlaceholder = false;+ }changed = true;}}if (changed) {- this.databaseManager.updateNote(noteId, { transcript: JSON.stringify(segments) });+ this.databaseManager.updateNote(noteId, {+ transcript: JSON.stringify(segments),+ });}} catch (_) {}}@@ -5233,9 +5483,12 @@ class IPCHandlers {continue;}- segment.speakerName = displayName;- segment.suggestedName = undefined;- segment.suggestedProfileId = undefined;+ applyConfirmedSpeaker(segment, {+ speakerName: displayName,+ speakerIsPlaceholder: false,+ suggestedName: undefined,+ suggestedProfileId: undefined,+ });}}@@ -5302,10 +5555,20 @@ class IPCHandlers {if (liveMapping) {displayName = liveMapping.display_name || displayName;profileId = liveMapping.profile_id ?? profileId;- this.databaseManager.setSpeakerMapping(bestEntry.noteId, mappedId, profileId, displayName);+ this.databaseManager.setSpeakerMapping(+ bestEntry.noteId,+ mappedId,+ profileId,+ displayName+ );this.databaseManager.removeSpeakerMapping(bestEntry.noteId, bestEntry.speakerId);} else if (displayName) {- this.databaseManager.setSpeakerMapping(bestEntry.noteId, mappedId, profileId, displayName);+ this.databaseManager.setSpeakerMapping(+ bestEntry.noteId,+ mappedId,+ profileId,+ displayName+ );}}@@ -5323,7 +5586,12 @@ class IPCHandlers {};if (!this.diarizationManager?.isAvailable() || !rawPcmPath) {- send({ segments: [] });+ send({+ segments: transcriptSegments.map((segment, index) => ({+ ...segment,+ id: segment.id || `segment-${index}`,+ })),+ });return;}@@ -5333,8 +5601,21 @@ class IPCHandlers {let tmpWav = null;try {tmpWav = await this.diarizationManager.convertRawPcmToWav(rawPcmPath, 24000);+ const observedSpeakerIds = new Set(+ transcriptSegments+ .filter((segment) => segment.source === "system" && segment.speaker)+ .map((segment) => segment.speaker)+ );+ for (const speakerId of Object.keys(liveSpeakerState || {})) {+ observedSpeakerIds.add(speakerId);+ }- const diarizationSegments = await this.diarizationManager.diarize(tmpWav);+ const expectedSpeakerCount =+ observedSpeakerIds.size >= 2 ? Math.min(observedSpeakerIds.size, 4) : -1;+ const diarizationSegments = await this.diarizationManager.diarize(+ tmpWav,+ expectedSpeakerCount > 0 ? { numSpeakers: expectedSpeakerCount } : {}+ );const startMs = transcriptSegments[0]?.timestamp || 0;const isEpochMs = startMs > 1e9;@@ -5353,7 +5634,7 @@ class IPCHandlers {diarizationSegments);- const speakerSet = new Set(diarizationSegments.map(d => d.speaker));+ const speakerSet = new Set(diarizationSegments.map((d) => d.speaker));const speakerRenumber = new Map();let sIdx = 0;for (const sp of speakerSet) {@@ -5365,12 +5646,12 @@ class IPCHandlers {const speakerEmb = require("./speakerEmbeddings");try {if (speakerEmb.isAvailable() && tmpWav) {- const speakerIds = [...new Set(diarizationSegments.map(s => s.speaker))];+ const speakerIds = [...new Set(diarizationSegments.map((s) => s.speaker))];speakerEmbeddingsMap = {};for (const spk of speakerIds) {- const segs = diarizationSegments.filter(s => s.speaker === spk);- const sorted = segs.sort((a, b) => (b.end - b.start) - (a.end - a.start)).slice(0, 3);+ const segs = diarizationSegments.filter((s) => s.speaker === spk);+ const sorted = segs.sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, 3);const embeddings = [];for (const seg of sorted) {if (seg.end - seg.start < 1.5) continue;@@ -5412,7 +5693,11 @@ class IPCHandlers {let bestSim = 0;for (const profile of profiles) {- const profileEmb = new Float32Array(profile.embedding.buffer, profile.embedding.byteOffset, profile.embedding.byteLength / 4);+ const profileEmb = new Float32Array(+ profile.embedding.buffer,+ profile.embedding.byteOffset,+ profile.embedding.byteLength / 4+ );const sim = speakerEmb.cosineSimilarity(emb, profileEmb);if (sim > bestSim) {bestSim = sim;@@ -5420,17 +5705,27 @@ class IPCHandlers {}}- if (bestProfile && bestSim > 0.70) {+ if (bestProfile && bestSim > 0.7) {for (const seg of enrichedSegments) {if (seg.speaker === mappedId) {- seg.speakerName = bestProfile.display_name;+ applyConfirmedSpeaker(seg, {+ speakerName: bestProfile.display_name,+ speakerIsPlaceholder: false,+ suggestedName: undefined,+ suggestedProfileId: undefined,+ });}}} else if (bestProfile && bestSim > 0.55) {for (const seg of enrichedSegments) {if (seg.speaker === mappedId) {- seg.suggestedName = bestProfile.display_name;- seg.suggestedProfileId = bestProfile.id;+ if (isSpeakerLocked(seg)) {+ continue;+ }+ applySuggestedSpeaker(seg, {+ suggestedName: bestProfile.display_name,+ suggestedProfileId: bestProfile.id,+ });}}}@@ -5446,9 +5741,13 @@ class IPCHandlers {debugLogger.warn("Background diarization failed", { error: err.message });send({ segments: [] });} finally {- try { fs.unlinkSync(rawPcmPath); } catch (_) {}+ try {+ fs.unlinkSync(rawPcmPath);+ } catch (_) {}if (tmpWav) {- try { fs.unlinkSync(tmpWav); } catch (_) {}+ try {+ fs.unlinkSync(tmpWav);+ } catch (_) {}}}})();diff --git a/src/helpers/liveSpeakerIdentifier.js b/src/helpers/liveSpeakerIdentifier.jsindex bcd79578b..d0a507cfe 100644--- a/src/helpers/liveSpeakerIdentifier.js+++ b/src/helpers/liveSpeakerIdentifier.js@@ -7,10 +7,18 @@ const SAMPLE_RATE = 16000;const VAD_WINDOW_SIZE = 512;const MIN_SEGMENT_SECONDS = 0.8;const MIN_SEGMENT_SAMPLES = Math.round(SAMPLE_RATE * MIN_SEGMENT_SECONDS);+const LIVE_IDENTIFICATION_MIN_SECONDS = 1.6;+const LIVE_IDENTIFICATION_MIN_SAMPLES = Math.round(SAMPLE_RATE * LIVE_IDENTIFICATION_MIN_SECONDS);+const LIVE_IDENTIFICATION_INTERVAL_SECONDS = 1.0;+const LIVE_IDENTIFICATION_INTERVAL_SAMPLES = Math.round(+ SAMPLE_RATE * LIVE_IDENTIFICATION_INTERVAL_SECONDS+);const SPEECH_THRESHOLD = 0.15;const SILENCE_THRESHOLD = 0.08;const SILENCE_WINDOWS_TO_END = 4;-const MATCH_THRESHOLD = 0.7;+const MATCH_THRESHOLD = 0.82;+const MATCH_MARGIN = 0.04;+const LIVE_WINDOW_PADDING_SECONDS = 0.75;const DEFAULT_VAD_STATE_SHAPE = [2, 1, 64];function pcm16BufferToFloat32(buffer) {@@ -66,7 +74,9 @@ function normalizeVadShape(shape) {}function normalizeVadStateName(name) {- return String(name || "").replace(/[^a-z0-9]/gi, "").toLowerCase();+ return String(name || "")+ .replace(/[^a-z0-9]/gi, "")+ .toLowerCase();}function getBufferFloat32View(buffer) {@@ -94,7 +104,11 @@ class LiveSpeakerIdentifier {this.transientCounts = new Map();this.transientDisplayNames = new Map();this.transientProfileIds = new Map();+ this.transientNoteIds = new Map();this.nextLiveIndex = 0;+ this.currentSegmentSpeakerId = null;+ this.currentSegmentSpeakerName = null;+ this.lastLiveIdentificationSample = 0;this._diarizationManager = null;}@@ -106,12 +120,19 @@ class LiveSpeakerIdentifier {return this._diarizationManager?.isVadModelDownloaded() && speakerEmbeddings.isAvailable();}- getTransientMap() {- const map = new Map();+ getTransientState() {+ const state = {};+for (const [speakerId, embedding] of this.transientEmbeddings.entries()) {- map.set(speakerId, cloneFloat32Array(embedding));+ state[speakerId] = {+ embedding: Array.from(embedding),+ displayName: this.transientDisplayNames.get(speakerId) || null,+ profileId: this.transientProfileIds.get(speakerId) ?? null,+ noteId: this.transientNoteIds.get(speakerId) ?? null,+ };}- return map;++ return state;}getSpeakerEmbedding(speakerId) {@@ -119,11 +140,10 @@ class LiveSpeakerIdentifier {return embedding ? cloneFloat32Array(embedding) : null;}- async start(options = {}) {- const {- onSpeakerIdentified = null,- getSpeakerProfiles = null,- } = typeof options === "function" ? { onSpeakerIdentified: options } : options;+ async start(options = {}, extraOptions = {}) {+ const resolvedOptions =+ typeof options === "function" ? { onSpeakerIdentified: options, ...extraOptions } : options;+ const { onSpeakerIdentified = null, getSpeakerProfiles = null } = resolvedOptions;this.onSpeakerIdentified =typeof onSpeakerIdentified === "function" ? onSpeakerIdentified : null;@@ -156,11 +176,11 @@ class LiveSpeakerIdentifier {await this._finalizeSpeechSegment();}- const transientMap = this.getTransientMap();+ const transientState = this.getTransientState();this._resetMeetingState();this.onSpeakerIdentified = null;this.getSpeakerProfiles = null;- return transientMap;+ return transientState;}feedAudio(pcmBuffer) {@@ -177,7 +197,7 @@ class LiveSpeakerIdentifier {return this.queue;}- mapSpeaker(liveId, profileId, displayName) {+ mapSpeaker(liveId, profileId, displayName, noteId) {if (!liveId || !this.transientEmbeddings.has(liveId)) {return false;}@@ -190,6 +210,10 @@ class LiveSpeakerIdentifier {this.transientDisplayNames.set(liveId, displayName);}+ if (noteId != null) {+ this.transientNoteIds.set(liveId, noteId);+ }+return true;}@@ -203,9 +227,7 @@ class LiveSpeakerIdentifier {const ort = require("onnxruntime-node");this.session = await ort.InferenceSession.create(vadModelPath);- this.vadStateInputs = (this.session.inputNames || []).filter((name) =>- /state|h|c/i.test(name)- );+ this.vadStateInputs = (this.session.inputNames || []).filter((name) => /state|h|c/i.test(name));this.vadStateOutputs = (this.session.outputNames || []).filter((name) =>/state|h|c/i.test(name));@@ -225,7 +247,11 @@ class LiveSpeakerIdentifier {this.transientCounts = new Map();this.transientDisplayNames = new Map();this.transientProfileIds = new Map();+ this.transientNoteIds = new Map();this.nextLiveIndex = 0;+ this.currentSegmentSpeakerId = null;+ this.currentSegmentSpeakerName = null;+ this.lastLiveIdentificationSample = 0;this._resetVadRuntimeState();}@@ -275,6 +301,7 @@ class LiveSpeakerIdentifier {if (probability >= SILENCE_THRESHOLD) {this.silenceWindows = 0;+ await this._identifyActiveSpeechSegment();return;}@@ -294,6 +321,9 @@ class LiveSpeakerIdentifier {this.segmentEndSample = windowEndSample;this.speechChunks = [cloneFloat32Array(window)];this.silenceWindows = 0;+ this.currentSegmentSpeakerId = null;+ this.currentSegmentSpeakerName = null;+ this.lastLiveIdentificationSample = 0;}async _getVadProbability(window) {@@ -350,8 +380,8 @@ class LiveSpeakerIdentifier {for (const inputName of this.vadStateInputs) {const expectedName = normalizeVadStateName(inputName);- const matchingOutput = this.vadStateOutputs.find(- (outputName) => normalizeVadStateName(outputName).startsWith(expectedName)+ const matchingOutput = this.vadStateOutputs.find((outputName) =>+ normalizeVadStateName(outputName).startsWith(expectedName));const output = (matchingOutput && results[matchingOutput]) || results[inputName];@@ -361,6 +391,43 @@ class LiveSpeakerIdentifier {}}+ async _identifyActiveSpeechSegment(force = false) {+ const currentSamples = concatFloat32Arrays(this.speechChunks);+ if (currentSamples.length < LIVE_IDENTIFICATION_MIN_SAMPLES) {+ return;+ }++ if (+ !force &&+ this.lastLiveIdentificationSample > 0 &&+ this.segmentEndSample - this.lastLiveIdentificationSample <+ LIVE_IDENTIFICATION_INTERVAL_SAMPLES+ ) {+ return;+ }++ const embedding = await speakerEmbeddings.extractEmbeddingFromSamples(currentSamples);+ if (!embedding) {+ return;+ }++ const resolved = this._resolveSpeakerForEmbedding(embedding, { updateCentroid: false });+ if (!resolved?.speakerId) {+ return;+ }++ this.currentSegmentSpeakerId = resolved.speakerId;+ this.currentSegmentSpeakerName = resolved.displayName || null;+ this.lastLiveIdentificationSample = this.segmentEndSample;++ this.onSpeakerIdentified?.({+ speakerId: resolved.speakerId,+ displayName: resolved.displayName || null,+ startTime: Math.max(0, this.segmentStartSample / SAMPLE_RATE - LIVE_WINDOW_PADDING_SECONDS),+ endTime: this.segmentEndSample / SAMPLE_RATE + LIVE_WINDOW_PADDING_SECONDS,+ });+ }+async _finalizeSpeechSegment() {const samples = concatFloat32Arrays(this.speechChunks);this.speechChunks = [];@@ -376,47 +443,50 @@ class LiveSpeakerIdentifier {return;}- let speakerId = this._findTransientMatch(embedding);- if (speakerId) {- this._updateCentroid(speakerId, embedding);- } else {- const matchedProfile = this._findStoredProfileMatch(embedding);- if (matchedProfile) {- speakerId = this._findTransientSpeakerForProfile(matchedProfile.id);- if (!speakerId) {- speakerId = this._assignSpeakerId(embedding);- } else {- this._updateCentroid(speakerId, embedding);- }-- this.transientProfileIds.set(speakerId, matchedProfile.id);- this.transientDisplayNames.set(speakerId, matchedProfile.display_name);- } else {- speakerId = this._assignSpeakerId(embedding);- }+ const resolved = this._resolveSpeakerForEmbedding(embedding, { updateCentroid: true });+ if (!resolved?.speakerId) {+ return;}+ const speakerId = resolved.speakerId;+ const displayName =+ resolved.displayName ||+ this.currentSegmentSpeakerName ||+ this.transientDisplayNames.get(speakerId) ||+ null;+this.onSpeakerIdentified?.({speakerId,- displayName: this.transientDisplayNames.get(speakerId) || null,- startTime: Math.max(0, this.segmentStartSample / SAMPLE_RATE - 10),- endTime: this.segmentEndSample / SAMPLE_RATE + 10,+ displayName,+ startTime: Math.max(0, this.segmentStartSample / SAMPLE_RATE - LIVE_WINDOW_PADDING_SECONDS),+ endTime: this.segmentEndSample / SAMPLE_RATE + LIVE_WINDOW_PADDING_SECONDS,});++ this.currentSegmentSpeakerId = null;+ this.currentSegmentSpeakerName = null;+ this.lastLiveIdentificationSample = 0;}_findTransientMatch(embedding) {let bestSpeakerId = null;let bestSimilarity = 0;+ let secondBestSimilarity = 0;for (const [speakerId, centroid] of this.transientEmbeddings.entries()) {const similarity = speakerEmbeddings.cosineSimilarity(embedding, centroid);if (similarity > bestSimilarity) {+ secondBestSimilarity = bestSimilarity;bestSimilarity = similarity;bestSpeakerId = speakerId;+ } else if (similarity > secondBestSimilarity) {+ secondBestSimilarity = similarity;}}- return bestSimilarity >= MATCH_THRESHOLD ? bestSpeakerId : null;+ return bestSimilarity >= MATCH_THRESHOLD &&+ bestSimilarity - secondBestSimilarity >= MATCH_MARGIN+ ? bestSpeakerId+ : null;}_findStoredProfileMatch(embedding) {@@ -431,6 +501,7 @@ class LiveSpeakerIdentifier {let bestProfile = null;let bestSimilarity = 0;+ let secondBestSimilarity = 0;for (const profile of profiles) {if (!profile?.embedding) continue;@@ -446,12 +517,63 @@ class LiveSpeakerIdentifier {const similarity = speakerEmbeddings.cosineSimilarity(embedding, profileEmbedding);if (similarity > bestSimilarity) {+ secondBestSimilarity = bestSimilarity;bestSimilarity = similarity;bestProfile = profile;+ } else if (similarity > secondBestSimilarity) {+ secondBestSimilarity = similarity;}}- return bestSimilarity >= MATCH_THRESHOLD ? bestProfile : null;+ return bestSimilarity >= MATCH_THRESHOLD &&+ bestSimilarity - secondBestSimilarity >= MATCH_MARGIN+ ? bestProfile+ : null;+ }++ _resolveSpeakerForEmbedding(embedding, options = {}) {+ const { updateCentroid = false } = options;++ let speakerId = this.currentSegmentSpeakerId || this._findTransientMatch(embedding);+ let displayName = this.currentSegmentSpeakerName || null;++ if (speakerId) {+ if (updateCentroid) {+ this._updateCentroid(speakerId, embedding);+ }++ return {+ speakerId,+ displayName: displayName || this.transientDisplayNames.get(speakerId) || null,+ };+ }++ const matchedProfile = this._findStoredProfileMatch(embedding);+ if (matchedProfile) {+ speakerId = this._findTransientSpeakerForProfile(matchedProfile.id);+ if (!speakerId) {+ speakerId = this._assignSpeakerId(embedding);+ } else if (updateCentroid) {+ this._updateCentroid(speakerId, embedding);+ }++ this.transientProfileIds.set(speakerId, matchedProfile.id);+ this.transientDisplayNames.set(speakerId, matchedProfile.display_name);+ return {+ speakerId,+ displayName: matchedProfile.display_name,+ };+ }++ speakerId = this.currentSegmentSpeakerId || this._assignSpeakerId(embedding);+ if (updateCentroid && this.currentSegmentSpeakerId) {+ this._updateCentroid(speakerId, embedding);+ }++ return {+ speakerId,+ displayName: this.transientDisplayNames.get(speakerId) || null,+ };}_findTransientSpeakerForProfile(profileId) {diff --git a/src/helpers/meetingEchoLeakDetector.js b/src/helpers/meetingEchoLeakDetector.jsnew file mode 100644index 000000000..13059d4a3--- /dev/null+++ b/src/helpers/meetingEchoLeakDetector.js@@ -0,0 +1,388 @@+const SAMPLE_RATE = 24000;+const MAX_SYSTEM_HISTORY_MS = 4000;+const MAX_MIC_HISTORY_MS = 12000;+const MIN_RMS = 0.006;+const MIN_SYSTEM_RMS = 0.004;+const MAX_LAG_MS = 220;+const LAG_STEP_SAMPLES = 120;+const PARTIAL_WINDOW_MS = 450;+const FINAL_PADDING_MS = 250;+const CHUNK_MUTE_WINDOW_MS = 180;+const STRONG_BLEED_CORRELATION = 0.94;+const STRONG_BLEED_RESIDUAL = 0.18;+const STRONG_BLEED_EXPLAINED = 0.82;+const STRONG_BLEED_MIC_TO_SYSTEM_RATIO = 1.12;+const PARTIAL_BLEED_CORRELATION = 0.9;+const PARTIAL_BLEED_RESIDUAL = 0.22;+const PARTIAL_BLEED_EXPLAINED = 0.78;+const FINAL_BLEED_CORRELATION = 0.88;+const FINAL_BLEED_RESIDUAL = 0.24;+const FINAL_BLEED_EXPLAINED = 0.74;+const FINAL_BLEED_MIC_TO_SYSTEM_RATIO = 1.18;+const DOUBLE_TALK_CORRELATION = 0.45;+const DOUBLE_TALK_EXPLAINED = 0.3;+const DOUBLE_TALK_RESIDUAL = 0.2;+const DOUBLE_TALK_MIC_TO_SYSTEM_RATIO = 1.16;++function pcm16BufferToFloat32(buffer) {+ const input = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.length / 2);+ const output = new Float32Array(input.length);++ for (let i = 0; i < input.length; i += 1) {+ output[i] = input[i] / 32768;+ }++ return output;+}++function computeRms(samples) {+ if (!samples.length) {+ return 0;+ }++ let sumSq = 0;+ for (let i = 0; i < samples.length; i += 1) {+ sumSq += samples[i] * samples[i];+ }++ return Math.sqrt(sumSq / samples.length);+}++class MeetingEchoLeakDetector {+ constructor() {+ this.systemHistory = [];+ this.micHistory = [];+ }++ reset() {+ this.systemHistory = [];+ this.micHistory = [];+ }++ recordSystemChunk(buffer, timestampMs = Date.now()) {+ if (!buffer?.length) {+ return;+ }++ const samples = pcm16BufferToFloat32(buffer);+ if (!samples.length) {+ return;+ }++ this.systemHistory.push({+ timestampMs,+ samples,+ durationMs: (samples.length / SAMPLE_RATE) * 1000,+ rms: computeRms(samples),+ });++ this._trimHistory(timestampMs);+ }++ analyzeMicChunk(buffer, timestampMs = Date.now()) {+ if (!buffer?.length) {+ return null;+ }++ const samples = pcm16BufferToFloat32(buffer);+ if (!samples.length) {+ return null;+ }++ const rms = computeRms(samples);+ const analysis = {+ timestampMs,+ durationMs: (samples.length / SAMPLE_RATE) * 1000,+ rms,+ correlation: 0,+ residualRatio: 1,+ explainedRatio: 0,+ systemRms: 0,+ micToSystemRatio: null,+ state: "clean_local",+ shouldMute: false,+ };++ if (rms < MIN_RMS) {+ this.micHistory.push(analysis);+ this._trimHistory(timestampMs);+ return analysis;+ }++ const systemWindow = this._getSystemWindow();+ if (systemWindow.length < samples.length + this._maxLagSamples()) {+ this.micHistory.push(analysis);+ this._trimHistory(timestampMs);+ return analysis;+ }++ const energyMic = this._computeEnergy(samples);+ let bestCorr = 0;+ let bestResidualRatio = 1;+ let bestExplainedRatio = 0;+ let bestSystemRms = 0;++ for (let lag = 0; lag <= this._maxLagSamples(); lag += LAG_STEP_SAMPLES) {+ const start = systemWindow.length - samples.length - lag;+ if (start < 0) {+ break;+ }++ const candidate = systemWindow.subarray(start, start + samples.length);+ const energySystem = this._computeEnergy(candidate);+ if (energySystem <= 0) {+ continue;+ }++ let dot = 0;+ for (let i = 0; i < samples.length; i += 1) {+ dot += samples[i] * candidate[i];+ }++ const corr = dot / Math.sqrt(energyMic * energySystem);+ if (corr <= bestCorr) {+ continue;+ }++ const alpha = dot / energySystem;+ let residualEnergy = 0;+ for (let i = 0; i < samples.length; i += 1) {+ const residual = samples[i] - alpha * candidate[i];+ residualEnergy += residual * residual;+ }++ const explainedRatio = Math.max(0, Math.min(1, 1 - residualEnergy / energyMic));+ bestCorr = corr;+ bestResidualRatio = residualEnergy / energyMic;+ bestExplainedRatio = explainedRatio;+ bestSystemRms = Math.sqrt(energySystem / candidate.length);+ }++ analysis.correlation = bestCorr;+ analysis.residualRatio = bestResidualRatio;+ analysis.explainedRatio = bestExplainedRatio;+ analysis.systemRms = bestSystemRms;+ analysis.micToSystemRatio = bestSystemRms > 0 ? rms / bestSystemRms : null;+ analysis.state = this._resolveState(analysis);++ this.micHistory.push(analysis);+ this._trimHistory(timestampMs);+ analysis.shouldMute = this.shouldMuteMicChunk(analysis, timestampMs);+ return analysis;+ }++ isMicProbablyRenderBleed(nowMs = Date.now()) {+ const recent = this.micHistory.filter(+ (entry) => nowMs - entry.timestampMs <= PARTIAL_WINDOW_MS && entry.rms >= MIN_RMS+ );++ if (recent.length < 3) {+ return false;+ }++ if (recent.some((entry) => entry.state === "double_talk")) {+ return false;+ }++ const suspectedCount = recent.filter(+ (entry) => entry.state === "suspected_render_bleed"+ ).length;+ if (suspectedCount < Math.ceil(recent.length * 0.8)) {+ return false;+ }++ const suspected = recent.filter((entry) => entry.state === "suspected_render_bleed");+ const averageCorrelation =+ suspected.reduce((sum, entry) => sum + entry.correlation, 0) / suspected.length;+ const averageResidual =+ suspected.reduce((sum, entry) => sum + entry.residualRatio, 0) / suspected.length;+ const averageExplained =+ suspected.reduce((sum, entry) => sum + entry.explainedRatio, 0) / suspected.length;++ return (+ averageCorrelation >= PARTIAL_BLEED_CORRELATION &&+ averageResidual <= PARTIAL_BLEED_RESIDUAL &&+ averageExplained >= PARTIAL_BLEED_EXPLAINED+ );+ }++ shouldSuppressMicSegment(startedAtMs, endedAtMs = Date.now()) {+ if (!startedAtMs) {+ return { suppress: false, reason: "missing_start" };+ }++ const windowStart = startedAtMs - FINAL_PADDING_MS;+ const windowEnd = endedAtMs + FINAL_PADDING_MS;+ const relevant = this.micHistory.filter(+ (entry) =>+ entry.timestampMs + entry.durationMs >= windowStart && entry.timestampMs <= windowEnd+ );++ if (relevant.length < 2) {+ return { suppress: false, reason: "insufficient_signal" };+ }++ const suspected = relevant.filter((entry) => entry.state === "suspected_render_bleed");+ const doubleTalk = relevant.filter((entry) => entry.state === "double_talk");++ const averageCorrelation =+ suspected.length > 0+ ? suspected.reduce((sum, entry) => sum + entry.correlation, 0) / suspected.length+ : 0;+ const averageResidual =+ suspected.length > 0+ ? suspected.reduce((sum, entry) => sum + entry.residualRatio, 0) / suspected.length+ : 1;+ const averageExplained =+ suspected.length > 0+ ? suspected.reduce((sum, entry) => sum + entry.explainedRatio, 0) / suspected.length+ : 0;+ const averageMicToSystemRatio =+ suspected.length > 0+ ? suspected.reduce((sum, entry) => sum + (entry.micToSystemRatio || 0), 0) /+ suspected.length+ : null;+ const suspectedShare = suspected.length / relevant.length;+ const likelyRenderBleed =+ suspected.length > 0 &&+ suspectedShare >= 0.5 &&+ averageCorrelation >= 0.84 &&+ averageResidual <= 0.32 &&+ averageExplained >= 0.68;++ if (doubleTalk.length > 0) {+ return {+ suppress: false,+ reason: "double_talk",+ likelyRenderBleed,+ averageCorrelation,+ averageResidual,+ averageExplained,+ averageMicToSystemRatio,+ sampleCount: relevant.length,+ };+ }++ if (suspectedShare < 0.75) {+ return {+ suppress: false,+ reason: "mixed_signal",+ likelyRenderBleed,+ averageCorrelation,+ averageResidual,+ averageExplained,+ averageMicToSystemRatio,+ sampleCount: relevant.length,+ };+ }++ const suppress =+ averageCorrelation >= FINAL_BLEED_CORRELATION &&+ averageResidual <= FINAL_BLEED_RESIDUAL &&+ averageExplained >= FINAL_BLEED_EXPLAINED &&+ (averageMicToSystemRatio == null ||+ averageMicToSystemRatio <= FINAL_BLEED_MIC_TO_SYSTEM_RATIO);++ return {+ suppress,+ likelyRenderBleed,+ reason: suppress ? "render_bleed" : "weak_match",+ averageCorrelation,+ averageResidual,+ averageExplained,+ averageMicToSystemRatio,+ sampleCount: relevant.length,+ };+ }++ shouldMuteMicChunk(analysis, nowMs = Date.now()) {+ if (!analysis || analysis.state !== "suspected_render_bleed") {+ return false;+ }++ const recent = this.micHistory.filter(+ (entry) => nowMs - entry.timestampMs <= CHUNK_MUTE_WINDOW_MS && entry.rms >= MIN_RMS+ );++ if (recent.some((entry) => entry.state === "double_talk")) {+ return false;+ }++ return (+ analysis.correlation >= STRONG_BLEED_CORRELATION &&+ analysis.residualRatio <= STRONG_BLEED_RESIDUAL &&+ analysis.explainedRatio >= STRONG_BLEED_EXPLAINED &&+ (analysis.micToSystemRatio == null ||+ analysis.micToSystemRatio <= STRONG_BLEED_MIC_TO_SYSTEM_RATIO)+ );+ }++ _resolveState(analysis) {+ const { correlation, residualRatio, explainedRatio, rms, systemRms, micToSystemRatio } =+ analysis;++ if (rms < MIN_RMS || systemRms < MIN_SYSTEM_RMS) {+ return "clean_local";+ }++ if (+ correlation >= 0.9 &&+ residualRatio <= 0.26 &&+ explainedRatio >= 0.72 &&+ (micToSystemRatio == null || micToSystemRatio <= 1.2)+ ) {+ return "suspected_render_bleed";+ }++ if (+ correlation >= DOUBLE_TALK_CORRELATION &&+ explainedRatio >= DOUBLE_TALK_EXPLAINED &&+ (residualRatio >= DOUBLE_TALK_RESIDUAL ||+ (micToSystemRatio != null && micToSystemRatio >= DOUBLE_TALK_MIC_TO_SYSTEM_RATIO))+ ) {+ return "double_talk";+ }++ return "clean_local";+ }++ _trimHistory(nowMs) {+ const systemCutoff = nowMs - MAX_SYSTEM_HISTORY_MS;+ const micCutoff = nowMs - MAX_MIC_HISTORY_MS;++ while (this.systemHistory.length > 0 && this.systemHistory[0].timestampMs < systemCutoff) {+ this.systemHistory.shift();+ }++ while (this.micHistory.length > 0 && this.micHistory[0].timestampMs < micCutoff) {+ this.micHistory.shift();+ }+ }++ _getSystemWindow() {+ const totalLength = this.systemHistory.reduce((sum, entry) => sum + entry.samples.length, 0);+ const merged = new Float32Array(totalLength);+ let offset = 0;++ for (const entry of this.systemHistory) {+ merged.set(entry.samples, offset);+ offset += entry.samples.length;+ }++ return merged;+ }++ _computeEnergy(samples) {+ let sumSq = 0;+ for (let i = 0; i < samples.length; i += 1) {+ sumSq += samples[i] * samples[i];+ }+ return sumSq;+ }++ _maxLagSamples() {+ return Math.round((MAX_LAG_MS / 1000) * SAMPLE_RATE);+ }+}++module.exports = MeetingEchoLeakDetector;diff --git a/src/helpers/speakerAssignmentPolicy.js b/src/helpers/speakerAssignmentPolicy.jsnew file mode 100644index 000000000..281fc200f--- /dev/null+++ b/src/helpers/speakerAssignmentPolicy.js@@ -0,0 +1,76 @@+const SPEAKER_STATUS = Object.freeze({+ PROVISIONAL: "provisional",+ CONFIRMED: "confirmed",+ SUGGESTED: "suggested",+ LOCKED: "locked",+});++function canonicalizeSpeakerStatus(status, segment = null) {+ if (segment?.speakerLocked || segment?.speakerLockSource === "user") {+ return SPEAKER_STATUS.LOCKED;+ }++ switch (status) {+ case SPEAKER_STATUS.PROVISIONAL:+ case SPEAKER_STATUS.CONFIRMED:+ case SPEAKER_STATUS.SUGGESTED:+ case SPEAKER_STATUS.LOCKED:+ return status;+ case "user_locked":+ return SPEAKER_STATUS.LOCKED;+ case "suggested_profile":+ return SPEAKER_STATUS.SUGGESTED;+ case "uncertain_overlap":+ return SPEAKER_STATUS.PROVISIONAL;+ default:+ return undefined;+ }+}++function isSpeakerLocked(segment) {+ return canonicalizeSpeakerStatus(segment?.speakerStatus, segment) === SPEAKER_STATUS.LOCKED;+}++function canAutoRelabelSpeaker(segment) {+ return !isSpeakerLocked(segment);+}++function applySpeakerUpdate(segment, patch, status) {+ if (isSpeakerLocked(segment)) {+ segment.speakerStatus = SPEAKER_STATUS.LOCKED;+ segment.speakerLocked = true;+ segment.speakerLockSource = segment.speakerLockSource || "user";+ return segment;+ }++ Object.assign(segment, patch);++ segment.speakerStatus = status;+ return segment;+}++function applyProvisionalSpeaker(segment, patch = {}) {+ return applySpeakerUpdate(segment, patch, SPEAKER_STATUS.PROVISIONAL);+}++function applyConfirmedSpeaker(segment, patch = {}) {+ return applySpeakerUpdate(segment, patch, SPEAKER_STATUS.CONFIRMED);+}++function applySuggestedSpeaker(segment, patch = {}) {+ if (isSpeakerLocked(segment)) {+ return segment;+ }++ return applySpeakerUpdate(segment, patch, SPEAKER_STATUS.SUGGESTED);+}++module.exports = {+ SPEAKER_STATUS,+ canonicalizeSpeakerStatus,+ isSpeakerLocked,+ canAutoRelabelSpeaker,+ applyProvisionalSpeaker,+ applyConfirmedSpeaker,+ applySuggestedSpeaker,+};diff --git a/src/hooks/useMeetingTranscription.ts b/src/hooks/useMeetingTranscription.tsindex 36125e807..999dc57fb 100644--- a/src/hooks/useMeetingTranscription.ts+++ b/src/hooks/useMeetingTranscription.ts@@ -2,6 +2,11 @@ import { useState, useEffect, useRef, useCallback } from "react";import { getSettings } from "../stores/settingsStore";import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";import logger from "../utils/logger";+import {+ normalizeTranscriptSegment,+ type TranscriptSpeakerLockSource,+ type TranscriptSpeakerStatus,+} from "../utils/transcriptSpeakerState";export interface TranscriptSegment {id: string;@@ -10,8 +15,26 @@ export interface TranscriptSegment {timestamp?: number;speaker?: string;speakerName?: string;+ speakerIsPlaceholder?: boolean;suggestedName?: string;suggestedProfileId?: number;+ speakerStatus?: TranscriptSpeakerStatus;+ speakerLocked?: boolean;+ speakerLockSource?: TranscriptSpeakerLockSource;+}++interface SpeakerIdentification {+ speakerId: string;+ displayName?: string | null;+ startTime: number;+ endTime: number;+}++interface RecentSystemSpeaker {+ speakerId: string;+ speakerName: string | null;+ speakerIsPlaceholder: boolean;+ updatedAt: number;}interface UseMeetingTranscriptionReturn {@@ -21,18 +44,53 @@ interface UseMeetingTranscriptionReturn {segments: TranscriptSegment[];micPartial: string;systemPartial: string;+ systemPartialSpeakerId: string | null;+ systemPartialSpeakerName: string | null;error: string | null;diarizationSessionId: string | null;prepareTranscription: () => Promise<void>;- startTranscription: () => Promise<void>;+ startTranscription: (_options?: { allowSystemAudio?: boolean }) => Promise<void>;stopTranscription: () => Promise<void>;}const MEETING_AUDIO_BUFFER_SIZE = 800;const MEETING_STOP_FLUSH_TIMEOUT_MS = 50;+const MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS = {+ echoCancellation: true,+ noiseSuppression: false,+ autoGainControl: false,+} as const;+const MEETING_MIC_FALLBACK_AUDIO_CONSTRAINTS = {+ echoCancellation: false,+ noiseSuppression: false,+ autoGainControl: false,+} as const;const REALTIME_MODELS = new Set(["gpt-4o-mini-transcribe", "gpt-4o-transcribe"]);const SPEAKER_IDENTIFICATION_RETENTION_MS = 30_000;+const SYSTEM_SPEAKER_CARRY_FORWARD_MS = 2_500;++const getSpeakerNumericIndex = (speakerId?: string): number | null => {+ if (!speakerId) {+ return null;+ }++ const match = speakerId.match(/speaker_(\d+)/);+ return match ? Number(match[1]) : null;+};++const isSegmentWithinIdentificationWindow = (+ segment: TranscriptSegment,+ identification: SpeakerIdentification+) => {+ if (segment.source !== "system" || segment.timestamp == null) {+ return false;+ }++ return (+ segment.timestamp >= identification.startTime && segment.timestamp <= identification.endTime+ );+};const getMeetingTranscriptionOptions = () => {const {@@ -115,11 +173,6 @@ registerProcessor("meeting-pcm-processor", MeetingPCMProcessor);const getMeetingMicConstraints = async (): Promise<MediaStreamConstraints> => {const { preferBuiltInMic, selectedMicDeviceId } = getSettings();- const micProcessing = {- echoCancellation: true,- noiseSuppression: false,- autoGainControl: false,- };if (preferBuiltInMic) {try {@@ -132,7 +185,7 @@ const getMeetingMicConstraints = async (): Promise<MediaStreamConstraints> => {return {audio: {deviceId: { exact: builtInMic.deviceId },- ...micProcessing,+ ...MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,},};}@@ -149,23 +202,25 @@ const getMeetingMicConstraints = async (): Promise<MediaStreamConstraints> => {return {audio: {deviceId: { exact: selectedMicDeviceId },- ...micProcessing,+ ...MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS,},};}- return { audio: micProcessing };+ return { audio: MEETING_MIC_PRIMARY_AUDIO_CONSTRAINTS };};+const getFallbackMeetingMicConstraints = (): MediaStreamConstraints => ({+ audio: MEETING_MIC_FALLBACK_AUDIO_CONSTRAINTS,+});+const createAudioPipeline = async ({stream,context,- label,onChunk,}: {stream: MediaStream;context: AudioContext;- label: string;onChunk: (chunk: ArrayBuffer) => void;}) => {if (context.state === "suspended") {@@ -176,33 +231,18 @@ const createAudioPipeline = async ({const source = context.createMediaStreamSource(stream);const processor = new AudioWorkletNode(context, "meeting-pcm-processor");- let chunkCount = 0;+ const silentGain = context.createGain();+ silentGain.gain.value = 0;processor.port.onmessage = (event) => {const chunk = event.data;if (!(chunk instanceof ArrayBuffer)) return;-- if (chunkCount < 10 || chunkCount % 50 === 0) {- const samples = new Int16Array(chunk);- let maxAmplitude = 0;- for (let i = 0; i < samples.length; i++) {- const normalized = Math.abs(samples[i]) / 0x7fff;- if (normalized > maxAmplitude) maxAmplitude = normalized;- }-- logger.debug(- `${label} audio chunk`,- { maxAmplitude: maxAmplitude.toFixed(6), samples: samples.length },- "meeting"- );- }-- chunkCount++;onChunk(chunk);};source.connect(processor);- processor.connect(context.destination);+ processor.connect(silentGain);+ silentGain.connect(context.destination);return { source, processor };};@@ -244,6 +284,8 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {const [segments, setSegments] = useState<TranscriptSegment[]>([]);const [micPartial, setMicPartial] = useState("");const [systemPartial, setSystemPartial] = useState("");+ const [systemPartialSpeakerId, setSystemPartialSpeakerId] = useState<string | null>(null);+ const [systemPartialSpeakerName, setSystemPartialSpeakerName] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [diarizationSessionId, setDiarizationSessionId] = useState<string | null>(null);@@ -254,33 +296,152 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {const isRecordingRef = useRef(false);const isStartingRef = useRef(false);const isPreparedRef = useRef(false);+ const segmentsRef = useRef<TranscriptSegment[]>([]);const preparePromiseRef = useRef<Promise<void> | null>(null);const ipcCleanupsRef = useRef<Array<() => void>>([]);const pendingCleanupRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const speakerIdentificationsRef = useRef<- Array<{ speakerId: string; displayName?: string; startTime: number; endTime: number }>- >([]);- const meetingStartTimeRef = useRef<number>(0);- const lastSpeakerRef = useRef<{ speakerId: string; displayName?: string } | null>(null);+ const speakerIdentificationsRef = useRef<SpeakerIdentification[]>([]);+ const nextPlaceholderSpeakerIndexRef = useRef(0);+ const systemPartialSpeakerIdRef = useRef<string | null>(null);+ const recentSystemSpeakerRef = useRef<RecentSystemSpeaker | null>(null);++ const setSystemPartialSpeakerIdentity = useCallback(+ (speakerId: string | null, speakerName: string | null) => {+ systemPartialSpeakerIdRef.current = speakerId;+ setSystemPartialSpeakerId(speakerId);+ setSystemPartialSpeakerName(speakerName);+ },+ []+ );const applySpeakerIdentification = useCallback(- (- segment: TranscriptSegment,- identification: { speakerId: string; displayName?: string; startTime: number; endTime: number }- ): TranscriptSegment => {- if (segment.source !== "system" || segment.speaker) {+ (segment: TranscriptSegment, identification: SpeakerIdentification): TranscriptSegment => {+ if (+ segment.source !== "system" ||+ !isSegmentWithinIdentificationWindow(segment, identification) ||+ (segment.speaker &&+ !segment.speakerIsPlaceholder &&+ segment.speakerStatus !== "provisional") ||+ segment.speakerLocked+ ) {return segment;}- return {+ return normalizeTranscriptSegment({...segment,speaker: identification.speakerId,speakerName: identification.displayName ?? segment.speakerName,- };+ speakerIsPlaceholder: false,+ speakerStatus: "confirmed",+ });+ },+ []+ );++ const rememberSystemSpeaker = useCallback(+ (+ speakerId: string | null,+ speakerName: string | null,+ speakerIsPlaceholder: boolean,+ updatedAt = Date.now()+ ) => {+ recentSystemSpeakerRef.current = speakerId+ ? {+ speakerId,+ speakerName,+ speakerIsPlaceholder,+ updatedAt,+ }+ : null;},[]);+ const getRecentSystemSpeaker = useCallback((nowMs: number) => {+ const candidate = recentSystemSpeakerRef.current;+ if (!candidate) {+ return null;+ }++ return nowMs - candidate.updatedAt <= SYSTEM_SPEAKER_CARRY_FORWARD_MS ? candidate : null;+ }, []);++ const reserveSpeakerIndex = useCallback((speakerId?: string) => {+ const idx = getSpeakerNumericIndex(speakerId);+ if (idx == null) {+ return;+ }++ nextPlaceholderSpeakerIndexRef.current = Math.max(+ nextPlaceholderSpeakerIndexRef.current,+ idx + 1+ );+ }, []);++ const assignProvisionalSpeaker = useCallback(+ (segment: TranscriptSegment) => {+ if (segment.source !== "system" || segment.speaker) {+ return segment;+ }++ const nowMs = segment.timestamp ?? Date.now();+ const partialSpeakerId = systemPartialSpeakerIdRef.current;+ if (partialSpeakerId) {+ reserveSpeakerIndex(partialSpeakerId);+ return normalizeTranscriptSegment({+ ...segment,+ speaker: partialSpeakerId,+ speakerIsPlaceholder: true,+ speakerStatus: "provisional",+ });+ }++ const recentSystemSpeaker = getRecentSystemSpeaker(nowMs);+ if (recentSystemSpeaker?.speakerId) {+ reserveSpeakerIndex(recentSystemSpeaker.speakerId);+ return normalizeTranscriptSegment({+ ...segment,+ speaker: recentSystemSpeaker.speakerId,+ speakerName: recentSystemSpeaker.speakerName ?? undefined,+ speakerIsPlaceholder: recentSystemSpeaker.speakerIsPlaceholder,+ speakerStatus: "provisional",+ });+ }++ const previousSystemSegment = [...segmentsRef.current]+ .reverse()+ .find(+ (candidate) =>+ candidate.source === "system" &&+ candidate.speaker &&+ candidate.timestamp != null &&+ nowMs - candidate.timestamp <= SYSTEM_SPEAKER_CARRY_FORWARD_MS+ );++ if (previousSystemSegment?.speaker && previousSystemSegment.speakerIsPlaceholder) {+ reserveSpeakerIndex(previousSystemSegment.speaker);+ return normalizeTranscriptSegment({+ ...segment,+ speaker: previousSystemSegment.speaker,+ speakerName: previousSystemSegment.speakerName,+ speakerIsPlaceholder: true,+ speakerStatus: "provisional",+ });+ }++ const speakerId = `speaker_${nextPlaceholderSpeakerIndexRef.current}`;+ nextPlaceholderSpeakerIndexRef.current += 1;++ return normalizeTranscriptSegment({+ ...segment,+ speaker: speakerId,+ speakerIsPlaceholder: true,+ speakerStatus: "provisional",+ });+ },+ [getRecentSystemSpeaker, reserveSpeakerIndex]+ );+const cleanup = useCallback(async () => {await flushAndDisconnectProcessor(micProcessorRef.current);micProcessorRef.current = null;@@ -308,7 +469,6 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {const stopTranscription = useCallback(async () => {if (!isRecordingRef.current) return;- // Signal stop immediately so in-flight startTranscription can abortisRecordingRef.current = false;isStartingRef.current = false;setIsRecording(false);@@ -339,7 +499,7 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {const prepareTranscription = useCallback(async () => {if (isPreparedRef.current || isRecordingRef.current || isStartingRef.current) return;- if (preparePromiseRef.current) return; // already preparing+ if (preparePromiseRef.current) return;logger.info("Meeting transcription preparing (pre-warming WebSockets)...", {}, "meeting");@@ -374,265 +534,301 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {await promise;}, []);- const startTranscription = useCallback(async () => {- if (isRecordingRef.current || isStartingRef.current) return;- isStartingRef.current = true;-- logger.info("Meeting transcription starting...", {}, "meeting");- setTranscript("");- setPartialTranscript("");- setSegments([]);- setMicPartial("");- setSystemPartial("");- setError(null);- speakerIdentificationsRef.current = [];- lastSpeakerRef.current = null;- meetingStartTimeRef.current = Date.now();-- // Set recording state immediately for instant UI feedback- isRecordingRef.current = true;- setIsRecording(true);-- // Wait for in-flight prepare to reuse the warm connection- if (preparePromiseRef.current) {- logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");- await preparePromiseRef.current;- }-- try {- const startTime = performance.now();-- const [startResult, micResult] = await Promise.all([- window.electronAPI?.meetingTranscriptionStart?.(getMeetingTranscriptionOptions()),- getMeetingMicConstraints().then((constraints) =>- navigator.mediaDevices.getUserMedia(constraints).catch((err) => {- logger.error(- "Mic capture failed, continuing with system audio only",- { error: (err as Error).message },- "meeting"- );- return null;- })- ),- ]);-- const streamsMs = performance.now() - startTime;- // Abort if stop was called during setup- if (!isRecordingRef.current) {- logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");- micResult?.getTracks().forEach((t) => t.stop());- isStartingRef.current = false;- return;+ const startTranscription = useCallback(+ async (_options?: { allowSystemAudio?: boolean }) => {+ if (isRecordingRef.current || isStartingRef.current) return;+ isStartingRef.current = true;++ logger.info("Meeting transcription starting...", {}, "meeting");+ setTranscript("");+ setPartialTranscript("");+ setSegments([]);+ segmentsRef.current = [];+ setMicPartial("");+ setSystemPartial("");+ setSystemPartialSpeakerIdentity(null, null);+ setError(null);+ speakerIdentificationsRef.current = [];+ nextPlaceholderSpeakerIndexRef.current = 0;+ recentSystemSpeakerRef.current = null;++ isRecordingRef.current = true;+ setIsRecording(true);++ if (preparePromiseRef.current) {+ logger.debug("Waiting for in-flight prepare to finish...", {}, "meeting");+ await preparePromiseRef.current;}- if (!startResult?.success) {- logger.error(- "Meeting transcription IPC start failed",- { error: startResult?.error },- "meeting"- );- setError(startResult?.error || "Failed to start meeting transcription");- micResult?.getTracks().forEach((track) => track.stop());- isRecordingRef.current = false;- isStartingRef.current = false;- setIsRecording(false);- return;- }+ try {+ const startTime = performance.now();++ const [startResult, micResult] = await Promise.all([+ window.electronAPI?.meetingTranscriptionStart?.(getMeetingTranscriptionOptions()),+ getMeetingMicConstraints().then(async (constraints) => {+ try {+ return await navigator.mediaDevices.getUserMedia(constraints);+ } catch (err) {+ logger.error(+ "Meeting mic capture failed with preferred constraints",+ { error: (err as Error).message, constraints },+ "meeting"+ );++ try {+ const fallbackConstraints = getFallbackMeetingMicConstraints();+ const fallbackStream =+ await navigator.mediaDevices.getUserMedia(fallbackConstraints);+ logger.info(+ "Meeting mic capture recovered with fallback constraints",+ { fallbackConstraints },+ "meeting"+ );+ return fallbackStream;+ } catch (fallbackErr) {+ logger.error(+ "Mic capture failed, continuing with system audio only",+ { error: (fallbackErr as Error).message },+ "meeting"+ );+ return null;+ }+ }+ }),+ ]);++ const streamsMs = performance.now() - startTime;+ if (!isRecordingRef.current) {+ logger.info("Meeting transcription aborted during setup (stop called)", {}, "meeting");+ micResult?.getTracks().forEach((t) => t.stop());+ isStartingRef.current = false;+ return;+ }- const systemAudioMode = startResult.systemAudioMode || "unsupported";+ if (!startResult?.success) {+ logger.error(+ "Meeting transcription IPC start failed",+ { error: startResult?.error },+ "meeting"+ );+ setError(startResult?.error || "Failed to start meeting transcription");+ micResult?.getTracks().forEach((track) => track.stop());+ isRecordingRef.current = false;+ isStartingRef.current = false;+ setIsRecording(false);+ return;+ }- if (!micResult && systemAudioMode !== "native") {- logger.error("Meeting transcription has no available audio source", {}, "meeting");- setError(- "No microphone is available and system audio capture is unsupported on this device."- );- await window.electronAPI?.meetingTranscriptionStop?.();- isRecordingRef.current = false;- isStartingRef.current = false;- setIsRecording(false);- return;- }+ const systemAudioMode = startResult.systemAudioMode || "unsupported";- const partialSetters = { mic: setMicPartial, system: setSystemPartial };-- const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(- (data: {- text: string;- source: "mic" | "system";- type: "partial" | "final";- timestamp?: number;- }) => {- logger.debug(- "Meeting segment received in renderer",- {- source: data.source,- type: data.type,- text: data.text?.slice(0, 80),- },- "meeting"+ if (!micResult && systemAudioMode === "native") {+ setError("Microphone capture failed. Continuing with system audio only.");+ }++ if (!micResult && systemAudioMode !== "native") {+ logger.error("Meeting transcription has no available audio source", {}, "meeting");+ setError(+ "No microphone is available and system audio capture is unsupported on this device.");- const setPartialForSource = partialSetters[data.source];-- if (data.type === "partial") {- setPartialForSource(data.text);- setPartialTranscript(data.text);- } else {- let rawSegment: TranscriptSegment = {- id: `seg-${++segmentCounter}`,- text: data.text,- source: data.source,- timestamp: data.timestamp,- };- if (rawSegment.source === "system" && !rawSegment.speaker && lastSpeakerRef.current) {- rawSegment = {- ...rawSegment,- speaker: lastSpeakerRef.current.speakerId,- speakerName: lastSpeakerRef.current.displayName,- };+ await window.electronAPI?.meetingTranscriptionStop?.();+ isRecordingRef.current = false;+ isStartingRef.current = false;+ setIsRecording(false);+ return;+ }++ const partialSetters = { mic: setMicPartial, system: setSystemPartial };++ const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(+ (data: {+ text: string;+ source: "mic" | "system";+ type: "partial" | "final";+ timestamp?: number;+ }) => {+ const setPartialForSource = partialSetters[data.source];++ if (data.type === "partial") {+ setPartialForSource(data.text);+ setPartialTranscript(data.text);+ if (data.source === "system" && !systemPartialSpeakerIdRef.current) {+ const speakerId = `speaker_${nextPlaceholderSpeakerIndexRef.current}`;+ nextPlaceholderSpeakerIndexRef.current += 1;+ setSystemPartialSpeakerIdentity(speakerId, null);+ }+ } else {+ let rawSegment: TranscriptSegment = normalizeTranscriptSegment({+ id: `seg-${++segmentCounter}`,+ text: data.text,+ source: data.source,+ timestamp: data.timestamp,+ });++ for (let i = speakerIdentificationsRef.current.length - 1; i >= 0; i -= 1) {+ rawSegment = applySpeakerIdentification(+ rawSegment,+ speakerIdentificationsRef.current[i]+ );+ }++ const seg = assignProvisionalSpeaker(rawSegment);+ reserveSpeakerIndex(seg.speaker);+ setSegments((prev) => {+ const ts = seg.timestamp ?? Infinity;+ let i = prev.length;+ while (i > 0 && (prev[i - 1].timestamp ?? 0) > ts) i--;+ const next =+ i === prev.length ? [...prev, seg] : [...prev.slice(0, i), seg, ...prev.slice(i)];+ segmentsRef.current = next;+ return next;+ });+ if (data.source === "system" && seg.speaker) {+ rememberSystemSpeaker(+ seg.speaker,+ seg.speakerName ?? null,+ !!seg.speakerIsPlaceholder,+ seg.timestamp ?? Date.now()+ );+ }+ setPartialForSource("");+ if (data.source === "system") {+ setSystemPartialSpeakerIdentity(null, null);+ }+ setTranscript((prev) => (prev ? prev + " " + data.text : data.text));+ setPartialTranscript("");}- const seg = speakerIdentificationsRef.current.reduce(applySpeakerIdentification, rawSegment);- setSegments((prev) => {- // Insert in chronological order — scan from the end since most- // segments arrive in order and this is O(1) in the common case.- const ts = seg.timestamp ?? Infinity;- let i = prev.length;- while (i > 0 && (prev[i - 1].timestamp ?? 0) > ts) i--;- if (i === prev.length) return [...prev, seg];- return [...prev.slice(0, i), seg, ...prev.slice(i)];- });- setPartialForSource("");- setTranscript((prev) => (prev ? prev + " " + data.text : data.text));- setPartialTranscript("");}- }- );- if (segmentCleanup) ipcCleanupsRef.current.push(segmentCleanup);-- const speakerCleanup = window.electronAPI?.onMeetingSpeakerIdentified?.((data) => {- lastSpeakerRef.current = { speakerId: data.speakerId, displayName: data.displayName };- speakerIdentificationsRef.current = [- ...speakerIdentificationsRef.current.filter(- (id) => id.endTime >= data.endTime - SPEAKER_IDENTIFICATION_RETENTION_MS- ),- data,- ];- setSegments((prev) =>- prev.map((segment) => {- if (segment.source !== "system" || segment.speaker) return segment;- return { ...segment, speaker: data.speakerId, speakerName: data.displayName ?? segment.speakerName };- }));- });- if (speakerCleanup) ipcCleanupsRef.current.push(speakerCleanup);+ if (segmentCleanup) ipcCleanupsRef.current.push(segmentCleanup);++ const speakerCleanup = window.electronAPI?.onMeetingSpeakerIdentified?.((data) => {+ reserveSpeakerIndex(data.speakerId);+ setSystemPartialSpeakerIdentity(data.speakerId, data.displayName ?? null);+ rememberSystemSpeaker(data.speakerId, data.displayName ?? null, false, data.endTime);+ speakerIdentificationsRef.current = [+ ...speakerIdentificationsRef.current.filter(+ (id) => id.endTime >= data.endTime - SPEAKER_IDENTIFICATION_RETENTION_MS+ ),+ data,+ ];+ setSegments((prev) => {+ const next = prev.map((segment) => applySpeakerIdentification(segment, data));+ segmentsRef.current = next;+ return next;+ });+ });+ if (speakerCleanup) ipcCleanupsRef.current.push(speakerCleanup);- const errorCleanup = window.electronAPI?.onMeetingTranscriptionError?.((err) => {- setError(err);- logger.error("Meeting transcription stream error", { error: err }, "meeting");- });- if (errorCleanup) ipcCleanupsRef.current.push(errorCleanup);-- const pendingMicChunks: ArrayBuffer[] = [];- let socketReady = false;-- let micPipelinePromise: Promise<void> | null = null;- if (micResult) {- micStreamRef.current = micResult;- const micContext = new AudioContext({ sampleRate: 24000 });- await detachFromOutputDevice(micContext);- micContextRef.current = micContext;-- micPipelinePromise = createAudioPipeline({- stream: micResult,- context: micContext,- label: "Meeting mic",- onChunk: (chunk) => {- if (!isRecordingRef.current) return;- if (socketReady) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");- return;- }- pendingMicChunks.push(chunk.slice(0));- },- }).then(({ source, processor }) => {- micSourceRef.current = source;- micProcessorRef.current = processor;+ const errorCleanup = window.electronAPI?.onMeetingTranscriptionError?.((err) => {+ setError(err);+ logger.error("Meeting transcription stream error", { error: err }, "meeting");+ });+ if (errorCleanup) ipcCleanupsRef.current.push(errorCleanup);++ const pendingMicChunks: ArrayBuffer[] = [];+ let socketReady = false;++ let micPipelinePromise: Promise<void> | null = null;+ if (micResult) {+ micStreamRef.current = micResult;+ const micContext = new AudioContext({ sampleRate: 24000 });+ await detachFromOutputDevice(micContext);+ micContextRef.current = micContext;++ micPipelinePromise = createAudioPipeline({+ stream: micResult,+ context: micContext,+ onChunk: (chunk) => {+ if (!isRecordingRef.current) return;+ if (socketReady) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");+ return;+ }+ pendingMicChunks.push(chunk.slice(0));+ },+ }).then(({ source, processor }) => {+ micSourceRef.current = source;+ micProcessorRef.current = processor;++ const micTrack = micResult.getAudioTracks()[0];+ logger.info(+ "Mic capture started for meeting transcription",+ {+ label: micTrack?.label,+ settings: micTrack?.getSettings(),+ },+ "meeting"+ );+ });+ }++ if (micPipelinePromise) {+ await micPipelinePromise;+ }- const micTrack = micResult.getAudioTracks()[0];+ if (!isRecordingRef.current) {logger.info(- "Mic capture started for meeting transcription",- {- label: micTrack?.label,- settings: micTrack?.getSettings(),- },+ "Meeting transcription aborted during pipeline setup (stop called)",+ {},"meeting");- });- }+ isStartingRef.current = false;+ await cleanup();+ return;+ }- if (micPipelinePromise) {- await micPipelinePromise;- }+ isStartingRef.current = false;+ socketReady = true;- // Abort if stop was called during pipeline setup- if (!isRecordingRef.current) {+ for (const chunk of pendingMicChunks) {+ window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");+ }++ const totalMs = performance.now() - startTime;logger.info(- "Meeting transcription aborted during pipeline setup (stop called)",- {},+ "Meeting transcription started successfully",+ {+ systemAudioMode,+ bufferedChunks: pendingMicChunks.length,+ streamsMs: Math.round(streamsMs),+ totalMs: Math.round(totalMs),+ wasPrepared: isPreparedRef.current,+ },+ "meeting"+ );+ } catch (err) {+ logger.error(+ "Meeting transcription setup failed",+ { error: (err as Error).message },"meeting");+ setError((err as Error).message);+ isRecordingRef.current = false;isStartingRef.current = false;+ setIsRecording(false);await cleanup();- return;- }-- isStartingRef.current = false;- socketReady = true;-- for (const chunk of pendingMicChunks) {- window.electronAPI?.meetingTranscriptionSend?.(chunk, "mic");}-- const totalMs = performance.now() - startTime;- logger.info(- "Meeting transcription started successfully",- {- systemAudioMode,- bufferedChunks: pendingMicChunks.length,- streamsMs: Math.round(streamsMs),- totalMs: Math.round(totalMs),- wasPrepared: isPreparedRef.current,- },- "meeting"- );- } catch (err) {- logger.error(- "Meeting transcription setup failed",- { error: (err as Error).message },- "meeting"- );- setError((err as Error).message);- isRecordingRef.current = false;- isStartingRef.current = false;- setIsRecording(false);- await cleanup();- }- }, [applySpeakerIdentification, cleanup]);+ },+ [+ applySpeakerIdentification,+ assignProvisionalSpeaker,+ cleanup,+ rememberSystemSpeaker,+ reserveSpeakerIndex,+ ]+ );useEffect(() => {getMeetingWorkletBlobUrl();}, []);useEffect(() => {- // Cancel any pending cleanup from a previous StrictMode unmount — the component remounted,- // so the in-flight startTranscription from the prior mount should keep running.if (pendingCleanupRef.current) {clearTimeout(pendingCleanupRef.current);pendingCleanupRef.current = null;}return () => {- // Defer cleanup to next tick so StrictMode remount can cancel it.- // On real unmount, the timeout fires and tears everything down.pendingCleanupRef.current = setTimeout(() => {pendingCleanupRef.current = null;void cleanup();@@ -647,6 +843,8 @@ export function useMeetingTranscription(): UseMeetingTranscriptionReturn {segments,micPartial,systemPartial,+ systemPartialSpeakerId,+ systemPartialSpeakerName,error,diarizationSessionId,prepareTranscription,diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex fef2648d4..7825d2e90 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -1927,8 +1927,16 @@"meetingAttendees": "Meeting attendees","assignName": "Assign name","isThisPerson": "Is this {{name}}?",+ "moveBubble": "Move this bubble",+ "moveRun": "Move this run","confirmed": "Confirmed",- "nameAssigned": "Name assigned"+ "nameAssigned": "Name assigned",+ "state": {+ "provisional": "Provisional",+ "confirmed": "Confirmed",+ "suggested": "Suggested",+ "locked": "Locked"+ }}},"dictionary": {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 3f473bb5f..132f308a8 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1356,12 +1356,13 @@ declare global {text: string;source: "mic" | "system";type: "partial" | "final";+ timestamp?: number;}) => void) => () => void;onMeetingSpeakerIdentified?: (callback: (data: {speakerId: string;- displayName?: string;+ displayName?: string | null;startTime: number;endTime: number;}) => void@@ -1391,20 +1392,26 @@ declare global {timestamp?: number;speaker?: string;speakerName?: string;+ speakerIsPlaceholder?: boolean;suggestedName?: string;suggestedProfileId?: number;+ speakerStatus?: "provisional" | "confirmed" | "suggested" | "locked";+ speakerLocked?: boolean;+ speakerLockSource?: "user" | "diarization" | "suggestion";}>;speakerEmbeddings?: Record<string, number[]> | null;}) => void) => () => void;// Speaker name mapping- getSpeakerMappings?: (noteId: number) => Promise<Array<{- note_id: number;- speaker_id: string;- profile_id: number | null;- display_name: string;- }>>;+ getSpeakerMappings?: (noteId: number) => Promise<+ Array<{+ note_id: number;+ speaker_id: string;+ profile_id: number | null;+ display_name: string;+ }>+ >;setSpeakerMapping?: (noteId: number,speakerId: string,@@ -1413,14 +1420,16 @@ declare global {profileId?: number | null) => Promise<{ success: boolean; profileId: number | null }>;removeSpeakerMapping?: (noteId: number, speakerId: string) => Promise<{ success: boolean }>;- getSpeakerProfiles?: () => Promise<Array<{- id: number;- display_name: string;- email: string | null;- sample_count: number;- created_at: string;- updated_at: string;- }>>;+ getSpeakerProfiles?: () => Promise<+ Array<{+ id: number;+ display_name: string;+ email: string | null;+ sample_count: number;+ created_at: string;+ updated_at: string;+ }>+ >;saveNoteSpeakerEmbeddings?: (noteId: number,embeddings: Record<string, number[]>diff --git a/src/utils/parseTranscriptSegments.ts b/src/utils/parseTranscriptSegments.tsindex 60e97bd46..f8429577b 100644--- a/src/utils/parseTranscriptSegments.ts+++ b/src/utils/parseTranscriptSegments.ts@@ -1,4 +1,5 @@import type { TranscriptSegment } from "../hooks/useMeetingTranscription";+import { normalizeTranscriptSegments } from "./transcriptSpeakerState";import logger from "./logger";export function parseTranscriptSegments(raw: string): TranscriptSegment[] {if (!raw.startsWith("[")) return [];@@ -9,19 +10,29 @@ export function parseTranscriptSegments(raw: string): TranscriptSegment[] {timestamp?: number;speaker?: string;speakerName?: string;+ speakerIsPlaceholder?: boolean;suggestedName?: string;suggestedProfileId?: number;+ speakerStatus?: TranscriptSegment["speakerStatus"];+ speakerLocked?: TranscriptSegment["speakerLocked"];+ speakerLockSource?: TranscriptSegment["speakerLockSource"];}>;- return parsed.map((s, i) => ({- id: `stored-${i}`,- text: s.text,- source: s.source,- timestamp: s.timestamp,- speaker: s.speaker,- speakerName: s.speakerName,- suggestedName: s.suggestedName,- suggestedProfileId: s.suggestedProfileId,- }));+ return normalizeTranscriptSegments(+ parsed.map((s, i) => ({+ id: `stored-${i}`,+ text: s.text,+ source: s.source,+ timestamp: s.timestamp,+ speaker: s.speaker,+ speakerName: s.speakerName,+ speakerIsPlaceholder: s.speakerIsPlaceholder,+ suggestedName: s.suggestedName,+ suggestedProfileId: s.suggestedProfileId,+ speakerStatus: s.speakerStatus,+ speakerLocked: s.speakerLocked,+ speakerLockSource: s.speakerLockSource,+ }))+ );} catch (e) {logger.warn("Failed to parse transcript segments", e);return [];diff --git a/src/utils/transcriptSpeakerState.ts b/src/utils/transcriptSpeakerState.tsnew file mode 100644index 000000000..a7f886b81--- /dev/null+++ b/src/utils/transcriptSpeakerState.ts@@ -0,0 +1,208 @@+import type { TranscriptSegment } from "../hooks/useMeetingTranscription";++export type TranscriptSpeakerStatus = "provisional" | "confirmed" | "suggested" | "locked";+export type TranscriptSpeakerLockSource = "user" | "diarization" | "suggestion";++const SPEAKER_STATE_FIELDS = [+ "speaker",+ "speakerName",+ "speakerIsPlaceholder",+ "suggestedName",+ "suggestedProfileId",+ "speakerStatus",+ "speakerLocked",+ "speakerLockSource",+] as const;++type SpeakerStateField = (typeof SPEAKER_STATE_FIELDS)[number];++const normalizeText = (text: string) => text.trim().replace(/\s+/g, " ");++const getSegmentMatchKey = (segment: TranscriptSegment) =>+ [segment.source, segment.timestamp ?? "", normalizeText(segment.text)].join("|");++const canonicalizeTranscriptSpeakerStatus = (+ status?: string,+ speakerLocked?: boolean,+ speakerLockSource?: TranscriptSpeakerLockSource+): TranscriptSpeakerStatus | undefined => {+ if (speakerLocked || speakerLockSource === "user") {+ return "locked";+ }++ switch (status) {+ case "provisional":+ case "confirmed":+ case "suggested":+ case "locked":+ return status;+ case "suggested_profile":+ return "suggested";+ case "user_locked":+ return "locked";+ case "uncertain_overlap":+ return "provisional";+ default:+ return undefined;+ }+};++const pickSpeakerStatus = (segment: TranscriptSegment): TranscriptSpeakerStatus | undefined => {+ const normalizedStatus = canonicalizeTranscriptSpeakerStatus(+ segment.speakerStatus,+ segment.speakerLocked,+ segment.speakerLockSource+ );+ if (normalizedStatus) return normalizedStatus;+ if (segment.suggestedName && !segment.speakerName) return "suggested";+ if (segment.source === "system" && segment.speakerIsPlaceholder) return "provisional";+ if (segment.speaker && segment.speaker !== "you") return "confirmed";+ return undefined;+};++export const isTranscriptSpeakerLocked = (segment: TranscriptSegment) =>+ !!segment.speakerLocked ||+ segment.speakerLockSource === "user" ||+ canonicalizeTranscriptSpeakerStatus(segment.speakerStatus) === "locked";++export const normalizeTranscriptSegment = (segment: TranscriptSegment): TranscriptSegment => {+ const speakerStatus = pickSpeakerStatus(segment);+ const speakerLocked =+ !!segment.speakerLocked || segment.speakerLockSource === "user" || speakerStatus === "locked";+ return {+ ...segment,+ speakerStatus,+ speakerLocked,+ speakerLockSource: speakerLocked+ ? (segment.speakerLockSource ?? "user")+ : segment.speakerLockSource,+ };+};++export const normalizeTranscriptSegments = (segments: TranscriptSegment[]) =>+ segments.map((segment) => normalizeTranscriptSegment(segment));++export const applyTranscriptSpeakerPatch = (+ segment: TranscriptSegment,+ patch: Partial<Pick<TranscriptSegment, SpeakerStateField>>+) => normalizeTranscriptSegment({ ...segment, ...patch });++export const lockTranscriptSpeaker = (+ segment: TranscriptSegment,+ patch: Partial<Pick<TranscriptSegment, SpeakerStateField>> = {}+) =>+ normalizeTranscriptSegment({+ ...segment,+ ...patch,+ speakerLocked: true,+ speakerStatus: "locked",+ speakerLockSource: "user",+ });++const mergeSpeakerFields = (existing: TranscriptSegment, incoming: TranscriptSegment) => {+ const merged = { ...incoming } as TranscriptSegment;+ const existingFields = existing as Record<SpeakerStateField, unknown>;+ const mergedFields = merged as Record<SpeakerStateField, unknown>;++ for (const field of SPEAKER_STATE_FIELDS) {+ if (mergedFields[field] === undefined && existingFields[field] !== undefined) {+ mergedFields[field] = existingFields[field];+ }+ }++ if (isTranscriptSpeakerLocked(existing)) {+ for (const field of SPEAKER_STATE_FIELDS) {+ if (existingFields[field] !== undefined) {+ mergedFields[field] = existingFields[field];+ }+ }+ }++ return normalizeTranscriptSegment(merged);+};++export const mergeTranscriptSegments = (+ existingSegments: TranscriptSegment[],+ incomingSegments: TranscriptSegment[]+) => {+ if (incomingSegments.length === 0) {+ return normalizeTranscriptSegments(existingSegments);+ }++ const existingById = new Map<string, TranscriptSegment>();+ const existingByKey = new Map<string, Array<{ index: number; segment: TranscriptSegment }>>();++ existingSegments.forEach((segment, index) => {+ if (segment.id) {+ existingById.set(segment.id, segment);+ }++ const key = getSegmentMatchKey(segment);+ const bucket = existingByKey.get(key);+ if (bucket) {+ bucket.push({ index, segment });+ } else {+ existingByKey.set(key, [{ index, segment }]);+ }+ });++ const usedIndexes = new Set<number>();++ return incomingSegments.map((segment, index) => {+ const byId = segment.id ? existingById.get(segment.id) : undefined;+ if (byId) {+ const byIdIndex = existingSegments.findIndex((candidate) => candidate.id === byId.id);+ if (byIdIndex >= 0) {+ usedIndexes.add(byIdIndex);+ }+ return mergeSpeakerFields(byId, segment);+ }++ const keyMatches = existingByKey.get(getSegmentMatchKey(segment)) || [];+ const keyMatch = keyMatches.find(({ index: existingIndex }) => !usedIndexes.has(existingIndex));+ if (keyMatch) {+ usedIndexes.add(keyMatch.index);+ return mergeSpeakerFields(keyMatch.segment, segment);+ }++ const fallbackIndex = existingSegments.findIndex(+ (candidate, existingIndex) =>+ !usedIndexes.has(existingIndex) &&+ candidate.source === segment.source &&+ candidate.text === segment.text+ );++ if (fallbackIndex >= 0) {+ usedIndexes.add(fallbackIndex);+ return mergeSpeakerFields(existingSegments[fallbackIndex], segment);+ }++ const positionalMatch = existingSegments[index];+ if (positionalMatch && !usedIndexes.has(index) && positionalMatch.source === segment.source) {+ usedIndexes.add(index);+ return mergeSpeakerFields(positionalMatch, segment);+ }++ return normalizeTranscriptSegment({+ ...segment,+ id: segment.id || `merged-${index}`,+ });+ });+};++export const serializeTranscriptSegments = (segments: TranscriptSegment[]) =>+ JSON.stringify(+ segments.map((segment) => ({+ text: segment.text,+ source: segment.source,+ timestamp: segment.timestamp,+ speaker: segment.speaker,+ speakerName: segment.speakerName,+ speakerIsPlaceholder: segment.speakerIsPlaceholder,+ suggestedName: segment.suggestedName,+ suggestedProfileId: segment.suggestedProfileId,+ speakerStatus: segment.speakerStatus,+ speakerLocked: segment.speakerLocked,+ speakerLockSource: segment.speakerLockSource,+ }))+ );