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
fix(meetings): Keep speaker identities stable and manual labels persistent
Chadpihae3642b2b3942
diff --git a/docs/meeting-speaker-identification-investigation.md b/docs/meeting-speaker-identification-investigation.mdnew file mode 100644index 000000000..39562b741--- /dev/null+++ b/docs/meeting-speaker-identification-investigation.md@@ -0,0 +1,205 @@+# Meeting Speaker Identification — Root Cause Investigation++**Bug report:** During a meeting recording (local models: Parakeet / Nemotron / OpenWhispr),+two different voices are treated as the same speaker, sometimes attributed to the+recorder. Manually identifying a participant in the transcript does not stick for+subsequent conversation. Participants' emails are added *during* the meeting.++**Branch:** `worktree-investigate-speaker-identification` (off `main` @ `b656fa69`)+**Status:** Root causes identified and reproduced; RC1–RC3, RC6, RC7 fixed on this+branch (see "Fix implemented" at the end). RC4/RC5 remain follow-ups.++---++## Architecture recap (as-built)++- Only **system audio** feeds the live identifier (`ipcHandlers.js` `sendMeetingAudio`,+ ~line 6767). The **mic channel is definitionally the recorder** — labeled `you`+ in `diarization.js mergeWithTranscript()` (~line 462) and rendered as+ `notes.speaker.you` in `PersonalNotesView.tsx` (~line 802).+- There are **four independent speaker-ID namespaces, all using the same+ `speaker_N` string format**:+ 1. Internal live cluster ids (`liveSpeakerIdentifier.js`, `_assignSpeakerId`)+ 2. Public remapped ids (`createSpeakerRemapper`, `ipcHandlers.js` ~5722)+ 3. Renderer-minted placeholder ids (`mintPlaceholderSpeakerId`,+ `meetingRecordingStore.ts` ~567)+ 4. Offline diarization renumbered ids (`_startOrSkipDiarization` ~9793 and+ `diarization.js mergeWithTranscript` ~440)++ They collide textually but denote different clusters. Several code paths pass an+ id from one namespace into a map keyed by another.++---++## Symptom 1 — Two different voices treated as the same speaker++### RC1 (primary): session speaker cap defaults to 1 when participants are added mid-meeting++- `resolveSessionMaxSpeakers()` (`ipcHandlers.js` ~5781) = `expectedCount − 1`+ (mic is "you"), and `expectedCount` falls back to+ `DEFAULT_EXPECTED_SPEAKER_COUNT = 2` (`src/constants/speakerDetection.json`).+- The renderer **never pushes the speaker config at recording start** —+ `startRecording()` only sets store state; `pushConfig` fires solely from the+ stepper/toggle UI. Main falls back to note participants **at start time only**+ (`_resolveInitialMeetingSpeakerConfig`, called at ~6655).+- The reported repro adds participant emails **during** the meeting → at start the+ note has no participants → cap = 1 → the live identifier force-merges every+ remote voice into one cluster (`_assignOrForceCluster`), and the renderer's own+ placeholder minting also caps at `speaker_0`.++**Demonstrated:** two orthogonal (cosine 0) embeddings both resolve to `speaker_0`+at cap 1 (Demo 1).++### RC2: the public-label remapper is frozen at recording start and collapses new voices++- `meetingSpeakerRemapper = createSpeakerRemapper(resolveSessionMaxSpeakers())` is+ created **once** in `startLiveSpeakerIdentification` (~5997). The+ `meeting-set-session-speaker-config` handler (~9189) updates the identifier's+ cap but **never rebuilds the remapper** — fixing the stepper mid-meeting does not+ help the UI labels.+- Remapper logic: once `map.size >= cap`, **every new internal id maps to+ `speaker_{cap-1}` permanently** — distinct voices folded into the last slot+ (Demo 3).++### RC3: the offline (post-meeting) pass re-clusters with the stale start-time count++- At stop, `sessionSpeakerConfigSnapshot = this.activeMeetingSpeakerConfig`+ (~6950/6977) is passed to `_startOrSkipDiarization`.+ `_resolveSpeakerExpectation` (~9678) short-circuits on+ `sessionConfig.expectedCount` and **never consults the note's (now-updated)+ attendees**. Default case → `sherpa-onnx-diarize --clustering.num-clusters=1` →+ the entire system track is literally one cluster in the final transcript.+ `capSpeakerClusters` additionally folds excess clusters into the most-talkative+ one.++### RC4 (contributing): single-VAD-segment short circuit++- A "speech segment" ends only after 24 consecutive silent 32 ms windows+ (~0.77 s). Back-and-forth exchanges with shorter gaps stay one segment;+ `_resolveSpeakerForEmbedding` short-circuits on `currentSegmentSpeakerId`+ (`liveSpeakerIdentifier.js` ~682) so the whole exchange keeps the first+ speaker, and the final mixed-voice embedding is averaged into that speaker's+ centroid (`updateCentroid: true`) — centroid pollution drives later+ `recluster()` merges (threshold 0.65) between genuinely different people.++### RC5 (contributing, local models — the reporter's setup): timestamp skew defeats window matching++- Local mode transcribes 5 s chunks (`LOCAL_MEETING_CHUNK_INTERVAL_MS = 5000`)+ and stamps segments with `Date.now()` **after decoding** (~6146), i.e. the+ utterance midpoint lags by ~2.5–7+ s. Live identifications carry+ sample-clock-derived windows padded only ±0.75 s+ (`LIVE_WINDOW_PADDING_SECONDS`). The window matching in main (~6029) and in the+ renderer (`isSegmentWithinIdentificationWindow`) systematically misses →+ segments fall back to the 8 s carry-forward+ (`SYSTEM_SPEAKER_CARRY_FORWARD_MS`) which chains consecutive *different* voices+ onto the previous speaker's id.++## Symptom 2 — Remote speech attributed to the recorder++- Anything on the mic channel is "you". Remote voices played over loudspeakers+ re-enter the mic; suppression is heuristic (echo-leak correlation/RMS ceilings,+ holdbacks, text-overlap dedupe in `transcribeLocalMeetingChunk` ~6148 and+ `dedupeMicAgainstSystem`). Local models transcribe the bleed slightly+ differently on each channel, so text-overlap dedupe misses → the bleed survives+ as a mic segment → rendered as the recorder. AEC helper absence/failure widens+ this hole.+- **Amplifier:** `bindOneOnOneAttendeeToSpeaker(publicSpeakerId)` (~5787, invoked+ at ~6005 with the *public* id) reads `getSpeakerEmbedding()` from the+ *internal*-keyed map — it can persist the 1:1 attendee's profile with the+ wrong cluster's embedding (including a bleed cluster). Poisoned profiles then+ mislabel future meetings via `getLiveSpeakerProfiles` matching (threshold 0.65,+ margin 0.03) and `_retroactiveMapping` (>0.6).++## Symptom 3 — Manual identification doesn't persist++### RC6: `set-speaker-mapping` crosses ID namespaces and fails silently++- The renderer only ever sees public/minted ids, but the handler (~9364) passes+ that id straight into `liveSpeakerIdentifier.getSpeakerEmbedding()` and+ `.mapSpeaker()`, which are keyed by internal ids. After any recluster merge or+ cap fold, the id doesn't exist internally → `mapSpeaker` returns `false`+ **silently** (return value ignored) → no display name attached → every+ subsequent identification of that voice arrives unnamed.++**Demonstrated end-to-end (Demo 2):** with cap 3, an ambiguous utterance mints a+third cluster, the 30 s recluster merges it away, the next new participant gets+internal `speaker_3` → public `speaker_2`; `mapSpeaker("speaker_2", …, "Carol")`+returns `false`; the next identification of Carol's voice carries no name.++### RC7: the post-meeting reconcile looks up manual mappings under the wrong key++- `_reconcileLiveSpeakerState` (~9592) matches offline clusters to live clusters+ by embedding, then fetches the user's mapping with+ `mapping.speaker_id === bestEntry.speakerId` — `bestEntry.speakerId` is the+ live **internal** id, but rows were stored under the renderer's **public** id+ → the transfer silently finds nothing whenever the namespaces diverged+ (exactly the multi-speaker sessions where users bother to identify people).+- The offline pass renumbers clusters independently and+ `mergeTranscriptSegments` (renderer, `NoteEditor.tsx` ~546) lets diarization+ overwrite `speaker` on unlocked segments. `NoteEditor`'s `speakerMappings`+ (keyed by the old ids) then no longer match any final segment → the+ identification visibly disappears after "diarization complete".+- During the live session the renderer's `speakerLocks` *does* keep the name on+ segments carrying the same public id — which, under RC1/RC2, also mislabels+ other voices with that name. Both halves of "identification doesn't work" are+ the same ID-aliasing defect seen from two sides.++---++## Reproduction++`node <scratchpad>/speaker-id-repro.js` (drives the real `LiveSpeakerIdentifier`+with mocked `debugLogger`/`speakerEmbeddings`, plus a verbatim copy of+`createSpeakerRemapper`): all three demos assert and pass on `main`.++Suggested regression home: `test/helpers/liveSpeakerIdentifier.test.js` using the+repo's existing `Module._load` mocking pattern (see+`test/helpers/audioActivityDetector.test.js`).++## Fix implemented (this branch)++1. **ID namespaces collapsed** (RC6, RC7, and the RC2 folding): cluster ids in+ `liveSpeakerIdentifier.js` now double as the transcript labels —+ `_assignSpeakerId` allocates the lowest free `speaker_N` slot and a slot freed+ by a recluster merge is reused for the next new voice. The+ `createSpeakerRemapper` layer in `ipcHandlers.js` is deleted; identification+ events, merge events, `set-speaker-mapping`, `getSpeakerEmbedding`,+ `bindOneOnOneAttendeeToSpeaker`, and the post-meeting+ `_reconcileLiveSpeakerState` all now share one id space. `mapSpeaker` logs a+ warning when it drops an unknown id instead of failing silently.+2. **Caps unfrozen** (RC1, RC3): stepper-set configs are marked `explicit`;+ `db-update-note` calls `_refreshMeetingSpeakerConfigFromNote` when+ participants change during the active meeting note, which re-derives+ `expectedCount`, raises the live identifier's cap, and broadcasts+ `meeting-session-speaker-config-updated` (new preload/renderer listener keeps+ the stepper and renderer-side placeholder cap in sync). The offline pass's+ `_resolveSpeakerExpectation` now re-reads the note at stop time unless the+ count was explicit, and applies consistent `total − 1` semantics.+3. **Renderer merge handler** now moves *locked* segments to the kept cluster id+ (preserving the user-set name) so a reused slot can't inherit a stale lock.+4. **Merged from `fix/meeting-speaker-identification` (concurrent Codex branch):**+ `expectedCountIsExplicit` on `startRecording` so participant-derived counts no+ longer masquerade as a manual stepper choice (`userTouchedStepper`), the+ extracted `resolveParticipant*` helpers in `src/utils/participants.ts` with+ tests, and `syncSessionExpectedCountFromParticipants` for instant stepper+ feedback on roster edits (state-only — the authoritative cap update stays in+ main's `db-update-note` hook so the config isn't misflagged as explicit).+ Intentionally **not** taken: the mutable remapper (`meetingSpeakerIdentity.js`)+ — superseded by the slot-reuse design, which also fixes RC6/RC7 — and the+ `loopback` live-ID enablement, split out as a Windows-verified follow-up.++Regression tests: `test/helpers/liveSpeakerIdentifier.test.js` (5 tests, written+RED-first against the pre-fix behavior) and `test/helpers/participants.test.js`.++## Remaining follow-ups (not in this branch)++1. **Persist manual identity by embedding, not by volatile id** (hardens+ reconcile further; the profile embedding is already saved at mapping time).+2. **Local-mode timestamps** (RC5): stamp segments at chunk capture start+ (arrival − chunk duration), not decode completion, and/or widen the+ identification matching window for the chunked path.+3. **Segment turn-splitting** (RC4): re-check speaker identity on live+ re-identification instead of short-circuiting on `currentSegmentSpeakerId`,+ or skip centroid updates for segments whose live identity flipped mid-segment.+4. **Mic bleed → "You" attribution:** heuristic; AEC coverage and cross-channel+ dedupe for local models are the levers.diff --git a/preload.js b/preload.jsindex b40f9b4cf..4c1b639c5 100644--- a/preload.js+++ b/preload.js@@ -715,6 +715,10 @@ contextBridge.exposeInMainWorld("electronAPI", {"meeting-speakers-merged",(callback) => (_event, data) => callback(data)),+ onMeetingSessionSpeakerConfigUpdated: registerListener(+ "meeting-session-speaker-config-updated",+ (callback) => (_event, data) => callback(data)+ ),onMeetingTranscriptionError: registerListener("meeting-transcription-error",(callback) => (_event, data) => callback(data)diff --git a/src/components/notes/NoteParticipants.tsx b/src/components/notes/NoteParticipants.tsxindex 18f2c5603..ee6c2a5f0 100644--- a/src/components/notes/NoteParticipants.tsx+++ b/src/components/notes/NoteParticipants.tsx@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";import { Users, X } from "lucide-react";import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";import type { CalendarAttendee } from "../../types/calendar";+import { syncSessionExpectedCountFromParticipants } from "../../stores/meetingRecordingStore";function getInitials(displayName: string | null, email: string): string {if (displayName) return displayName.charAt(0).toUpperCase();@@ -106,6 +107,7 @@ export default function NoteParticipants({ noteId, participants }: NoteParticipaconst saveParticipants = useCallback((updated: CalendarAttendee[]) => {+ syncSessionExpectedCountFromParticipants(noteId, updated);window.electronAPI.updateNote(noteId, {participants: JSON.stringify(updated),});diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 4c6aec269..8f85dd93f 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -330,6 +330,7 @@ export default function PersonalNotesView({seedSegments,diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,expectedCount: resolveExpectedSpeakerCount(note),+ expectedCountIsExplicit: note?.expected_speaker_count != null,});}, [activeNote]);@@ -622,6 +623,7 @@ export default function PersonalNotesView({seedSegments,diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,expectedCount: resolveExpectedSpeakerCount(note),+ expectedCountIsExplicit: note?.expected_speaker_count != null,});onMeetingRecordingRequestHandled?.();}, [meetingRecordingRequest, activeNoteId, activeNote, onMeetingRecordingRequestHandled]);diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex b08f7d654..d6ce3fb9c 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -72,17 +72,6 @@ const ALLOWED_MEETING_PROVIDERS = new Set([// streaming providers must be told the true PCM rate or they misread the audio.const MEETING_STREAM_SAMPLE_RATE = 24000;-function parseAttendees(raw) {- if (!raw) return [];- if (Array.isArray(raw)) return raw;- try {- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }-}-const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";const XAI_STT_URL = "https://api.x.ai/v1/stt";@@ -727,7 +716,7 @@ class IPCHandlers {return { displayName, email };}- _resolveNoteExpectedSpeakerCount(note) {+ _noteExpectedSpeakerCountOrNull(note) {const stored = Number(note?.expected_speaker_count);if (Number.isFinite(stored) && stored > 0) {return Math.min(stored, MAX_SPEAKER_COUNT);@@ -736,7 +725,11 @@ class IPCHandlers {if (others > 0) {return Math.min(others + 1, MAX_SPEAKER_COUNT);}- return DEFAULT_EXPECTED_SPEAKER_COUNT;+ return null;+ }++ _resolveNoteExpectedSpeakerCount(note) {+ return this._noteExpectedSpeakerCountOrNull(note) ?? DEFAULT_EXPECTED_SPEAKER_COUNT;}_resolveInitialMeetingSpeakerConfig(noteId) {@@ -755,6 +748,30 @@ class IPCHandlers {return { enabled, expectedCount: this._resolveNoteExpectedSpeakerCount(note) };}+ // Participants added mid-meeting must raise the speaker cap that was derived+ // from the note at recording start. A count the user set via the stepper+ // (explicit) is never overridden.+ _refreshMeetingSpeakerConfigFromNote(noteId, note) {+ const config = this.activeMeetingSpeakerConfig;+ if (!config || config.explicit) return;+ if (noteId == null || this._activeMeetingNoteId !== noteId) return;++ const expectedCount = this._resolveNoteExpectedSpeakerCount(note);+ if (expectedCount === config.expectedCount) return;++ this.activeMeetingSpeakerConfig = { ...config, expectedCount };+ liveSpeakerIdentifier.setMaxSpeakers(Math.max(1, expectedCount - 1));+ broadcastToWindows("meeting-session-speaker-config-updated", {+ enabled: config.enabled,+ expectedCount,+ });+ debugLogger.info(+ "Meeting speaker config refreshed from participants",+ { noteId, expectedCount },+ "speaker"+ );+ }+_rebuildMirror(basePath) {const markdownMirror = require("./markdownMirror");if (basePath) markdownMirror.init(basePath);@@ -1383,7 +1400,10 @@ class IPCHandlers {setImmediate(() => broadcastToWindows("note-updated", result.note));this._asyncVectorUpsert(result.note);this._asyncMirrorWrite(result.note);- if (updates.participants) this._tryAutoLabelOneOnOne(id);+ if (updates.participants) {+ this._tryAutoLabelOneOnOne(id);+ this._refreshMeetingSpeakerConfigFromNote(id, result.note);+ }}return result;});@@ -5717,21 +5737,6 @@ class IPCHandlers {let meetingLiveSpeakerState = null;let meetingLiveSpeakerStartedAt = null;let meetingReclusterTimer = null;- let meetingSpeakerRemapper = (id) => id;-- const createSpeakerRemapper = (maxSpeakers) => {- const cap = Math.max(1, Math.floor(maxSpeakers) || 1);- const map = new Map();- return (internalId) => {- if (!internalId) return internalId;- const existing = map.get(internalId);- if (existing !== undefined) return existing;- const index = map.size < cap ? map.size : cap - 1;- const label = `speaker_${index}`;- map.set(internalId, label);- return label;- };- };let meetingLocalMode = false;let meetingLocalBuffers = { mic: [], system: [] };@@ -5994,15 +5999,13 @@ class IPCHandlers {meetingLiveSpeakerState = null;meetingLiveSpeakerStartedAt = Date.now();- meetingSpeakerRemapper = createSpeakerRemapper(resolveSessionMaxSpeakers());const started = await liveSpeakerIdentifier.start((identification) => {if (!win || win.isDestroyed()) {return;}- const publicSpeakerId = meetingSpeakerRemapper(identification.speakerId);- bindOneOnOneAttendeeToSpeaker(publicSpeakerId);+ bindOneOnOneAttendeeToSpeaker(identification.speakerId);const displayName = meetingOneOnOneAttendee? meetingOneOnOneAttendee.displayName@@ -6018,7 +6021,6 @@ class IPCHandlers {);const enrichedIdentification = {...identification,- speakerId: publicSpeakerId,displayName,startTime,endTime,@@ -6035,7 +6037,7 @@ class IPCHandlers {(!seg.speaker || seg.speakerIsPlaceholder)) {applyConfirmedSpeaker(seg, {- speaker: publicSpeakerId,+ speaker: identification.speakerId,speakerName: displayName || seg.speakerName,speakerIsPlaceholder: false,});@@ -6057,14 +6059,7 @@ class IPCHandlers {const merges = await liveSpeakerIdentifier.recluster();if (!merges.length) return;- const publicMerges = merges.map(({ keep, remove, displayName, similarity }) => ({- keep: meetingSpeakerRemapper(keep),- remove: meetingSpeakerRemapper(remove),- displayName,- similarity,- }));- for (const { keep, remove, displayName } of publicMerges) {- if (keep === remove) continue;+ for (const { keep, remove, displayName } of merges) {for (const seg of meetingDiarizationSegments) {if (seg.speaker === remove) {seg.speaker = keep;@@ -6073,7 +6068,7 @@ class IPCHandlers {}}- win.webContents.send("meeting-speakers-merged", publicMerges);+ win.webContents.send("meeting-speakers-merged", merges);}, 30_000);} else {meetingLiveSpeakerStartedAt = null;@@ -6292,6 +6287,7 @@ class IPCHandlers {meetingOneOnOneAttendee = null;meetingOneOnOneProfileBound = false;meetingNoteId = null;+ this._activeMeetingNoteId = null;meetingLocalMode = false;meetingLocalBuffers = { mic: [], system: [] };if (meetingDiarizationStream) {@@ -6649,6 +6645,7 @@ class IPCHandlers {meetingOneOnOneAttendee = resolveOneOnOneAttendeeForNote(options.noteId);meetingOneOnOneProfileBound = false;meetingNoteId = options.noteId ?? null;+ this._activeMeetingNoteId = meetingNoteId;// Seed the speaker cap from the note/calendar participants up front so live// identification isn't stuck at the default if the renderer never pushes a config.@@ -9196,7 +9193,7 @@ class IPCHandlers {Number(payload?.expectedCount) || DEFAULT_EXPECTED_SPEAKER_COUNT));- this.activeMeetingSpeakerConfig = { enabled, expectedCount };+ this.activeMeetingSpeakerConfig = { enabled, expectedCount, explicit: true };liveSpeakerIdentifier.setEnabled(enabled);// Live identification only labels other speakers (the mic track is "you"),// so cap at expectedCount - 1 to match resolveSessionMaxSpeakers().@@ -9676,23 +9673,21 @@ class IPCHandlers {}_resolveSpeakerExpectation({ sessionConfig, noteId, observedSpeakerIds }) {- if (sessionConfig?.expectedCount) {- const total = Math.min(sessionConfig.expectedCount, MAX_SPEAKER_COUNT);- const numSpeakers = Math.max(1, total - 1);- return { numSpeakers, cap: numSpeakers };- }+ // Only a count the user set explicitly outranks the note: participants added+ // mid-meeting postdate the config snapshot taken at recording start.+ let expectedTotal = sessionConfig?.explicit ? sessionConfig.expectedCount : null;- let attendees = [];- if (noteId) {+ if (!expectedTotal && noteId != null) {try {- const note = this.databaseManager.getNote(noteId);- attendees = parseAttendees(note?.participants);+ expectedTotal = this._noteExpectedSpeakerCountOrNull(this.databaseManager.getNote(noteId));} catch (_) {- attendees = [];+ expectedTotal = null;}}- if (attendees.length >= 2) {- const numSpeakers = Math.min(attendees.length, MAX_SPEAKER_COUNT);++ if (expectedTotal) {+ const total = Math.min(expectedTotal, MAX_SPEAKER_COUNT);+ const numSpeakers = Math.max(1, total - 1);return { numSpeakers, cap: numSpeakers };}diff --git a/src/helpers/liveSpeakerIdentifier.js b/src/helpers/liveSpeakerIdentifier.jsindex d39dd620c..793436962 100644--- a/src/helpers/liveSpeakerIdentifier.js+++ b/src/helpers/liveSpeakerIdentifier.js@@ -134,7 +134,6 @@ class LiveSpeakerIdentifier {this.transientDisplayNames = new Map();this.transientProfileIds = new Map();this.transientNoteIds = new Map();- this.nextLiveIndex = 0;this.currentSegmentSpeakerId = null;this.currentSegmentSpeakerName = null;this.lastLiveIdentificationSample = 0;@@ -333,6 +332,11 @@ class LiveSpeakerIdentifier {mapSpeaker(liveId, profileId, displayName, noteId) {if (!liveId || !this.transientEmbeddings.has(liveId)) {+ debugLogger.warn("Live speaker mapping dropped: unknown speaker id", {+ liveId,+ displayName,+ knownSpeakers: [...this.transientEmbeddings.keys()],+ });return false;}@@ -382,7 +386,6 @@ class LiveSpeakerIdentifier {this.transientDisplayNames = new Map();this.transientProfileIds = new Map();this.transientNoteIds = new Map();- this.nextLiveIndex = 0;this.currentSegmentSpeakerId = null;this.currentSegmentSpeakerName = null;this.lastLiveIdentificationSample = 0;@@ -755,9 +758,15 @@ class LiveSpeakerIdentifier {return null;}+ // Cluster ids double as the transcript's speaker labels, so a slot freed by a+ // recluster merge is reused for the next new voice — the renderer has already+ // rewritten the merged label's segments via the merge event._assignSpeakerId(embedding) {- const speakerId = `speaker_${this.nextLiveIndex}`;- this.nextLiveIndex += 1;+ let index = 0;+ while (this.transientEmbeddings.has(`speaker_${index}`)) {+ index += 1;+ }+ const speakerId = `speaker_${index}`;this.transientEmbeddings.set(speakerId, cloneFloat32Array(embedding));this.transientCounts.set(speakerId, 1);return speakerId;diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex 22b95c02a..37d35ffbf 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -8,7 +8,12 @@ import {} from "../helpers/micSelectionRecovery";import { ActiveMicRecoveryController } from "../helpers/activeMicRecovery";import { getBaseLanguageCode } from "../utils/languageSupport";+import {+ resolveInitialSpeakerCountOverride,+ resolveParticipantSpeakerCountSync,+} from "../utils/participants";import type { SystemAudioAccessResult, SystemAudioStrategy } from "../types/electron";+import type { CalendarAttendee } from "../types/calendar";import {DEFAULT_SYSTEM_AUDIO_ACCESS,getDisplayCaptureModeForStrategy,@@ -503,6 +508,31 @@ export function setSessionExpectedCount(count: number): void {}}+// Instant stepper feedback when the roster changes mid-recording. The+// authoritative cap update happens in main (db-update-note →+// _refreshMeetingSpeakerConfigFromNote), which broadcasts+// meeting-session-speaker-config-updated back to this store — so no pushConfig+// here, or the config would be marked as an explicit stepper choice.+export function syncSessionExpectedCountFromParticipants(+ noteId: number,+ participants: readonly CalendarAttendee[]+): void {+ const state = useMeetingRecordingStore.getState();+ const expectedCount = resolveParticipantSpeakerCountSync({+ recordingNoteId: state.recordingNoteId,+ noteId,+ userTouchedStepper: state.userTouchedStepper,+ currentExpectedCount: state.sessionExpectedCount,+ participants,+ });+ if (expectedCount == null) return;++ const clamped = Math.max(1, Math.min(MAX_SPEAKER_COUNT, expectedCount));+ if (clamped === state.sessionExpectedCount) return;++ useMeetingRecordingStore.setState({ sessionExpectedCount: clamped });+}+function setSystemPartialSpeakerIdentity(speakerId: string | null, speakerName: string | null) {systemPartialSpeakerIdValue = speakerId;useMeetingRecordingStore.setState({@@ -716,6 +746,7 @@ export interface StartRecordingArgs {seedSegments?: TranscriptSegment[];diarizationEnabled?: boolean | null;expectedCount?: number | null;+ expectedCountIsExplicit?: boolean;}export async function startRecording(args: StartRecordingArgs): Promise<void> {@@ -761,7 +792,10 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {recordingFolderId: args.folderId,sessionDiarizationEnabled: initialEnabled,sessionExpectedCount: initialCount,- userTouchedStepper: args.expectedCount != null,+ userTouchedStepper: resolveInitialSpeakerCountOverride(+ args.expectedCount,+ args.expectedCountIsExplicit+ ),segments: seed,transcript: buildTranscriptText(seed),micPartial: "",@@ -1015,7 +1049,12 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {let next = useMeetingRecordingStore.getState().segments;for (const { keep, remove, displayName } of merges) {next = next.map((seg) => {- if (seg.speaker !== remove || seg.speakerLocked) return seg;+ if (seg.speaker !== remove) return seg;+ // Locked segments keep their user-set name but must still move to the+ // kept cluster: the freed id is reused for the next new voice.+ if (seg.speakerLocked) {+ return normalizeTranscriptSegment({ ...seg, speaker: keep });+ }return normalizeTranscriptSegment({...seg,speaker: keep,@@ -1051,6 +1090,16 @@ export async function startRecording(args: StartRecordingArgs): Promise<void> {});if (errorCleanup) ipcCleanups.push(errorCleanup);+ // Main re-derives the expected count when participants are added mid-meeting+ // (never for a count set explicitly via the stepper — main skips those).+ const speakerConfigCleanup = window.electronAPI?.onMeetingSessionSpeakerConfigUpdated?.(+ (config) => {+ const clamped = Math.max(1, Math.min(MAX_SPEAKER_COUNT, config.expectedCount));+ useMeetingRecordingStore.setState({ sessionExpectedCount: clamped });+ }+ );+ if (speakerConfigCleanup) ipcCleanups.push(speakerConfigCleanup);+if (startResult.oneOnOneAttendee) {const synthetic: SpeakerIdentification = {speakerId: "speaker_0",diff --git a/src/types/electron.ts b/src/types/electron.tsindex b3dd927c2..e3ef21f91 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2147,6 +2147,9 @@ declare global {}>) => void) => () => void;+ onMeetingSessionSpeakerConfigUpdated?: (+ callback: (config: { enabled: boolean; expectedCount: number }) => void+ ) => () => void;onMeetingTranscriptionError?: (callback: (error: string) => void) => () => void;// Speaker diarizationdiff --git a/src/utils/participants.ts b/src/utils/participants.tsindex c72d5a28a..5c166a244 100644--- a/src/utils/participants.ts+++ b/src/utils/participants.ts@@ -1,5 +1,38 @@import type { CalendarAttendee } from "../types/calendar";+interface ParticipantSpeakerCountSyncInput {+ recordingNoteId: number | null;+ noteId: number;+ userTouchedStepper: boolean;+ currentExpectedCount: number;+ participants: readonly CalendarAttendee[];+}++export const resolveParticipantExpectedSpeakerCount = (+ participants: readonly CalendarAttendee[]+): number | null => {+ const others = participants.filter((attendee) => attendee?.self !== true).length;+ return others > 0 ? others + 1 : null;+};++export const resolveParticipantSpeakerCountSync = ({+ recordingNoteId,+ noteId,+ userTouchedStepper,+ currentExpectedCount,+ participants,+}: ParticipantSpeakerCountSyncInput): number | null => {+ if (recordingNoteId !== noteId || userTouchedStepper) return null;++ const expectedCount = resolveParticipantExpectedSpeakerCount(participants);+ return expectedCount != null && expectedCount !== currentExpectedCount ? expectedCount : null;+};++export const resolveInitialSpeakerCountOverride = (+ expectedCount: number | null | undefined,+ expectedCountIsExplicit?: boolean+): boolean => expectedCountIsExplicit ?? expectedCount != null;+// Expected total speaker count for a meeting note: the stored value, else derived from// calendar participants (non-self attendees + you), else null so callers use their default.export const resolveExpectedSpeakerCount = (note?: {@@ -17,6 +50,5 @@ export const resolveExpectedSpeakerCount = (note?: {return null;}- const others = attendees.filter((attendee) => attendee?.self !== true).length;- return others > 0 ? others + 1 : null;+ return resolveParticipantExpectedSpeakerCount(attendees);};diff --git a/test/helpers/liveSpeakerIdentifier.test.js b/test/helpers/liveSpeakerIdentifier.test.jsnew file mode 100644index 000000000..2966d5652--- /dev/null+++ b/test/helpers/liveSpeakerIdentifier.test.js@@ -0,0 +1,155 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const identifierModulePath = require.resolve("../../src/helpers/liveSpeakerIdentifier");+const originalLoad = Module._load;++function cosineSimilarity(a, b) {+ let dot = 0;+ let normA = 0;+ let normB = 0;+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }+ const denom = Math.sqrt(normA) * Math.sqrt(normB);+ return denom === 0 ? 0 : dot / denom;+}++function loadIdentifier() {+ delete require.cache[identifierModulePath];+ const warnings = [];++ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "./debugLogger") {+ return {+ info() {},+ warn(message, data) {+ warnings.push({ message, data });+ },+ debug() {},+ error() {},+ };+ }+ if (request === "./speakerEmbeddings") {+ return {+ MAX_EMBEDDING_SECONDS: 8,+ isAvailable: () => true,+ cosineSimilarity,+ extractEmbeddingFromSamples: async () => null,+ };+ }+ return originalLoad.call(this, request, parent, isMain);+ };++ try {+ const { LiveSpeakerIdentifier } = require(identifierModulePath);+ return { LiveSpeakerIdentifier, warnings };+ } finally {+ Module._load = originalLoad;+ }+}++const unit = (values) => {+ const norm = Math.sqrt(values.reduce((sum, v) => sum + v * v, 0));+ return new Float32Array(values.map((v) => v / norm));+};++const voiceA = unit([1, 0, 0]);+const voiceB = unit([0, 1, 0]);+// ~0.7 similar to both A and B: fails the match margin, so it mints a cluster+// that the next recluster pass merges back into A.+const ambiguousVoice = unit([0.7, 0.7, 0.14]);+const voiceC = unit([0.05, 0.05, 0.99]);++function seedMergedSession(identifier) {+ identifier.setMaxSpeakers(3);+ identifier._resolveSpeakerForEmbedding(voiceA, { updateCentroid: true });+ identifier._resolveSpeakerForEmbedding(voiceB, { updateCentroid: true });+ identifier._resolveSpeakerForEmbedding(ambiguousVoice, { updateCentroid: true });+ const merges = identifier._performRecluster();+ assert.equal(merges.length, 1, "expected the ambiguous cluster to merge away");+ return merges[0];+}++test("new voice after a recluster merge reuses the freed speaker slot", () => {+ const { LiveSpeakerIdentifier } = loadIdentifier();+ const identifier = new LiveSpeakerIdentifier();++ const merge = seedMergedSession(identifier);+ assert.equal(merge.remove, "speaker_2");++ const resolved = identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });+ assert.equal(+ resolved.speakerId,+ "speaker_2",+ "a freed slot must be reused so cluster ids stay aligned with the labels the UI shows"+ );+});++test("manual identification sticks for a voice that appeared after a merge", () => {+ const { LiveSpeakerIdentifier } = loadIdentifier();+ const identifier = new LiveSpeakerIdentifier();++ seedMergedSession(identifier);+ identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });++ // "speaker_2" is the label the transcript shows for the new voice — the+ // renderer reuses the slot freed by the merge. Naming that label must work.+ const mapped = identifier.mapSpeaker("speaker_2", 42, "Carol", 7);+ assert.equal(mapped, true, "mapSpeaker must recognize the id shown in the transcript");++ const embedding = identifier.getSpeakerEmbedding("speaker_2");+ assert.ok(embedding, "profile persistence needs the cluster embedding");++ const again = identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });+ assert.equal(again.displayName, "Carol", "the manual name must carry to later speech");+});++test("stop() state keys match the resolved speaker ids", async () => {+ const { LiveSpeakerIdentifier } = loadIdentifier();+ const identifier = new LiveSpeakerIdentifier();++ seedMergedSession(identifier);+ identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });++ const state = identifier.getTransientState();+ assert.deepEqual(+ Object.keys(state).sort(),+ ["speaker_0", "speaker_1", "speaker_2"],+ "post-meeting reconciliation looks mappings up by these keys"+ );+});++test("mapSpeaker on an unknown id fails loudly", () => {+ const { LiveSpeakerIdentifier, warnings } = loadIdentifier();+ const identifier = new LiveSpeakerIdentifier();++ identifier.setMaxSpeakers(3);+ identifier._resolveSpeakerForEmbedding(voiceA, { updateCentroid: true });++ const mapped = identifier.mapSpeaker("speaker_9", 1, "Alice", null);+ assert.equal(mapped, false);+ assert.ok(+ warnings.some((w) => /speaker/i.test(w.message)),+ "a dropped manual identification must leave a trace in the logs"+ );+});++test("distinct voices are folded into one cluster when the session cap is 1", () => {+ const { LiveSpeakerIdentifier } = loadIdentifier();+ const identifier = new LiveSpeakerIdentifier();+ identifier.setMaxSpeakers(1);++ const first = identifier._resolveSpeakerForEmbedding(voiceA, { updateCentroid: true });+ const second = identifier._resolveSpeakerForEmbedding(voiceB, { updateCentroid: true });++ assert.equal(cosineSimilarity(voiceA, voiceB), 0);+ assert.equal(+ second.speakerId,+ first.speakerId,+ "at the cap, new voices are force-merged into the nearest cluster by design"+ );+});diff --git a/test/helpers/participants.test.js b/test/helpers/participants.test.jsnew file mode 100644index 000000000..8128f5d65--- /dev/null+++ b/test/helpers/participants.test.js@@ -0,0 +1,97 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const ts = require("typescript");++let loaded;+const load = () => {+ if (!loaded) {+ const filename = path.join(__dirname, "../../src/utils/participants.ts");+ const source = fs.readFileSync(filename, "utf8");+ const output = ts.transpileModule(source, {+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },+ }).outputText;+ loaded = import(`data:text/javascript;base64,${Buffer.from(output).toString("base64")}`);+ }+ return loaded;+};++test("participant rosters derive total speakers from non-self attendees plus the recorder", async () => {+ const { resolveParticipantExpectedSpeakerCount } = await load();+ const participants = [+ { email: "[email protected]", self: true },+ { email: "[email protected]", self: false },+ { email: "[email protected]" },+ ];++ assert.equal(resolveParticipantExpectedSpeakerCount(participants), 3);+ assert.equal(resolveParticipantExpectedSpeakerCount([participants[0]]), null);+ assert.equal(resolveParticipantExpectedSpeakerCount([]), null);+});++test("active participant changes synchronize the session count before a manual override", async () => {+ const { resolveParticipantSpeakerCountSync } = await load();++ assert.equal(+ resolveParticipantSpeakerCountSync({+ recordingNoteId: 42,+ noteId: 42,+ userTouchedStepper: false,+ currentExpectedCount: 2,+ participants: [+ { email: "[email protected]", self: false },+ { email: "[email protected]", self: false },+ ],+ }),+ 3+ );+});++test("participant changes do not override another recording, a manual count, or an unchanged count", async () => {+ const { resolveParticipantSpeakerCountSync } = await load();+ const participants = [+ { email: "[email protected]", self: false },+ { email: "[email protected]", self: false },+ ];++ assert.equal(+ resolveParticipantSpeakerCountSync({+ recordingNoteId: 7,+ noteId: 42,+ userTouchedStepper: false,+ currentExpectedCount: 2,+ participants,+ }),+ null+ );+ assert.equal(+ resolveParticipantSpeakerCountSync({+ recordingNoteId: 42,+ noteId: 42,+ userTouchedStepper: true,+ currentExpectedCount: 2,+ participants,+ }),+ null+ );+ assert.equal(+ resolveParticipantSpeakerCountSync({+ recordingNoteId: 42,+ noteId: 42,+ userTouchedStepper: false,+ currentExpectedCount: 3,+ participants,+ }),+ null+ );+});++test("participant-derived startup counts remain eligible for roster synchronization", async () => {+ const { resolveInitialSpeakerCountOverride } = await load();++ assert.equal(resolveInitialSpeakerCountOverride(3, false), false);+ assert.equal(resolveInitialSpeakerCountOverride(3, true), true);+ assert.equal(resolveInitialSpeakerCountOverride(3), true);+ assert.equal(resolveInitialSpeakerCountOverride(null), false);+});