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): Address speaker identity review findings
Chadpiha47623ee31a52
diff --git a/docs/meeting-speaker-identification-investigation.md b/docs/meeting-speaker-identification-investigation.mddeleted file mode 100644index 39562b741..000000000--- a/docs/meeting-speaker-identification-investigation.md+++ /dev/null@@ -1,205 +0,0 @@-# 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/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d6ce3fb9c..6e101e17f 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -9193,7 +9193,13 @@ class IPCHandlers {Number(payload?.expectedCount) || DEFAULT_EXPECTED_SPEAKER_COUNT));- this.activeMeetingSpeakerConfig = { enabled, expectedCount, explicit: true };+ // Only a stepper-set count is explicit; the diarization toggle reuses this+ // channel and must not freeze the count against roster-driven refreshes.+ this.activeMeetingSpeakerConfig = {+ enabled,+ expectedCount,+ explicit: payload?.countIsExplicit === true,+ };liveSpeakerIdentifier.setEnabled(enabled);// Live identification only labels other speakers (the mic track is "you"),// so cap at expectedCount - 1 to match resolveSessionMaxSpeakers().@@ -9655,7 +9661,11 @@ class IPCHandlers {profileId,displayName);- this.databaseManager.removeSpeakerMapping(bestEntry.noteId, bestEntry.speakerId);+ // Live and offline ids share one namespace now, so they often match —+ // removing the "old" row would delete the mapping just written.+ if (bestEntry.speakerId !== mappedId) {+ this.databaseManager.removeSpeakerMapping(bestEntry.noteId, bestEntry.speakerId);+ }} else if (displayName) {this.databaseManager.setSpeakerMapping(bestEntry.noteId,diff --git a/src/helpers/liveSpeakerIdentifier.js b/src/helpers/liveSpeakerIdentifier.jsindex 793436962..849e78d87 100644--- a/src/helpers/liveSpeakerIdentifier.js+++ b/src/helpers/liveSpeakerIdentifier.js@@ -134,6 +134,7 @@ 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;@@ -334,7 +335,7 @@ class LiveSpeakerIdentifier {if (!liveId || !this.transientEmbeddings.has(liveId)) {debugLogger.warn("Live speaker mapping dropped: unknown speaker id", {liveId,- displayName,+ hasDisplayName: !!displayName,knownSpeakers: [...this.transientEmbeddings.keys()],});return false;@@ -386,6 +387,7 @@ 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;@@ -758,15 +760,13 @@ 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.+ // Cluster ids double as the transcript's speaker labels. Ids freed by a+ // recluster merge are never reused: durable state (note speaker mappings,+ // the renderer's name map) may still reference them, and a recycled id would+ // let a new voice inherit the previous person's identity._assignSpeakerId(embedding) {- let index = 0;- while (this.transientEmbeddings.has(`speaker_${index}`)) {- index += 1;- }- const speakerId = `speaker_${index}`;+ const speakerId = `speaker_${this.nextLiveIndex}`;+ this.nextLiveIndex += 1;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 37d35ffbf..80c21cf3b 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -472,7 +472,7 @@ export const useMeetingRecordingStore = create<MeetingRecordingState>()(() => ({export const getMicAnalyser = (): AnalyserNode | null => micAnalyser;-function pushConfig(enabled: boolean, expectedCount: number) {+function pushConfig(enabled: boolean, expectedCount: number, countIsExplicit: boolean) {if (pushConfigTimeout) clearTimeout(pushConfigTimeout);pushConfigTimeout = setTimeout(() => {(@@ -480,15 +480,19 @@ function pushConfig(enabled: boolean, expectedCount: number) {setMeetingSessionSpeakerConfig?: (config: {enabled: boolean;expectedCount: number;+ countIsExplicit: boolean;}) => void;}- )?.setMeetingSessionSpeakerConfig?.({ enabled, expectedCount });+ )?.setMeetingSessionSpeakerConfig?.({ enabled, expectedCount, countIsExplicit });}, 150);}export function setSessionDiarizationEnabled(enabled: boolean): void {useMeetingRecordingStore.setState({ sessionDiarizationEnabled: enabled });- pushConfig(enabled, useMeetingRecordingStore.getState().sessionExpectedCount);+ // The toggle only carries the count along — it is explicit solely when the+ // user has actually touched the stepper, so roster refreshes stay possible.+ const state = useMeetingRecordingStore.getState();+ pushConfig(enabled, state.sessionExpectedCount, state.userTouchedStepper);const noteId = useMeetingRecordingStore.getState().recordingNoteId;if (noteId != null) {window.electronAPI?.updateNote?.(noteId, { diarization_enabled: enabled ? 1 : 0 });@@ -501,7 +505,7 @@ export function setSessionExpectedCount(count: number): void {sessionExpectedCount: clamped,userTouchedStepper: true,});- pushConfig(useMeetingRecordingStore.getState().sessionDiarizationEnabled, clamped);+ pushConfig(useMeetingRecordingStore.getState().sessionDiarizationEnabled, clamped, true);const noteId = useMeetingRecordingStore.getState().recordingNoteId;if (noteId != null) {window.electronAPI?.updateNote?.(noteId, { expected_speaker_count: clamped });diff --git a/src/types/electron.ts b/src/types/electron.tsindex e3ef21f91..8bee03a99 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2287,6 +2287,7 @@ declare global {setMeetingSessionSpeakerConfig?: (config: {enabled: boolean;expectedCount: number;+ countIsExplicit?: boolean;}) => Promise<{ success: boolean; error?: string }>;getWhisperVadConfig?: () => Promise<{success: boolean;diff --git a/test/helpers/liveSpeakerIdentifier.test.js b/test/helpers/liveSpeakerIdentifier.test.jsindex 2966d5652..5761b70af 100644--- a/test/helpers/liveSpeakerIdentifier.test.js+++ b/test/helpers/liveSpeakerIdentifier.test.js@@ -74,19 +74,18 @@ function seedMergedSession(identifier) {return merges[0];}-test("new voice after a recluster merge reuses the freed speaker slot", () => {+test("new voice after a recluster merge gets a fresh id — freed ids are never reused", () => {const { LiveSpeakerIdentifier } = loadIdentifier();const identifier = new LiveSpeakerIdentifier();const merge = seedMergedSession(identifier);assert.equal(merge.remove, "speaker_2");+ // Durable state (note speaker mappings, NoteEditor's name map) may still+ // reference the retired id, so recycling it would let a new voice inherit+ // the previous person's identity.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"- );+ assert.equal(resolved.speakerId, "speaker_3", "ids must stay monotonic within a meeting");});test("manual identification sticks for a voice that appeared after a merge", () => {@@ -94,14 +93,14 @@ test("manual identification sticks for a voice that appeared after a merge", ()const identifier = new LiveSpeakerIdentifier();seedMergedSession(identifier);- identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });+ const resolved = 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);+ // With no remapper layer, the id the transcript shows IS the cluster id, so+ // naming it must reach the right cluster.+ const mapped = identifier.mapSpeaker(resolved.speakerId, 42, "Carol", 7);assert.equal(mapped, true, "mapSpeaker must recognize the id shown in the transcript");- const embedding = identifier.getSpeakerEmbedding("speaker_2");+ const embedding = identifier.getSpeakerEmbedding(resolved.speakerId);assert.ok(embedding, "profile persistence needs the cluster embedding");const again = identifier._resolveSpeakerForEmbedding(voiceC, { updateCentroid: true });@@ -118,7 +117,7 @@ test("stop() state keys match the resolved speaker ids", async () => {const state = identifier.getTransientState();assert.deepEqual(Object.keys(state).sort(),- ["speaker_0", "speaker_1", "speaker_2"],+ ["speaker_0", "speaker_1", "speaker_3"],"post-meeting reconciliation looks mappings up by these keys");});@@ -132,9 +131,11 @@ test("mapSpeaker on an unknown id fails loudly", () => {const mapped = identifier.mapSpeaker("speaker_9", 1, "Alice", null);assert.equal(mapped, false);+ const warning = warnings.find((w) => /speaker/i.test(w.message));+ assert.ok(warning, "a dropped manual identification must leave a trace in the logs");assert.ok(- warnings.some((w) => /speaker/i.test(w.message)),- "a dropped manual identification must leave a trace in the logs"+ !JSON.stringify(warning.data ?? {}).includes("Alice"),+ "the participant's name must not be written to the logs");});diff --git a/test/helpers/meetingSpeakerReconcile.test.js b/test/helpers/meetingSpeakerReconcile.test.jsnew file mode 100644index 000000000..3ec68ba5d--- /dev/null+++ b/test/helpers/meetingSpeakerReconcile.test.js@@ -0,0 +1,170 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const identifierModulePath = require.resolve("../../src/helpers/liveSpeakerIdentifier");+const originalLoad = Module._load;++const electronStub = {+ app: {+ getPath: () => "/tmp",+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ requestSingleInstanceLock: () => true,+ },+ ipcMain: { handle: () => {}, on: () => {}, removeHandler: () => {} },+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ },+ shell: {},+ dialog: {},+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+};++// ipcHandlers pulls in a large module graph; stub the process boundaries and+// capture broadcasts so the prototype methods can run against a fake `this`.+function loadHandlers() {+ delete require.cache[handlersModulePath];+ delete require.cache[identifierModulePath];+ const broadcasts = [];++ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") {+ return electronStub;+ }+ if (request === "./windowBroadcast" && parent?.filename === handlersModulePath) {+ return {+ broadcastToWindows: (channel, payload) => {+ broadcasts.push({ channel, payload });+ },+ };+ }+ return originalLoad.call(this, request, parent, isMain);+ };++ try {+ const IPCHandlers = require(handlersModulePath);+ const liveSpeakerIdentifier = require(identifierModulePath);+ return { IPCHandlers, liveSpeakerIdentifier, broadcasts };+ } finally {+ Module._load = originalLoad;+ }+}++function createMappingRecorder(existingMappings) {+ const calls = { set: [], remove: [] };+ const databaseManager = {+ getSpeakerMappings: () => existingMappings,+ setSpeakerMapping: (noteId, speakerId, profileId, displayName) => {+ calls.set.push({ noteId, speakerId, profileId, displayName });+ },+ removeSpeakerMapping: (noteId, speakerId) => {+ calls.remove.push({ noteId, speakerId });+ },+ };+ return { calls, databaseManager };+}++const NOTE_ID = 42;+const embedding = Array.from({ length: 8 }, (_, i) => (i === 0 ? 1 : 0));++function reconcile(IPCHandlers, databaseManager, liveSpeakerId) {+ const fakeThis = Object.assign(Object.create(IPCHandlers.prototype), { databaseManager });+ const liveState = {+ [liveSpeakerId]: {+ displayName: "Alice",+ profileId: 5,+ noteId: NOTE_ID,+ embedding,+ },+ };+ const segments = [];+ return IPCHandlers.prototype._reconcileLiveSpeakerState.call(+ fakeThis,+ liveState,+ { speaker_0: embedding },+ segments+ );+}++test("reconciliation keeps the mapping when live and offline ids already match", () => {+ const { IPCHandlers } = loadHandlers();+ const { calls, databaseManager } = createMappingRecorder([+ { speaker_id: "speaker_0", display_name: "Alice", profile_id: 5 },+ ]);++ reconcile(IPCHandlers, databaseManager, "speaker_0");++ assert.equal(calls.set.length, 1);+ assert.deepEqual(calls.set[0], {+ noteId: NOTE_ID,+ speakerId: "speaker_0",+ profileId: 5,+ displayName: "Alice",+ });+ assert.deepEqual(+ calls.remove,+ [],+ "removing the row that was just upserted deletes the user's identification"+ );+});++test("reconciliation migrates the mapping when the offline id differs", () => {+ const { IPCHandlers } = loadHandlers();+ const { calls, databaseManager } = createMappingRecorder([+ { speaker_id: "speaker_3", display_name: "Alice", profile_id: 5 },+ ]);++ reconcile(IPCHandlers, databaseManager, "speaker_3");++ assert.equal(calls.set.length, 1);+ assert.equal(calls.set[0].speakerId, "speaker_0");+ assert.deepEqual(calls.remove, [{ noteId: NOTE_ID, speakerId: "speaker_3" }]);+});++function refreshConfig(explicit) {+ const { IPCHandlers, liveSpeakerIdentifier, broadcasts } = loadHandlers();+ const fakeThis = Object.assign(Object.create(IPCHandlers.prototype), {+ activeMeetingSpeakerConfig: { enabled: true, expectedCount: 2, explicit },+ _activeMeetingNoteId: NOTE_ID,+ databaseManager: { getGoogleAccounts: () => [] },+ });+ const note = {+ participants: JSON.stringify([+ { email: "[email protected]" },+ { email: "[email protected]" },+ { email: "[email protected]" },+ ]),+ };++ IPCHandlers.prototype._refreshMeetingSpeakerConfigFromNote.call(fakeThis, NOTE_ID, note);+ return { fakeThis, liveSpeakerIdentifier, broadcasts };+}++test("roster changes refresh an auto-derived speaker config", () => {+ const { fakeThis, liveSpeakerIdentifier, broadcasts } = refreshConfig(false);++ assert.equal(fakeThis.activeMeetingSpeakerConfig.expectedCount, 4);+ assert.equal(liveSpeakerIdentifier.maxSpeakers, 3);+ assert.equal(broadcasts.length, 1);+ assert.equal(broadcasts[0].channel, "meeting-session-speaker-config-updated");+ assert.deepEqual(broadcasts[0].payload, { enabled: true, expectedCount: 4 });+});++test("an explicit stepper count is never overridden by roster changes", () => {+ const { fakeThis, broadcasts } = refreshConfig(true);++ assert.equal(fakeThis.activeMeetingSpeakerConfig.expectedCount, 2);+ assert.deepEqual(broadcasts, []);+});