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 echo-deduped mic rows from saving epoch timestamps (#2791)
Chad Piha26b320d364e0
diff --git a/src/helpers/diarization.js b/src/helpers/diarization.jsindex be72f7932..fb1b9a7bb 100644--- a/src/helpers/diarization.js+++ b/src/helpers/diarization.js@@ -23,34 +23,11 @@ const {} = require("./transcriptionTimeout");const DIARIZATION_TIMEOUT_MS = 3600000; // 60 minutes-const POST_MERGE_CONTEXT_WINDOW_MS = 6000;-const POST_MERGE_CONTEXT_MERGE_LIMIT = 3;--const dedupeMicAgainstSystem = (segments) => {- const systemSegments = segments.filter((seg) => seg.source === "system" && seg.text);- if (!systemSegments.length) return segments;-- return segments.filter((seg) => {- if (seg.source !== "mic" || !seg.text) return true;- if (- !seg.likelyRenderBleed &&- !seg.hasBleedEvidence &&- seg.suppressionReason !== "double_talk"- ) {- return true;- }-- const matcher =- seg.suppressionReason === "double_talk" ? transcriptsLooselyOverlap : transcriptsOverlap;- const candidates = buildMergedCandidates({- segments: systemSegments,- timestamp: seg.timestamp,- windowMs: POST_MERGE_CONTEXT_WINDOW_MS,- mergeLimit: POST_MERGE_CONTEXT_MERGE_LIMIT,- });- return !candidates.some((candidateText) => matcher(seg.text, candidateText));- });-};+// splitMicEchoDuplicates runs on timestamps already normalized to seconds from+// the start of the recording, so this window is in seconds too, though+// buildMergedCandidates calls it windowMs.+const ECHO_DUPLICATE_WINDOW_S = 6;+const ECHO_DUPLICATE_MERGE_LIMIT = 3;const SEGMENTATION_MODEL_URL ="https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/sherpa-onnx-pyannote-segmentation-3-0.tar.bz2";@@ -430,6 +407,39 @@ class DiarizationManager {return segments;}+ // Splits out echo-flagged mic segments whose text matches nearby system audio.+ // `removed` holds the same objects that were passed in, so callers can map+ // them back to their original rows.+ splitMicEchoDuplicates(segments) {+ const systemSegments = segments.filter((seg) => seg.source === "system" && seg.text);+ if (!systemSegments.length) return { kept: segments, removed: [] };++ const kept = [];+ const removed = [];+ for (const seg of segments) {+ if (+ seg.source !== "mic" ||+ !seg.text ||+ (!seg.likelyRenderBleed && !seg.hasBleedEvidence && seg.suppressionReason !== "double_talk")+ ) {+ kept.push(seg);+ continue;+ }++ const matcher =+ seg.suppressionReason === "double_talk" ? transcriptsLooselyOverlap : transcriptsOverlap;+ const candidates = buildMergedCandidates({+ segments: systemSegments,+ timestamp: seg.timestamp,+ windowMs: ECHO_DUPLICATE_WINDOW_S,+ mergeLimit: ECHO_DUPLICATE_MERGE_LIMIT,+ });+ const isEcho = candidates.some((candidateText) => matcher(seg.text, candidateText));+ (isEcho ? removed : kept).push(seg);+ }+ return { kept, removed };+ }+capSpeakerClusters(segments, cap) {if (!cap || !segments?.length) return segments;const totals = new Map();@@ -444,15 +454,16 @@ class DiarizationManager {return segments.map((s) => (keep.has(s.speaker) ? s : { ...s, speaker: primary }));}+ // Expects echo duplicates already removed with splitMicEchoDuplicates, so+ // the caller can report them to the renderer.mergeWithTranscript(transcriptSegments,diarizationSegments,{ diarizedSource = "system", speakerIndexBase = 0 } = {}) {if (!transcriptSegments || transcriptSegments.length === 0) return [];- const deduped = dedupeMicAgainstSystem(transcriptSegments);if (!diarizationSegments || diarizationSegments.length === 0) {- return deduped.map((seg) => ({ ...seg }));+ return transcriptSegments.map((seg) => ({ ...seg }));}// Renumber clusters (speaker_00 → speaker_0), offset past a resumed note's ids.@@ -465,8 +476,8 @@ class DiarizationManager {const micSingleCluster = diarizedSource === "mic" && speakerSet.size === 1;const nextTimestampAt = (startIndex, source) => {- for (let i = startIndex + 1; i < deduped.length; i += 1) {- const candidate = deduped[i];+ for (let i = startIndex + 1; i < transcriptSegments.length; i += 1) {+ const candidate = transcriptSegments[i];if (candidate.source === source && candidate.timestamp != null) {return candidate.timestamp;}@@ -474,7 +485,7 @@ class DiarizationManager {return null;};- return deduped.map((seg, index) => {+ return transcriptSegments.map((seg, index) => {const enriched = { ...seg };if (seg.source === "mic" && (diarizedSource !== "mic" || micSingleCluster)) {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex a564b97f5..51dd583ee 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -7295,6 +7295,9 @@ class IPCHandlers {removed.push(meetingDiarizationSegments[index]);meetingDiarizationSegments.splice(index, 1);}+ // The renderer stops applying retracts once a stop begins, so the+ // diarization result must name them for its persisted copy (#2781).+ meetingRetractedMicSegments.push(...removed);return removed;};@@ -7454,6 +7457,7 @@ class IPCHandlers {const micStartedAt = meetingMicDiarizationStartedAt;const systemAudioHeard = meetingSystemAudioHeard;const diarizationSegments = meetingDiarizationSegments;+ const retractedSegments = meetingRetractedMicSegments;if (meetingDiarizationStream) {await new Promise((resolve) => meetingDiarizationStream.end(resolve));meetingDiarizationStream = null;@@ -7469,6 +7473,7 @@ class IPCHandlers {meetingSystemAudioHeard = false;meetingSystemAudioHandover.reset();meetingDiarizationSegments = [];+ meetingRetractedMicSegments = [];const { pcmPath, startedAt, diarizedSource, cleanupPcmPaths } = resolveDiarizationInput({systemPcmPath,micPcmPath,@@ -7482,6 +7487,7 @@ class IPCHandlers {return {diarizationPcmPath: pcmPath,diarizationSegments,+ retractedSegments,diarizationStartedAt: startedAt,diarizedSource,};@@ -8042,6 +8048,7 @@ class IPCHandlers {let meetingSystemAudioHeard = false;const meetingSystemAudioHandover = createMeetingSystemAudioHandover();let meetingDiarizationSegments = [];+ let meetingRetractedMicSegments = [];let meetingLiveSpeakerActive = false;let meetingLiveSpeakerState = null;let meetingLiveSpeakerStartedAt = null;@@ -8655,6 +8662,7 @@ class IPCHandlers {meetingSystemAudioHeard = false;meetingSystemAudioHandover.reset();meetingDiarizationSegments = [];+ meetingRetractedMicSegments = [];meetingLocalWin = null;meetingLocalTranscript = "";meetingLocalProvider = null;@@ -9647,8 +9655,13 @@ class IPCHandlers {debugLogger.error("Local meeting final transcription failed", { error: err.message });}flushPendingMicFinals(true);- const { diarizationPcmPath, diarizationSegments, diarizationStartedAt, diarizedSource } =- await captureMeetingDiarizationState();+ const {+ diarizationPcmPath,+ diarizationSegments,+ retractedSegments,+ diarizationStartedAt,+ diarizedSource,+ } = await captureMeetingDiarizationState();const transcript =buildOrderedTranscriptText(diarizationSegments) || meetingLocalTranscript;const sessionSpeakerConfigSnapshot = this.activeMeetingSpeakerConfig;@@ -9668,15 +9681,21 @@ class IPCHandlers {sessionSpeakerConfigSnapshot,noteIdSnapshot,diarizedSource,- speakerIndexBaseSnapshot+ speakerIndexBaseSnapshot,+ retractedSegments);return { success: true, transcript, diarizationSessionId };}const results = await disconnectMeetingStreaming({ flushPending: true });- const { diarizationPcmPath, diarizationSegments, diarizationStartedAt, diarizedSource } =- await captureMeetingDiarizationState();+ const {+ diarizationPcmPath,+ diarizationSegments,+ retractedSegments,+ diarizationStartedAt,+ diarizedSource,+ } = await captureMeetingDiarizationState();const transcript =buildOrderedTranscriptText(diarizationSegments) ||[results[0]?.text, results[1]?.text].filter(Boolean).join(" ");@@ -9697,7 +9716,8 @@ class IPCHandlers {sessionSpeakerConfigSnapshot,noteIdSnapshot,diarizedSource,- speakerIndexBaseSnapshot+ speakerIndexBaseSnapshot,+ retractedSegments);return { success: true, transcript, diarizationSessionId };@@ -13043,23 +13063,60 @@ class IPCHandlers {sessionConfig = null,noteId = null,diarizedSource = "system",- speakerIndexBase = 0+ speakerIndexBase = 0,+ retractedSegments = []) {+ const startMs =+ (Number.isFinite(audioStartedAt) && audioStartedAt) ||+ transcriptSegments.find((segment) => segment.source === diarizedSource)?.timestamp ||+ transcriptSegments[0]?.timestamp ||+ 0;+ const isEpochMs = startMs > 1e9;+ const normalized = transcriptSegments.map((seg) => ({+ ...seg,+ timestamp:+ seg.timestamp != null+ ? isEpochMs+ ? (seg.timestamp - startMs) / 1000+ : seg.timestamp+ : undefined,+ }));++ // Split before any send so diarized, skipped and failed runs drop the same+ // echo rows.+ const { kept, removed: echoDuplicates } = this.diarizationManager?.splitMicEchoDuplicates(+ normalized+ ) ?? { kept: normalized, removed: [] };+ const echoDuplicateSet = new Set(echoDuplicates);+ const isEchoDuplicate = (index) => echoDuplicateSet.has(normalized[index]);+ // Rows main dropped that the renderer may still hold in the transcript it+ // persisted at stop. Raw (epoch-ms) timestamps, matching that copy (#2781).+ const removedSegments = [+ ...retractedSegments,+ ...transcriptSegments.filter((_, index) => isEchoDuplicate(index)),+ ].map(({ text, source, timestamp }) => ({ text, source, timestamp }));const send = (payload) => {if (win && !win.isDestroyed()) {- win.webContents.send("meeting-diarization-complete", { sessionId, noteId, ...payload });+ win.webContents.send("meeting-diarization-complete", {+ sessionId,+ noteId,+ ...payload,+ removedSegments,+ });}};+ // Raw rows, sent when there is no diarization to merge.+ const sendUndiarized = () =>+ send({+ segments: transcriptSegments+ .map((segment, index) => ({ ...segment, id: segment.id || `segment-${index}` }))+ .filter((_, index) => !isEchoDuplicate(index)),+ });const diarizationEnabled = (sessionConfig?.enabled ?? this.speakerDiarizationEnabled) !== false;if (!diarizationEnabled || !this.diarizationManager?.isAvailable() || !rawPcmPath) {- send({- segments: transcriptSegments.map((segment, index) => ({- ...segment,- id: segment.id || `segment-${index}`,- })),- });+ sendUndiarized();return;}@@ -13110,24 +13167,8 @@ class IPCHandlers {);}- const startMs =- (Number.isFinite(audioStartedAt) && audioStartedAt) ||- transcriptSegments.find((segment) => segment.source === diarizedSource)?.timestamp ||- transcriptSegments[0]?.timestamp ||- 0;- const isEpochMs = startMs > 1e9;- const normalized = transcriptSegments.map((seg) => ({- ...seg,- timestamp:- seg.timestamp != null- ? isEpochMs- ? (seg.timestamp - startMs) / 1000- : seg.timestamp- : undefined,- }));-const enrichedSegments = this.diarizationManager.mergeWithTranscript(- normalized,+ kept,diarizationSegments,{ diarizedSource, speakerIndexBase });@@ -13246,7 +13287,9 @@ class IPCHandlers {} catch (err) {debugLogger.warn("Background diarization failed", { error: err.message });this._diarizationSpeakerReservations.delete(sessionId);- send({ segments: [] });+ // The renderer only applies removedSegments alongside segments, so a+ // failed run falls back to the skip result rather than an empty one.+ sendUndiarized();} finally {try {fs.unlinkSync(rawPcmPath);diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.tsindex e8f595280..e03f42c16 100644--- a/src/stores/meetingRecordingStore.ts+++ b/src/stores/meetingRecordingStore.ts@@ -33,14 +33,17 @@ import { isTranscriptionContextAllowed } from "./policyRules";import { usePolicyStore } from "./policyStore";import {lockTranscriptSpeaker,- mergeTranscriptSegments,normalizeTranscriptSegment,serializeTranscriptSegments,type TranscriptSpeakerLockSource,type TranscriptSpeakerStatus,} from "../utils/transcriptSpeakerState";import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";-import { resolveDiarizationTarget, selectBaseSegments } from "../utils/diarizationCompletion";+import {+ mergeSessionDiarization,+ resolveDiarizationTarget,+ selectBaseSegments,+} from "../utils/diarizationCompletion";import { createSerialQueue } from "../utils/serialQueue";import { reduceMeetingSegmentEvent, type MeetingSegmentEvent } from "./meetingSegmentReducer";import {@@ -427,7 +430,12 @@ let segmentsRefValue: TranscriptSegment[] = [];// session's diarization covers only its own audio, so its result must not be// matched against the seeded rows. Keyed by diarization session at stop.let sessionSeedLength = 0;-const seedLengthByDiarizationSession = new Map<string, number>();+const seedLengthByDiarizationSession = new Map<+ string,+ { noteId: number | null; seedLength: number }+>();+// The stopping session's seed, until its stop call returns and keys it above.+let stoppingSeed: { noteId: number | null; seedLength: number } | null = null;let preparePromise: Promise<void> | null = null;let ipcCleanups: Array<() => void> = [];let speakerIdentifications: SpeakerIdentification[] = [];@@ -1701,17 +1709,20 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRecpersist: persistTranscript,fallbackTranscript: () => useMeetingRecordingStore.getState().transcript,stop: async () => {+ // Set before cleanup's awaits: the final transcript write is already+ // posted, so an earlier session's result can land from here on.+ const seed = { noteId: recordingNoteId, seedLength: sessionSeedLength };+ stoppingSeed = seed;await cleanup();let stoppedDiarizationSessionId: string | null = null;- const seedLength = sessionSeedLength;try {const result = await window.electronAPI?.meetingTranscriptionStop?.(sessionId ?? undefined);if (result?.diarizationSessionId) {stoppedDiarizationSessionId = result.diarizationSessionId;- seedLengthByDiarizationSession.set(stoppedDiarizationSessionId, seedLength);+ seedLengthByDiarizationSession.set(stoppedDiarizationSessionId, seed);useMeetingRecordingStore.setState({diarizationSessionId: stoppedDiarizationSessionId,});@@ -1728,6 +1739,8 @@ export async function stopRecording(expectedSessionId?: string): Promise<StopRec{ error: (err as Error).message },"meeting");+ } finally {+ stoppingSeed = null;}return stoppedDiarizationSessionId;},@@ -1839,7 +1852,7 @@ if (typeof window !== "undefined") {// Read after the getNote await: a skipped diarization is sent before the// stop call that records this session's seed length returns.const seedLength = data.sessionId- ? (seedLengthByDiarizationSession.get(data.sessionId) ?? 0)+ ? (seedLengthByDiarizationSession.get(data.sessionId)?.seedLength ?? 0): 0;if (data.sessionId) seedLengthByDiarizationSession.delete(data.sessionId);// No note means no safe base to merge into, and writing to a deleted one@@ -1858,18 +1871,21 @@ if (typeof window !== "undefined") {recordingNoteId,targetNoteId,});- const seededCount = Math.min(seedLength, existing.length);- const enriched = [- ...existing.slice(0, seededCount),- ...mergeTranscriptSegments(- existing.slice(seededCount),- data.segments.map((segment, index) => ({- ...segment,- id: segment.id || `diarized-${index}`,- }))- ),- ];+ const { segments: enriched, removedCount } = mergeSessionDiarization({+ existing,+ seedLength,+ segments: data.segments,+ removedSegments: data.removedSegments,+ });+ // A later session resumed from this note seeded the rows about to be+ // removed, so its seed ends that many rows earlier once this write lands.+ // Only sessions whose final write is already posted count: one posted+ // after this write puts the rows back.+ const laterSeeds = [...seedLengthByDiarizationSession.values(), stoppingSeed].filter(+ (pending): pending is NonNullable<typeof stoppingSeed> =>+ pending?.noteId === targetNoteId && pending.seedLength > seedLength+ );try {// Awaited so the next queued completion's getNote is guaranteed to// read this write — without it the ordering depends on db-update-note@@ -1881,6 +1897,7 @@ if (typeof window !== "undefined") {publish([]);throw error;}+ for (const pending of laterSeeds) pending.seedLength -= removedCount;publish(enriched);if (data.speakerEmbeddings) {diff --git a/src/types/electron.ts b/src/types/electron.tsindex fd9b2b096..44d7d480d 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -6,6 +6,7 @@ import type { UsageResponse } from "../lib/usageStore";import type { OrgPolicy } from "./policy";import type { TechnicalErrorDetailsData } from "../components/ui/useToast";import type { ProviderSettingsTarget } from "../utils/describeProviderError";+import type { RemovedTranscriptSegment } from "../utils/diarizationCompletion";import type {ManagedEnterpriseConfig,ManagedEnterpriseRequestContext,@@ -3387,6 +3388,7 @@ declare global {speakerLockSource?: "user" | "diarization" | "suggestion";}>;speakerEmbeddings?: Record<string, number[]> | null;+ removedSegments?: RemovedTranscriptSegment[];}) => void) => () => void;diff --git a/src/utils/diarizationCompletion.ts b/src/utils/diarizationCompletion.tsindex 08fa65f33..6e767bba9 100644--- a/src/utils/diarizationCompletion.ts+++ b/src/utils/diarizationCompletion.ts@@ -1,3 +1,6 @@+import type { TranscriptSegment } from "../stores/meetingRecordingStore";+import { mergeTranscriptSegments } from "./transcriptSpeakerState";+// Routing rules for meeting-diarization-complete events (issue #1495): a result// must be persisted to the note that owns the recording session, never to// whichever note happens to be rendered when the event arrives.@@ -51,3 +54,61 @@ export function selectBaseSegments<Segment>(params: {if (recordingNoteId === targetNoteId && liveSegments.length > 0) return liveSegments;return [];}++export interface RemovedTranscriptSegment {+ text: string;+ source: "mic" | "system";+ timestamp?: number;+}++// Main drops echo duplicates and late retracts from its copy, so its result+// never matches those rows and the merge would keep them with their raw+// epoch-ms timestamps and no speaker (#2781). Matches on source, timestamp and+// exact text like a live retract, but removes only one persisted row per+// removed entry.+export function withoutRemovedSegments<+ Segment extends { text: string; source: string; timestamp?: number },+>(segments: Segment[], removed: RemovedTranscriptSegment[] | undefined): Segment[] {+ if (!removed?.length) return segments;++ const keyOf = (segment: Segment | RemovedTranscriptSegment): string =>+ `${segment.source}|${segment.timestamp ?? ""}|${segment.text}`;+ const pending = new Map<string, number>();+ for (const segment of removed) {+ const key = keyOf(segment);+ pending.set(key, (pending.get(key) ?? 0) + 1);+ }++ return segments.filter((segment) => {+ const key = keyOf(segment);+ const count = pending.get(key) ?? 0;+ if (count === 0) return true;+ pending.set(key, count - 1);+ return false;+ });+}++// Merges main's result into this session's rows only: the first `seedLength`+// rows are a resumed note's earlier sessions and stay as saved. `removedCount`+// is how many of this session's rows were dropped.+export function mergeSessionDiarization(params: {+ existing: TranscriptSegment[];+ seedLength: number;+ segments: Array<Omit<TranscriptSegment, "id"> & { id?: string }>;+ removedSegments?: RemovedTranscriptSegment[];+}): { segments: TranscriptSegment[]; removedCount: number } {+ const { existing, seedLength, segments, removedSegments } = params;+ const seededCount = Math.min(seedLength, existing.length);+ const sessionRows = existing.slice(seededCount);+ const keptRows = withoutRemovedSegments(sessionRows, removedSegments);+ return {+ segments: [+ ...existing.slice(0, seededCount),+ ...mergeTranscriptSegments(+ keptRows,+ segments.map((segment, index) => ({ ...segment, id: segment.id || `diarized-${index}` }))+ ),+ ],+ removedCount: sessionRows.length - keptRows.length,+ };+}diff --git a/test/helpers/apiKeyUpdatesIpc.test.js b/test/helpers/apiKeyUpdatesIpc.test.jsindex 863bd9a02..ace0e1521 100644--- a/test/helpers/apiKeyUpdatesIpc.test.js+++ b/test/helpers/apiKeyUpdatesIpc.test.js@@ -50,6 +50,7 @@ const environmentManager = Object.fromEntries(// only when it opens the socket (one already open or opening wins), cleanup// forgets both, and connect rides a warm socket when one is there.class FakeStreaming {+ completedSegments = [];warmToken = null;warmConnectionOptions = null;cachedToken = null;@@ -165,6 +166,7 @@ test.after(() => {// Loaded after the electron stub above, and shared with ipcHandlers so tests can mock it.const liveSpeakerIdentifier = require("../../src/helpers/liveSpeakerIdentifier");+const MeetingEchoLeakDetector = require("../../src/helpers/meetingEchoLeakDetector");function anything() {return new Proxy(function () {}, {@@ -592,18 +594,19 @@ test("a prepare after a mid-meeting renewal leaves the live meeting alone", asyn});// Main's base (past the note's stored ids), not the renderer's, numbers the live-// identifier, reaches the renderer, and is what each stop path hands diarization.+// identifier, reaches the renderer, and is what each stop path hands diarization+// beside the meeting's retracts (none here).for (const options of [{ provider: "local" }, { provider: "deepgram-realtime", mode: "byok" }]) {test(`${options.provider}: a meeting's speaker index base reaches live identification, the renderer and diarization`, async (t) => {resetMeeting(t);invoke("save-deepgram-key", "A");const requestedBases = [];- const diarizedBases = [];+ const diarized = [];target._resolveMeetingSpeakerIndexBase = (_noteId, requestedBase) => {requestedBases.push(requestedBase);return 6;};- target._startOrSkipDiarization = (...args) => diarizedBases.push(args[9]);+ target._startOrSkipDiarization = (...args) => diarized.push(args.slice(9));t.after(() => {delete target._resolveMeetingSpeakerIndexBase;delete target._startOrSkipDiarization;@@ -617,6 +620,43 @@ for (const options of [{ provider: "local" }, { provider: "deepgram-realtime", massert.deepEqual(requestedBases, [3]);assert.equal(liveStart.mock.calls[0].arguments[1].speakerIndexBase, 6);assert.equal(result.speakerIndexBase, 6);- assert.deepEqual(diarizedBases, [6]);+ assert.deepEqual(diarized, [[6, []]]);});}++// The renderer stops applying retracts once a stop begins, so main hands each+// meeting's retracted mic rows to its diarization and starts the next one empty.+test("a mic row retracted during a meeting reaches that meeting's diarization only", async (t) => {+ resetMeeting(t);+ invoke("save-deepgram-key", "A");+ const retracted = [];+ target._startOrSkipDiarization = (...args) => retracted.push(args[10]);+ t.after(() => delete target._startOrSkipDiarization);+ t.mock.method(MeetingEchoLeakDetector.prototype, "shouldSuppressMicSegment", () => ({+ suppress: false,+ hasBleedEvidence: true,+ }));+ const options = { provider: "deepgram-realtime", mode: "byok" };+ const text = "sounds good to me";++ assert.equal((await invoke("meeting-transcription-start", options)).success, true);+ const [mic, system] = meetingStreams();+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() });+ const timestamp = Date.now();+ mic.onFinalTranscript(text, timestamp);+ // A bleed-flagged mic row commits only after the risky-mic holdback.+ t.mock.timers.tick(3000);+ system.onFinalTranscript(text, timestamp + 500);+ t.mock.timers.reset();+ assert.equal((await invoke("meeting-transcription-stop")).success, true);++ assert.equal((await invoke("meeting-transcription-start", options)).success, true);+ assert.equal((await invoke("meeting-transcription-stop")).success, true);++ assert.deepEqual(+ retracted.map((segments) =>+ segments.map((segment) => [segment.source, segment.text, segment.timestamp])+ ),+ [[["mic", text, timestamp]], []]+ );+});diff --git a/test/helpers/diarizationSpeakerMerge.test.js b/test/helpers/diarizationSpeakerMerge.test.jsindex df45d3310..db767710a 100644--- a/test/helpers/diarizationSpeakerMerge.test.js+++ b/test/helpers/diarizationSpeakerMerge.test.js@@ -145,14 +145,15 @@ test("mic mode leaves system segments unlabeled", () => {test("mic mode still dedupes bleed-flagged mic echoes of system text first", () => {const manager = new DiarizationManager();+ const { kept } = manager.splitMicEchoDuplicates([+ systemSegment(10, "the quarterly revenue forecast slipped again"),+ {+ ...micSegment(10.5, "the quarterly revenue forecast slipped again"),+ likelyRenderBleed: true,+ },+ ]);const merged = manager.mergeWithTranscript(- [- systemSegment(10, "the quarterly revenue forecast slipped again"),- {- ...micSegment(10.5, "the quarterly revenue forecast slipped again"),- likelyRenderBleed: true,- },- ],+ kept,[{ start: 0, end: 5, speaker: "speaker_00" },{ start: 10, end: 20, speaker: "speaker_01" },diff --git a/test/helpers/meetingDiarizationEpochTimestamps.test.js b/test/helpers/meetingDiarizationEpochTimestamps.test.jsnew file mode 100644index 000000000..bf59a6453--- /dev/null+++ b/test/helpers/meetingDiarizationEpochTimestamps.test.js@@ -0,0 +1,225 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const Module = require("node:module");+const os = require("node:os");++const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");+const originalLoad = Module._load;++// ipcHandlers and diarization.js reach for electron at load time; speaker+// embeddings stay off so the diarized path needs no ONNX worker.+Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "electron") {+ return {+ app: {+ getPath: () => os.tmpdir(),+ getAppPath: () => process.cwd(),+ getName: () => "test",+ getVersion: () => "0.0.0",+ isPackaged: false,+ on: () => {},+ },+ ipcMain: { handle: () => {}, on: () => {}, removeHandler: () => {} },+ net: {},+ BrowserWindow: class BrowserWindow {+ static getAllWindows() {+ return [];+ }+ },+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },+ systemPreferences: { getMediaAccessStatus: () => "granted" },+ session: { fromPartition: () => ({}) },+ shell: {},+ dialog: {},+ clipboard: {},+ nativeImage: {},+ globalShortcut: {},+ utilityProcess: {},+ MessageChannelMain: class {},+ };+ }+ if (parent?.filename === handlersModulePath && request === "./speakerEmbeddings") {+ return { isAvailable: () => false };+ }+ return originalLoad.call(this, request, parent, isMain);+};++const IPCHandlers = require(handlersModulePath);+const DiarizationManager = require("../../src/helpers/diarization.js");+const { mergeSessionDiarization } = require("../../src/utils/diarizationCompletion.ts");+const { parseTranscriptSegments } = require("../../src/utils/parseTranscriptSegments.ts");+const { serializeTranscriptSegments } = require("../../src/utils/transcriptSpeakerState.ts");++test.after(() => {+ Module._load = originalLoad;+});++// #2781: a few mic rows were saved with epoch-ms timestamps and no speaker.+// Live segments carry Date.now() timestamps; main normalizes its copy to+// seconds, and the renderer merges main's result onto the transcript it+// persisted at stop.++const START_MS = 1792414000000;++// Runs main's real _startOrSkipDiarization and resolves with the payload it+// sends. `outcome` picks the diarized, skipped or failed path.+const runMainDiarization = (mainSegments, { retracted = [], outcome = "diarized" } = {}) =>+ new Promise((resolve) => {+ const diarizationManager = new DiarizationManager();+ diarizationManager.isAvailable = () => outcome !== "skipped";+ diarizationManager.convertRawPcmToWav = async () => {+ if (outcome === "failed") throw new Error("Raw PCM file is empty");+ return "/nonexistent/diarization.wav";+ };+ diarizationManager.diarize = async () => [{ start: 0, end: 120, speaker: "speaker_00" }];++ const handlers = Object.create(IPCHandlers.prototype);+ Object.assign(handlers, {+ diarizationManager,+ speakerDiarizationEnabled: true,+ _diarizationSpeakerReservations: new Map(),+ _resolveSpeakerExpectation: () => ({ numSpeakers: 0, cap: null }),+ _reconcileLiveSpeakerState: () => new Map(),+ });+ const win = {+ isDestroyed: () => false,+ webContents: { send: (_channel, payload) => resolve(payload) },+ };++ handlers._startOrSkipDiarization(+ "diar-1",+ "/nonexistent/meeting.pcm",+ START_MS,+ mainSegments,+ win,+ null,+ null,+ 1,+ "system",+ 0,+ retracted+ );+ });++// The renderer's meeting-diarization-complete listener, from the transcript it+// persisted at stop (serialized and read back from the note).+const runRendererCompletion = (live, payload, seed = []) => {+ assert.ok(payload.segments.length > 0, "the renderer ignores removedSegments without segments");+ const existing = parseTranscriptSegments(serializeTranscriptSegments([...seed, ...live]));+ return mergeSessionDiarization({+ existing,+ seedLength: seed.length,+ segments: payload.segments,+ removedSegments: payload.removedSegments,+ }).segments;+};++const stripIds = (segments) => segments.map(({ id: _id, ...segment }) => segment);+const rows = (segments) => segments.map((segment) => [segment.source, segment.text]);++const assertNoEpochTimestamps = (segments) => {+ for (const segment of segments) {+ assert.ok(+ segment.timestamp == null || segment.timestamp < 1e9,+ `segment "${segment.text}" (${segment.source}) kept epoch timestamp ${segment.timestamp}`+ );+ }+};++const echoed = "let's ship the pricing page on friday";+const liveWithEcho = [+ { id: "seg-1", source: "mic", text: "morning everyone", timestamp: START_MS + 2000 },+ { id: "seg-2", source: "system", text: echoed, timestamp: START_MS + 10000 },+ // Released after holdback with no live match, then confirmed as echo by the+ // post-session dedupe.+ {+ id: "seg-3",+ source: "mic",+ text: echoed,+ timestamp: START_MS + 11000,+ hasBleedEvidence: true,+ },+];++test("a bleed-flagged mic segment that duplicates system text never keeps its epoch timestamp", async () => {+ const payload = await runMainDiarization(stripIds(liveWithEcho));+ const merged = runRendererCompletion(liveWithEcho, payload);++ assertNoEpochTimestamps(merged);+ assert.deepEqual(rows(merged), [+ ["mic", "morning everyone"],+ ["system", echoed],+ ]);+ assert.ok(merged.every((segment) => segment.speaker));+});++const racing = "sounds good to me";+// During disconnect a system final retracted seg-2 in main; the retract event+// arrived after the renderer's stop and was ignored.+const liveWithLateRetract = [+ { id: "seg-1", source: "system", text: "any objections", timestamp: START_MS + 1000 },+ { id: "seg-2", source: "mic", text: racing, timestamp: START_MS + 4000 },+];+const mainAfterLateRetract = [+ { source: "system", text: "any objections", timestamp: START_MS + 1000 },+ { source: "system", text: racing, timestamp: START_MS + 4500 },+];+const lateRetracts = [{ source: "mic", text: racing, timestamp: START_MS + 4000 }];++test("a mic segment retracted after the renderer stopped listening is removed from the note", async () => {+ const payload = await runMainDiarization(mainAfterLateRetract, { retracted: lateRetracts });+ const merged = runRendererCompletion(liveWithLateRetract, payload);++ assertNoEpochTimestamps(merged);+ assert.deepEqual(rows(merged), [+ ["system", "any objections"],+ ["system", racing],+ ]);+});++for (const outcome of ["skipped", "failed"]) {+ test(`${outcome} diarization still drops echo duplicates and late retracts`, async () => {+ const echoPayload = await runMainDiarization(stripIds(liveWithEcho), { outcome });+ assert.deepEqual(rows(runRendererCompletion(liveWithEcho, echoPayload)), [+ ["mic", "morning everyone"],+ ["system", echoed],+ ]);++ const retractPayload = await runMainDiarization(mainAfterLateRetract, {+ retracted: lateRetracts,+ outcome,+ });+ assert.deepEqual(rows(runRendererCompletion(liveWithLateRetract, retractPayload)), [+ ["system", "any objections"],+ ["system", racing],+ ]);+ });+}++test("a resumed note's earlier rows are never removed, even with the same key", async () => {+ // An earlier session's row that happens to share the echo row's key.+ const seed = [{ id: "old-1", source: "mic", text: echoed, timestamp: START_MS + 11000 }];+ const payload = await runMainDiarization(stripIds(liveWithEcho));+ const merged = runRendererCompletion(liveWithEcho, payload, seed);++ assert.deepEqual(rows(merged), [+ ["mic", echoed],+ ["mic", "morning everyone"],+ ["system", echoed],+ ]);+ assert.equal(merged[0].timestamp, START_MS + 11000);+});++test("post-session mic dedupe only looks at system text within 6 seconds", () => {+ const manager = new DiarizationManager();+ const repeated = "can everyone see my screen";+ const system = { source: "system", text: repeated, timestamp: 30 };+ const nearEcho = { source: "mic", text: repeated, timestamp: 33, hasBleedEvidence: true };+ // Said again 10 minutes later: real speech, not an echo.+ const later = { source: "mic", text: repeated, timestamp: 630, hasBleedEvidence: true };++ const { kept, removed } = manager.splitMicEchoDuplicates([system, nearEcho, later]);++ assert.deepEqual(removed, [nearEcho]);+ assert.deepEqual(kept, [system, later]);+});diff --git a/test/stores/meetingRecordingStoreDiarizationPublish.test.js b/test/stores/meetingRecordingStoreDiarizationPublish.test.jsindex f7373b75a..971a01ddc 100644--- a/test/stores/meetingRecordingStoreDiarizationPublish.test.js+++ b/test/stores/meetingRecordingStoreDiarizationPublish.test.js@@ -289,6 +289,69 @@ test("an earlier session's diarization that lands after the note was resumed sti]);});+// An earlier session's result that removes rows after the note was resumed+// must not leave the resumed session's seed covering its own first row, even+// when it lands while the resumed session's stop call is still running.+for (const duringStop of [false, true]) {+ test(`rows an earlier session's diarization removes don't shift a resumed session's seed${duringStop ? " (mid-stop)" : ""}`, async (t) => {+ const { api, state, notes } = createElectronAPI();+ const { store, parseTranscriptSegments } = await loadModules(t, api);+ const note = notes.get(NOTE_ID);+ const echo = { text: "Yeah.", source: "mic", timestamp: 1760000001500 };++ state.stopDiarizationSessionId = "diar-1";+ assert.equal(await store.startRecording(START_ARGS), true);+ state.segmentCallback({+ type: "final",+ source: "system",+ text: "Yeah.",+ timestamp: 1760000001000,+ });+ state.segmentCallback({ type: "final", ...echo });+ await store.stopRecording();++ state.stopDiarizationSessionId = "diar-2";+ const seedSegments = parseTranscriptSegments(note.transcript);+ assert.equal(await store.startRecording({ ...START_ARGS, seedSegments }), true);+ state.segmentCallback({+ type: "final",+ source: "system",+ text: "Sure, go ahead.",+ timestamp: 1760000100000,+ });+ const earlierResult = async () => {+ state.diarizationCallback({+ noteId: NOTE_ID,+ sessionId: "diar-1",+ segments: [diarized("Yeah.", 1.0, "Carol")],+ removedSegments: [echo],+ });+ await settle();+ };+ if (duringStop) {+ const stop = api.meetingTranscriptionStop;+ api.meetingTranscriptionStop = async () => {+ await earlierResult();+ return stop();+ };+ }+ await store.stopRecording();+ if (!duringStop) await earlierResult();++ state.diarizationCallback({+ noteId: NOTE_ID,+ sessionId: "diar-2",+ segments: [diarized("Sure, go ahead.", 2.0, "Dave")],+ });+ await settle();++ assert.deepEqual(rowsOf(note), [+ ["Yeah.", 1.0, "Carol"],+ ["Sure, go ahead.", 2.0, "Dave"],+ ]);+ });+}+// Main sends a skipped diarization before the stop call returns, so the// listener must read the seed length only after its getNote round trip.test("a skipped diarization sent before stop returns still leaves the seeded rows alone", async (t) => {diff --git a/test/utils/diarizationCompletion.test.js b/test/utils/diarizationCompletion.test.jsindex 845d0fb5e..c18fceaf5 100644--- a/test/utils/diarizationCompletion.test.js+++ b/test/utils/diarizationCompletion.test.js@@ -4,6 +4,7 @@ const assert = require("node:assert/strict");const {resolveDiarizationTarget,selectBaseSegments,+ withoutRemovedSegments,} = require("../../src/utils/diarizationCompletion.ts");// Issue #1495: a delayed diarization result must be saved to the note that@@ -150,3 +151,39 @@ test("no persisted transcript and empty live segments merge into nothing", () =>});assert.deepEqual(result, []);});++// #2781: rows main dropped must leave the persisted transcript, or the merge+// keeps them with their raw epoch-ms timestamps.+test("withoutRemovedSegments drops exact source/timestamp/text matches only", () => {+ const segments = [+ { id: "a", source: "mic", text: "hello", timestamp: 1792414001000 },+ { id: "b", source: "system", text: "hello", timestamp: 1792414001000 },+ { id: "c", source: "mic", text: "hello", timestamp: 1792414002000 },+ ];+ const result = withoutRemovedSegments(segments, [+ { source: "mic", text: "hello", timestamp: 1792414001000 },+ ]);+ assert.deepEqual(+ result.map((segment) => segment.id),+ ["b", "c"]+ );+});++test("withoutRemovedSegments removes one row per removed entry", () => {+ const row = { source: "mic", text: "yes", timestamp: 1792414003000 };+ const segments = [+ { id: "a", ...row },+ { id: "b", ...row },+ ];+ const result = withoutRemovedSegments(segments, [row]);+ assert.deepEqual(+ result.map((segment) => segment.id),+ ["b"]+ );+});++test("withoutRemovedSegments returns the input when nothing was removed", () => {+ const segments = [{ id: "a", source: "mic", text: "hi", timestamp: 1 }];+ assert.deepEqual(withoutRemovedSegments(segments, undefined), segments);+ assert.deepEqual(withoutRemovedSegments(segments, []), segments);+});