Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

refactor(meeting): Phase 0 test seams — extract mic gate, holdback policy, segment reducer; pin streaming/token behavior (#1697)

Chad Piha884d9bfac05f
diff --git a/CLAUDE.md b/CLAUDE.md
index 5417fb360..13e70e068 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -131,6 +131,9 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- Linux: Event-driven via `pactl subscribe` (PulseAudio source-output events)
- All platforms: Graceful fallback to polling if native approach fails
- **processListCache.js**: Shared singleton process list cache (5s TTL, `ps-list` npm)
+- **meetingEchoLeakDetector.js**: Audio-layer echo analysis for meeting recordings — correlates each mic chunk against the recent system-audio tap (lag search 0–500 ms in 5 ms steps) and classifies it `clean_local` / `suspected_render_bleed` / `double_talk`; drives chunk muting and per-segment suppression flags. PCM-driven tests in `test/helpers/meetingEchoLeakDetector.test.js`
+- **meetingMicGate.js**: Pure RMS/peak chunk stats + the meeting mic gate verdict (`send` / `zero` for streaming, `send` / `skip` for local) with the exported silence and bleed thresholds; `ipcHandlers.js` (`dispatchMeetingAudioBuffer`, `transcribeLocalMeetingChunk`) only applies the verdict. Unit-tested in `test/helpers/meetingMicGate.test.js`
+- **meetingMicHoldback.js**: Pure holdback/retract policy for risky mic finals — pending-final partition, retract window, risky-profile classifier, text-layer duplicate check, racing-retract candidate selection, pending-overlap partition. `ipcHandlers.js` keeps thin adapters over its closure state (`meetingDiarizationSegments`, `meetingPendingMicFinals`, `hasNearbyTranscriptMatch`). Unit-tested in `test/helpers/meetingMicHoldback.test.js`
- **googleCalendarManager.js**: Google Calendar sync (REST, OAuth via `googleCalendarOAuth.js`)
- 10s socket timeout on API requests
- Incremental sync via `syncToken`; full re-sync on 410 prunes stale events (note-linked rows retained)
@@ -666,6 +669,16 @@ When "Share screen context" is enabled (Settings → AI Models → Voice Agent
**Tests**: `test/helpers/dictationRouting.test.js`, `test/helpers/screenContextCapture.test.js` (run with `node --test`)
+### 18. Meeting Transcription: Echo, Duplicate, and Segment Pipeline
+
+Live meeting transcription runs two streams (mic + system-audio tap) and must keep the remote party's voice, as heard through the local speakers, out of the mic transcript. The policy lives in pure, unit-tested seams so it can be tuned without touching the IPC plumbing:
+
+- **Audio layer**: `meetingEchoLeakDetector.js` correlates mic chunks against recent system audio; `meetingMicGate.js` turns chunk RMS/peak (+ a "system speaking" lookback) into a `send` / `zero` / `skip` verdict that `ipcHandlers.js` applies in `dispatchMeetingAudioBuffer` (streaming) and `transcribeLocalMeetingChunk` (local)
+- **Text layer**: `meetingMicHoldback.js` decides whether a mic final is risky (held back), a duplicate of recent system text (dropped), or racing an arriving system final (retracted); the `ipcHandlers.js` adapters (`shouldSkipDuplicateMicSegment`, `hasRiskyMicDuplicateProfile`, `removeRacingMicEntriesFor`, `removePendingMicFinalsFor`) apply the results to closure state and emit `meeting-transcription-segment` events (`partial` / `final` / `retract`)
+- **Renderer**: `src/stores/meetingSegmentReducer.ts` is the pure `(state, event, deps) → reduction` transition for those events (timestamp-sorted insert, retract by exact match, per-source partial slots); `meetingRecordingStore.ts` supplies `mintSegmentId` / `decorateFinal` (speaker identifications, provisional speaker, locks — must not write to the store) and applies the reduction. Tests: `test/stores/meetingSegmentReducer.test.js`, `test/stores/meetingRecordingStoreImports.test.js`
+- **Regression pins**: BYOK `session.update` payload and the disconnect-commit callback (`test/helpers/openaiRealtimeStreaming.test.js`, `tinfoilRealtimeStreaming.test.js`), token-endpoint wire bodies (`test/helpers/realtimeTokenProviders.test.js`). Tests named `characterization: …` pin known oddities on purpose — flip them deliberately when changing policy
+- **Fixtures**: `test/helpers/harness/pcmFixtures.js` — deterministic 24 kHz PCM generators (`makeSine`, `makeSeededNoise`, `mix`, `delayBy`, `toInt16Buffer`, `chunkBuffer`, …) used by the gate and echo-detector tests
+
## Development Guidelines
### Internationalization (i18n) — REQUIRED
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 4de6743bc..f8297c626 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -66,7 +66,14 @@ const AudioStorageManager = require("./audioStorage");
const liveSpeakerIdentifier = require("./liveSpeakerIdentifier");
const { supportsLiveSpeakerIdentification } = require("./liveSpeakerIdPolicy");
const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");
-const { partitionPendingMicFinals, isWithinRetractWindow } = require("./meetingMicHoldback");
+const {
+ partitionPendingMicFinals,
+ isRiskyMicDuplicateProfile,
+ isDuplicateMicSegment,
+ selectRacingMicEntryIndices,
+ partitionOverlappingPendingMicFinals,
+} = require("./meetingMicHoldback");
+const { computeChunkStats, resolveMicChunkAction } = require("./meetingMicGate");
const { applySmartSpacing } = require("./smartSpacing");
const { applyAutoLearnSetting } = require("./autoLearnSetting");
const {
@@ -5476,73 +5483,32 @@ class IPCHandlers {
return false;
};
- const shouldSkipDuplicateMicSegment = (text, timestamp, suppression = null) => {
- if (suppression?.likelyRenderBleed || suppression?.hasBleedEvidence) {
- if (hasNearbyTranscriptMatch("system", text, timestamp)) {
- return true;
- }
- }
-
- if (suppression?.reason === "double_talk") {
- return hasNearbyTranscriptMatch("system", text, timestamp, { relaxed: true });
- }
-
- return false;
- };
+ const shouldSkipDuplicateMicSegment = (text, timestamp, suppression = null) =>
+ isDuplicateMicSegment({ text, timestamp, suppression, hasNearbyTranscriptMatch });
const isWithinMeetingStartupWarmup = () =>
meetingStartedAt != null && Date.now() - meetingStartedAt < MEETING_STARTUP_WARMUP_MS;
- const hasRiskyMicDuplicateProfile = (suppression = null) => {
- if (isWithinMeetingStartupWarmup()) {
- return true;
- }
- if (suppression?.systemSpeaking) {
- return true;
- }
- return (
- !!suppression &&
- (suppression.reason === "double_talk" ||
- suppression.hasBleedEvidence ||
- suppression.likelyRenderBleed)
- );
- };
+ const hasRiskyMicDuplicateProfile = (suppression = null) =>
+ isRiskyMicDuplicateProfile({
+ suppression,
+ inStartupWarmup: isWithinMeetingStartupWarmup(),
+ });
const removeRacingMicEntriesFor = (systemText, systemTimestamp) => {
+ const indices = selectRacingMicEntryIndices({
+ segments: meetingDiarizationSegments,
+ systemText,
+ systemTimestamp,
+ hasNearbyTranscriptMatch,
+ duplicateWindowMs: DUPLICATE_TRANSCRIPT_WINDOW_MS,
+ retractWindowMs: RACING_MIC_RETRACT_WINDOW_MS,
+ });
const removed = [];
- for (let i = meetingDiarizationSegments.length - 1; i >= 0; i -= 1) {
- const candidate = meetingDiarizationSegments[i];
- if (candidate.source !== "mic" || candidate.timestamp == null) continue;
- if (systemTimestamp != null) {
- const windowMs =
- candidate.hasBleedEvidence || candidate.likelyRenderBleed
- ? DUPLICATE_TRANSCRIPT_WINDOW_MS
- : RACING_MIC_RETRACT_WINDOW_MS;
- if (!isWithinRetractWindow({ candidate, systemTimestamp, windowMs })) {
- if (candidate.timestamp < systemTimestamp - DUPLICATE_TRANSCRIPT_WINDOW_MS) break;
- continue;
- }
- }
- const hasMicDuplicateRisk =
- candidate.likelyRenderBleed ||
- candidate.hasBleedEvidence ||
- candidate.suppressionReason === "double_talk";
- const overlapsSystem = hasNearbyTranscriptMatch(
- "system",
- candidate.text,
- candidate.timestamp,
- {
- extraSegment: {
- text: systemText,
- timestamp: systemTimestamp,
- },
- relaxed: candidate.suppressionReason === "double_talk",
- }
- );
- if (hasMicDuplicateRisk && overlapsSystem) {
- meetingDiarizationSegments.splice(i, 1);
- removed.push(candidate);
- }
+ // Indices are descending, so splicing in order never shifts a later index.
+ for (const index of indices) {
+ removed.push(meetingDiarizationSegments[index]);
+ meetingDiarizationSegments.splice(index, 1);
}
return removed;
};
@@ -5672,26 +5638,13 @@ class IPCHandlers {
};
const removePendingMicFinalsFor = (systemText, systemTimestamp) => {
- const removed = [];
- meetingPendingMicFinals = meetingPendingMicFinals.filter((candidate) => {
- const overlapsSystem = hasNearbyTranscriptMatch(
- "system",
- candidate.text,
- candidate.timestamp,
- {
- extraSegment: {
- text: systemText,
- timestamp: systemTimestamp,
- },
- relaxed: candidate.micSuppression?.reason === "double_talk",
- }
- );
- if (!overlapsSystem) {
- return true;
- }
- removed.push(candidate);
- return false;
+ const { kept, removed } = partitionOverlappingPendingMicFinals({
+ pending: meetingPendingMicFinals,
+ systemText,
+ systemTimestamp,
+ hasNearbyTranscriptMatch,
});
+ meetingPendingMicFinals = kept;
schedulePendingMicFinalFlush();
return removed;
};
@@ -6199,8 +6152,6 @@ class IPCHandlers {
const MEETING_MIC_REFERENCE_ALIGNMENT_MS = 320;
const MEETING_STARTUP_WARMUP_MS = 1500;
- const MEETING_MIC_BLEED_RMS_CEILING = 0.018;
- const MEETING_MIC_BLEED_PEAK_CEILING = 0.07;
const MEETING_MIC_BLEED_LOOKBACK_MS = 500;
const MEETING_MIC_STATS_LOG_LIMIT = 200;
let meetingMicStatsLogCount = 0;
@@ -6323,26 +6274,20 @@ class IPCHandlers {
let outbound = buffer;
if (source === "mic" && buffer.length >= 2) {
- const samples = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.length >> 1);
- let sumSq = 0;
- let peak = 0;
- for (let i = 0; i < samples.length; i++) {
- const n = samples[i] / 0x7fff;
- sumSq += n * n;
- const abs = n < 0 ? -n : n;
- if (abs > peak) peak = abs;
- }
- const rms = Math.sqrt(sumSq / samples.length);
+ const { rms, peak, sampleCount } = computeChunkStats(buffer);
+ // Evaluated eagerly (as before) because the stats log reports it.
const systemSpeaking = meetingEchoLeakDetector.isSystemSpeaking(
Date.now() - MEETING_MIC_BLEED_LOOKBACK_MS
);
- if (rms < 0.0015 && peak < 0.05) {
- outbound = Buffer.alloc(buffer.length);
- } else if (
- rms < MEETING_MIC_BLEED_RMS_CEILING &&
- peak < MEETING_MIC_BLEED_PEAK_CEILING &&
- systemSpeaking
- ) {
+ const verdict = resolveMicChunkAction({
+ mode: "streaming",
+ source,
+ rms,
+ peak,
+ sampleCount,
+ isSystemSpeaking: () => systemSpeaking,
+ });
+ if (verdict.action === "zero") {
outbound = Buffer.alloc(buffer.length);
}
if (
@@ -6593,36 +6538,27 @@ class IPCHandlers {
const pcm16k = downsample24kTo16k(pcm24k);
- const samples = new Int16Array(pcm16k.buffer, pcm16k.byteOffset, pcm16k.length / 2);
- let sumSq = 0;
- let peak = 0;
- for (let i = 0; i < samples.length; i++) {
- const n = samples[i] / 0x7fff;
- sumSq += n * n;
- const abs = n < 0 ? -n : n;
- if (abs > peak) peak = abs;
- }
- const rms = Math.sqrt(sumSq / samples.length);
- if (rms < 0.0015 && peak < 0.05) {
- debugLogger.debug("Skipping silent meeting chunk", {
- source,
- rms: rms.toFixed(4),
- peak: peak.toFixed(4),
- });
- return;
- }
-
- if (
- source === "mic" &&
- rms < MEETING_MIC_BLEED_RMS_CEILING &&
- peak < MEETING_MIC_BLEED_PEAK_CEILING &&
- meetingEchoLeakDetector.isSystemSpeaking(Date.now() - LOCAL_MEETING_CHUNK_INTERVAL_MS)
- ) {
- debugLogger.debug("Skipping system-dominant mic chunk", {
- source,
- rms: rms.toFixed(4),
- peak: peak.toFixed(4),
- });
+ const { rms, peak, sampleCount } = computeChunkStats(pcm16k);
+ const verdict = resolveMicChunkAction({
+ mode: "local",
+ source,
+ rms,
+ peak,
+ sampleCount,
+ isSystemSpeaking: () =>
+ meetingEchoLeakDetector.isSystemSpeaking(Date.now() - LOCAL_MEETING_CHUNK_INTERVAL_MS),
+ });
+ if (verdict.action === "skip") {
+ debugLogger.debug(
+ verdict.reason === "silence"
+ ? "Skipping silent meeting chunk"
+ : "Skipping system-dominant mic chunk",
+ {
+ source,
+ rms: rms.toFixed(4),
+ peak: peak.toFixed(4),
+ }
+ );
return;
}
diff --git a/src/helpers/meetingMicGate.js b/src/helpers/meetingMicGate.js
new file mode 100644
index 000000000..80990b219
--- /dev/null
+++ b/src/helpers/meetingMicGate.js
@@ -0,0 +1,57 @@
+/**
+ * Pure meeting mic gate: RMS/peak chunk stats and the send/zero/skip verdict.
+ *
+ * Extracted verbatim from ipcHandlers.js (dispatchMeetingAudioBuffer for the
+ * streaming path, transcribeLocalMeetingChunk for the local path). Phase 0 keeps
+ * today's policy exactly; Phase 1 changes the policy here, behind these tests.
+ */
+const MEETING_MIC_SILENCE_RMS = 0.0015;
+const MEETING_MIC_SILENCE_PEAK = 0.05;
+const MEETING_MIC_BLEED_RMS_CEILING = 0.018;
+const MEETING_MIC_BLEED_PEAK_CEILING = 0.07;
+
+const SEND = Object.freeze({ action: "send", reason: null });
+
+function computeChunkStats(buffer) {
+ if (!buffer || buffer.length < 2) {
+ return { rms: 0, peak: 0, sampleCount: 0 };
+ }
+ const samples = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.length >> 1);
+ let sumSq = 0;
+ let peak = 0;
+ for (let i = 0; i < samples.length; i += 1) {
+ const n = samples[i] / 0x7fff;
+ sumSq += n * n;
+ const abs = n < 0 ? -n : n;
+ if (abs > peak) peak = abs;
+ }
+ return { rms: Math.sqrt(sumSq / samples.length), peak, sampleCount: samples.length };
+}
+
+function resolveMicChunkAction({ mode, source, rms, peak, sampleCount, isSystemSpeaking }) {
+ if (!sampleCount) return SEND;
+
+ const isMic = source === "mic";
+ const silent = rms < MEETING_MIC_SILENCE_RMS && peak < MEETING_MIC_SILENCE_PEAK;
+ const quiet = rms < MEETING_MIC_BLEED_RMS_CEILING && peak < MEETING_MIC_BLEED_PEAK_CEILING;
+
+ if (mode === "local") {
+ if (silent) return { action: "skip", reason: "silence" };
+ if (isMic && quiet && isSystemSpeaking()) return { action: "skip", reason: "system_dominant" };
+ return SEND;
+ }
+
+ if (!isMic) return SEND;
+ if (silent) return { action: "zero", reason: "silence" };
+ if (quiet && isSystemSpeaking()) return { action: "zero", reason: "bleed_floor" };
+ return SEND;
+}
+
+module.exports = {
+ MEETING_MIC_SILENCE_RMS,
+ MEETING_MIC_SILENCE_PEAK,
+ MEETING_MIC_BLEED_RMS_CEILING,
+ MEETING_MIC_BLEED_PEAK_CEILING,
+ computeChunkStats,
+ resolveMicChunkAction,
+};
diff --git a/src/helpers/meetingMicHoldback.js b/src/helpers/meetingMicHoldback.js
index e035e51af..b5f047a24 100644
--- a/src/helpers/meetingMicHoldback.js
+++ b/src/helpers/meetingMicHoldback.js
@@ -54,4 +54,131 @@ const isWithinRetractWindow = ({ candidate, systemTimestamp, windowMs }) => {
);
};
-module.exports = { partitionPendingMicFinals, isWithinRetractWindow };
+/**
+ * A mic final is "risky" (held back rather than committed on arrival) during
+ * the startup warmup, whenever the system tap was speaking, or when the audio
+ * analysis flagged double-talk / render bleed. Verified 2026-08-17: bare
+ * `systemSpeaking` is sufficient today (design plan D4b tightens this).
+ * @returns {boolean|undefined} falsy (may be `undefined`, not `false`) when not risky — callers test truthiness only.
+ */
+const isRiskyMicDuplicateProfile = ({ suppression = null, inStartupWarmup = false } = {}) => {
+ if (inStartupWarmup) {
+ return true;
+ }
+ if (suppression?.systemSpeaking) {
+ return true;
+ }
+ return (
+ !!suppression &&
+ (suppression.reason === "double_talk" ||
+ suppression.hasBleedEvidence ||
+ suppression.likelyRenderBleed)
+ );
+};
+
+/**
+ * Text-layer duplicate check for a mic final: strict overlap when bleed
+ * evidence exists, relaxed overlap for double-talk. `hasNearbyTranscriptMatch`
+ * is ipcHandlers' closure over the committed system segments.
+ */
+const isDuplicateMicSegment = ({
+ text,
+ timestamp,
+ suppression = null,
+ hasNearbyTranscriptMatch,
+}) => {
+ if (suppression?.likelyRenderBleed || suppression?.hasBleedEvidence) {
+ if (hasNearbyTranscriptMatch("system", text, timestamp)) {
+ return true;
+ }
+ }
+
+ if (suppression?.reason === "double_talk") {
+ return hasNearbyTranscriptMatch("system", text, timestamp, { relaxed: true });
+ }
+
+ return false;
+};
+
+/**
+ * Indices (descending) of committed mic segments that an arriving system final
+ * proves to be echo. Scans newest→oldest and stops early once a candidate is
+ * older than the largest window (today's `break`; the array is committedAt-
+ * ordered, so this is an optimisation that is only unsound under mixed
+ * per-candidate windows — see the characterization test).
+ */
+const selectRacingMicEntryIndices = ({
+ segments,
+ systemText,
+ systemTimestamp,
+ hasNearbyTranscriptMatch,
+ duplicateWindowMs,
+ retractWindowMs,
+}) => {
+ const removedIndices = [];
+ for (let i = segments.length - 1; i >= 0; i -= 1) {
+ const candidate = segments[i];
+ if (candidate.source !== "mic" || candidate.timestamp == null) continue;
+ if (systemTimestamp != null) {
+ const windowMs =
+ candidate.hasBleedEvidence || candidate.likelyRenderBleed
+ ? duplicateWindowMs
+ : retractWindowMs;
+ if (!isWithinRetractWindow({ candidate, systemTimestamp, windowMs })) {
+ if (candidate.timestamp < systemTimestamp - duplicateWindowMs) break;
+ continue;
+ }
+ }
+ const hasMicDuplicateRisk =
+ candidate.likelyRenderBleed ||
+ candidate.hasBleedEvidence ||
+ candidate.suppressionReason === "double_talk";
+ const overlapsSystem = hasNearbyTranscriptMatch("system", candidate.text, candidate.timestamp, {
+ extraSegment: {
+ text: systemText,
+ timestamp: systemTimestamp,
+ },
+ relaxed: candidate.suppressionReason === "double_talk",
+ });
+ if (hasMicDuplicateRisk && overlapsSystem) {
+ removedIndices.push(i);
+ }
+ }
+ return removedIndices;
+};
+
+/**
+ * Splits the pending (held-back) mic finals into those that overlap an
+ * arriving system final (`removed`) and the rest (`kept`). No risk-flag check
+ * today — any overlapping pending final is dropped (design plan Phase 2 routes
+ * this into the pending pipeline).
+ */
+const partitionOverlappingPendingMicFinals = ({
+ pending,
+ systemText,
+ systemTimestamp,
+ hasNearbyTranscriptMatch,
+}) => {
+ const kept = [];
+ const removed = [];
+ for (const candidate of pending) {
+ const overlapsSystem = hasNearbyTranscriptMatch("system", candidate.text, candidate.timestamp, {
+ extraSegment: {
+ text: systemText,
+ timestamp: systemTimestamp,
+ },
+ relaxed: candidate.micSuppression?.reason === "double_talk",
+ });
+ (overlapsSystem ? removed : kept).push(candidate);
+ }
+ return { kept, removed };
+};
+
+module.exports = {
+ partitionPendingMicFinals,
+ isWithinRetractWindow,
+ isRiskyMicDuplicateProfile,
+ isDuplicateMicSegment,
+ selectRacingMicEntryIndices,
+ partitionOverlappingPendingMicFinals,
+};
diff --git a/src/stores/meetingRecordingStore.ts b/src/stores/meetingRecordingStore.ts
index 64f6fefa1..6174c5fbe 100644
--- a/src/stores/meetingRecordingStore.ts
+++ b/src/stores/meetingRecordingStore.ts
@@ -40,6 +40,7 @@ import {
import { parseTranscriptSegments } from "../utils/parseTranscriptSegments";
import { resolveDiarizationTarget, selectBaseSegments } from "../utils/diarizationCompletion";
import { createSerialQueue } from "../utils/serialQueue";
+import { reduceMeetingSegmentEvent, type MeetingSegmentEvent } from "./meetingSegmentReducer";
export interface TranscriptSegment {
id: string;
@@ -935,36 +936,56 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
}
const segmentCleanup = window.electronAPI?.onMeetingTranscriptionSegment?.(
- (data: {
- text: string;
- source: "mic" | "system";
- type: "partial" | "final" | "retract";
- timestamp?: number;
- }) => {
- if (data.type === "retract") {
- const next = useMeetingRecordingStore
- .getState()
- .segments.filter(
- (seg) =>
- !(
- seg.source === data.source &&
- seg.timestamp === data.timestamp &&
- seg.text === data.text
- )
- );
- segmentsRefValue = next;
+ (data: MeetingSegmentEvent) => {
+ const current = useMeetingRecordingStore.getState();
+ const reduction = reduceMeetingSegmentEvent(
+ {
+ segments: current.segments,
+ micPartial: current.micPartial,
+ systemPartial: current.systemPartial,
+ },
+ data,
+ {
+ mintSegmentId: () => `seg-${++segmentCounter}`,
+ // Must not call setState: `current.segments` was snapshotted before this runs and the
+ // reduction inserts into that snapshot. Reads of segmentsRefValue (assignProvisionalSpeaker)
+ // still see the previous segments, exactly as before the reducer extraction.
+ decorateFinal: (rawSegment) => {
+ let decorated = rawSegment;
+ for (let i = speakerIdentifications.length - 1; i >= 0; i -= 1) {
+ decorated = applySpeakerIdentification(decorated, speakerIdentifications[i]);
+ }
+ const provisional = assignProvisionalSpeaker(decorated);
+ reserveSpeakerIndex(provisional.speaker);
+ const lockedName = provisional.speaker
+ ? speakerLocks.get(provisional.speaker)
+ : undefined;
+ return lockedName
+ ? lockTranscriptSpeaker(provisional, {
+ speakerName: lockedName,
+ speakerIsPlaceholder: false,
+ suggestedName: undefined,
+ suggestedProfileId: undefined,
+ })
+ : provisional;
+ },
+ }
+ );
+
+ if (reduction.kind === "retract") {
+ segmentsRefValue = reduction.state.segments;
useMeetingRecordingStore.setState({
- segments: next,
- transcript: buildTranscriptText(next),
+ segments: reduction.state.segments,
+ transcript: buildTranscriptText(reduction.state.segments),
});
return;
}
- if (data.type === "partial") {
- if (data.source === "mic") {
- useMeetingRecordingStore.setState({ micPartial: data.text });
+ if (reduction.kind === "partial") {
+ if (reduction.source === "mic") {
+ useMeetingRecordingStore.setState({ micPartial: reduction.state.micPartial });
} else {
- useMeetingRecordingStore.setState({ systemPartial: data.text });
+ useMeetingRecordingStore.setState({ systemPartial: reduction.state.systemPartial });
if (!systemPartialSpeakerIdValue) {
// Reuse the recent system speaker before minting — the partial id is
// cleared after every final, so always minting spawned one per utterance.
@@ -978,44 +999,17 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
return;
}
- let rawSegment: TranscriptSegment = normalizeTranscriptSegment({
- id: `seg-${++segmentCounter}`,
- text: data.text,
- source: data.source,
- timestamp: data.timestamp,
- });
-
- for (let i = speakerIdentifications.length - 1; i >= 0; i -= 1) {
- rawSegment = applySpeakerIdentification(rawSegment, speakerIdentifications[i]);
- }
-
- const provisional = assignProvisionalSpeaker(rawSegment);
- reserveSpeakerIndex(provisional.speaker);
- const lockedName = provisional.speaker ? speakerLocks.get(provisional.speaker) : undefined;
- const seg = lockedName
- ? lockTranscriptSpeaker(provisional, {
- speakerName: lockedName,
- speakerIsPlaceholder: false,
- suggestedName: undefined,
- suggestedProfileId: undefined,
- })
- : provisional;
-
- const prev = useMeetingRecordingStore.getState().segments;
- const ts = seg.timestamp ?? Infinity;
- let i = prev.length;
- while (i > 0 && (prev[i - 1].timestamp ?? 0) > ts) i--;
- const next =
- i === prev.length ? [...prev, seg] : [...prev.slice(0, i), seg, ...prev.slice(i)];
- segmentsRefValue = next;
-
- const partialPatch = data.source === "mic" ? { micPartial: "" } : { systemPartial: "" };
+ const seg = reduction.inserted;
+ segmentsRefValue = reduction.state.segments;
+ // Only the cleared partial goes in the payload (spreading both partial fields would add a
+ // key the pre-reducer code never wrote), so derive it from the inserted segment's source.
+ const partialPatch = seg.source === "mic" ? { micPartial: "" } : { systemPartial: "" };
useMeetingRecordingStore.setState({
- segments: next,
- transcript: buildTranscriptText(next),
+ segments: reduction.state.segments,
+ transcript: buildTranscriptText(reduction.state.segments),
...partialPatch,
});
- if (data.source === "system" && seg.speaker) {
+ if (seg.source === "system" && seg.speaker) {
rememberSystemSpeaker(
seg.speaker,
seg.speakerName ?? null,
@@ -1023,7 +1017,7 @@ export async function startRecording(args: StartRecordingArgs): Promise<boolean>
seg.timestamp ?? Date.now()
);
}
- if (data.source === "system") {
+ if (seg.source === "system") {
setSystemPartialSpeakerIdentity(null, null);
}
}
diff --git a/src/stores/meetingSegmentReducer.ts b/src/stores/meetingSegmentReducer.ts
new file mode 100644
index 000000000..112a9b23c
--- /dev/null
+++ b/src/stores/meetingSegmentReducer.ts
@@ -0,0 +1,86 @@
+import type { TranscriptSegment } from "./meetingRecordingStore";
+import { normalizeTranscriptSegment } from "../utils/transcriptSpeakerState";
+
+/**
+ * State transition for live meeting segment events (partial / final / retract)
+ * that never mutates its state argument; all side effects are confined to the
+ * injected deps. Extracted from meetingRecordingStore's
+ * onMeetingTranscriptionSegment handler; speaker identity side effects stay in
+ * the store and are driven by the returned reduction. Phase 0: byte-for-byte
+ * today's semantics.
+ */
+export interface MeetingSegmentEvent {
+ text: string;
+ source: "mic" | "system";
+ type: "partial" | "final" | "retract";
+ timestamp?: number;
+}
+
+export interface MeetingSegmentState {
+ segments: TranscriptSegment[];
+ micPartial: string;
+ systemPartial: string;
+}
+
+export interface MeetingSegmentReducerDeps {
+ /** Renderer-side id for a new final (today `seg-${++segmentCounter}`). */
+ mintSegmentId: () => string;
+ /** Applies speaker identifications, provisional speaker, index reservation, locks. Must be free of store writes — the reducer inserts into the segments snapshot it was handed. */
+ decorateFinal: (segment: TranscriptSegment) => TranscriptSegment;
+}
+
+export type MeetingSegmentReduction =
+ | { kind: "retract"; state: MeetingSegmentState; removed: TranscriptSegment[] }
+ | { kind: "partial"; state: MeetingSegmentState; source: "mic" | "system" }
+ | { kind: "final"; state: MeetingSegmentState; inserted: TranscriptSegment; index: number };
+
+// Live finals are inserted by capture timestamp. An incoming final without a
+// timestamp goes to the end (`?? Infinity`); an existing row without one sorts
+// as 0. Strict `>` keeps equal timestamps in arrival order.
+export function insertSegmentByTimestamp(
+ segments: TranscriptSegment[],
+ seg: TranscriptSegment
+): { segments: TranscriptSegment[]; index: number } {
+ const ts = seg.timestamp ?? Infinity;
+ let i = segments.length;
+ while (i > 0 && (segments[i - 1].timestamp ?? 0) > ts) i--;
+ const next =
+ i === segments.length
+ ? [...segments, seg]
+ : [...segments.slice(0, i), seg, ...segments.slice(i)];
+ return { segments: next, index: i };
+}
+
+export function reduceMeetingSegmentEvent(
+ state: MeetingSegmentState,
+ event: MeetingSegmentEvent,
+ deps: MeetingSegmentReducerDeps
+): MeetingSegmentReduction {
+ if (event.type === "retract") {
+ const removed: TranscriptSegment[] = [];
+ const segments = state.segments.filter((seg) => {
+ const hit =
+ seg.source === event.source && seg.timestamp === event.timestamp && seg.text === event.text;
+ if (hit) removed.push(seg);
+ return !hit;
+ });
+ return { kind: "retract", state: { ...state, segments }, removed };
+ }
+
+ if (event.type === "partial") {
+ const patch =
+ event.source === "mic" ? { micPartial: event.text } : { systemPartial: event.text };
+ return { kind: "partial", source: event.source, state: { ...state, ...patch } };
+ }
+
+ const raw = normalizeTranscriptSegment({
+ id: deps.mintSegmentId(),
+ text: event.text,
+ source: event.source,
+ timestamp: event.timestamp,
+ });
+ const inserted = deps.decorateFinal(raw);
+ const { segments, index } = insertSegmentByTimestamp(state.segments, inserted);
+ const partialPatch = event.source === "mic" ? { micPartial: "" } : { systemPartial: "" };
+ return { kind: "final", inserted, index, state: { ...state, segments, ...partialPatch } };
+}
diff --git a/test/helpers/harness/pcmFixtures.js b/test/helpers/harness/pcmFixtures.js
new file mode 100644
index 000000000..c42639c73
--- /dev/null
+++ b/test/helpers/harness/pcmFixtures.js
@@ -0,0 +1,92 @@
+// Deterministic PCM generators for meeting-audio tests. 24 kHz mono float in [-1, 1].
+const SAMPLE_RATE = 24000;
+
+const samplesFor = (durationMs, sampleRate) => Math.round((durationMs / 1000) * sampleRate);
+
+function makeSine({
+ frequencyHz = 440,
+ durationMs,
+ amplitude = 0.5,
+ sampleRate = SAMPLE_RATE,
+ phase = 0,
+}) {
+ const out = new Float32Array(samplesFor(durationMs, sampleRate));
+ const step = (2 * Math.PI * frequencyHz) / sampleRate;
+ for (let i = 0; i < out.length; i += 1) out[i] = amplitude * Math.sin(phase + i * step);
+ return out;
+}
+
+// Numerical Recipes LCG — same seed ⇒ same samples on every platform.
+function makeSeededNoise({ durationMs, amplitude = 0.5, seed = 1, sampleRate = SAMPLE_RATE }) {
+ const out = new Float32Array(samplesFor(durationMs, sampleRate));
+ let state = seed >>> 0;
+ for (let i = 0; i < out.length; i += 1) {
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
+ out[i] = amplitude * ((state / 4294967296) * 2 - 1);
+ }
+ return out;
+}
+
+function mix(...tracks) {
+ const length = Math.max(0, ...tracks.map((t) => t.length));
+ const out = new Float32Array(length);
+ for (const track of tracks) {
+ for (let i = 0; i < track.length; i += 1) out[i] += track[i];
+ }
+ for (let i = 0; i < out.length; i += 1) out[i] = Math.max(-1, Math.min(1, out[i]));
+ return out;
+}
+
+function scale(track, gain) {
+ const out = new Float32Array(track.length);
+ for (let i = 0; i < track.length; i += 1) out[i] = track[i] * gain;
+ return out;
+}
+
+function delayBy(track, delayMs, sampleRate = SAMPLE_RATE) {
+ const lead = samplesFor(delayMs, sampleRate);
+ const out = new Float32Array(track.length + lead);
+ out.set(track, lead);
+ return out;
+}
+
+function toInt16Buffer(track) {
+ const buf = Buffer.alloc(track.length * 2);
+ for (let i = 0; i < track.length; i += 1) {
+ const clamped = Math.max(-1, Math.min(1, track[i]));
+ const value = clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767);
+ buf.writeInt16LE(Math.max(-32768, Math.min(32767, value)), i * 2);
+ }
+ return buf;
+}
+
+function chunkBuffer(buffer, samplesPerChunk) {
+ const bytes = samplesPerChunk * 2;
+ const chunks = [];
+ for (let offset = 0; offset < buffer.length; offset += bytes) {
+ chunks.push(buffer.subarray(offset, Math.min(buffer.length, offset + bytes)));
+ }
+ return chunks;
+}
+
+function rmsOf(track) {
+ if (!track.length) return 0;
+ let sumSq = 0;
+ for (let i = 0; i < track.length; i += 1) sumSq += track[i] * track[i];
+ return Math.sqrt(sumSq / track.length);
+}
+
+const dbToGain = (db) => 10 ** (db / 20);
+
+module.exports = {
+ SAMPLE_RATE,
+ makeSine,
+ makeSeededNoise,
+ mix,
+ scale,
+ delayBy,
+ toInt16Buffer,
+ chunkBuffer,
+ rmsOf,
+ dbToGain,
+};
diff --git a/test/helpers/meetingEchoLeakDetector.test.js b/test/helpers/meetingEchoLeakDetector.test.js
index 04221f6ec..22445ecc0 100644
--- a/test/helpers/meetingEchoLeakDetector.test.js
+++ b/test/helpers/meetingEchoLeakDetector.test.js
@@ -72,3 +72,117 @@ test("shouldSuppressMicSegment keeps bleed evidence even when share stays below
assert.equal(result.bleedMatchCount, 1);
assert.equal(result.sampleCount, 4);
});
+
+const fx = require("./harness/pcmFixtures");
+
+const CHUNK = 800; // renderer mic chunk = 800 samples @ 24 kHz ≈ 33 ms
+const REF_MS = 1200; // ≥ 800 + 12000 samples so the lag search has a full window
+
+// Feeds `reference` to the detector as system chunks and returns the sample index of the window end.
+function feedReference(detector, reference, startMs = 0) {
+ const chunks = fx.chunkBuffer(fx.toInt16Buffer(reference), CHUNK);
+ chunks.forEach((chunk, i) =>
+ detector.recordSystemChunk(chunk, startMs + Math.round((i * CHUNK * 1000) / 24000))
+ );
+ return reference.length;
+}
+
+// Mic chunk that "hears" the reference `delayMs` late: the reference slice that
+// ends `delayMs` before the window end.
+function delayedReferenceSlice(reference, delayMs, gain) {
+ const delaySamples = Math.round((delayMs / 1000) * 24000);
+ const end = reference.length - delaySamples;
+ return fx.scale(reference.subarray(end - CHUNK, end), gain);
+}
+
+test("PCM: a −12 dB copy of the reference delayed 100 ms reads as render bleed and mutes", () => {
+ const detector = new MeetingEchoLeakDetector();
+ const reference = fx.makeSeededNoise({ durationMs: REF_MS, amplitude: 0.2, seed: 11 });
+ feedReference(detector, reference);
+ const mic = delayedReferenceSlice(reference, 100, fx.dbToGain(-12));
+
+ const analysis = detector.analyzeMicChunk(fx.toInt16Buffer(mic), REF_MS);
+
+ assert.ok(analysis.rms >= 0.006, `mic rms ${analysis.rms} must clear MIN_RMS`);
+ assert.equal(analysis.state, "suspected_render_bleed");
+ assert.ok(analysis.correlation > 0.95, `corr ${analysis.correlation}`);
+ assert.ok(analysis.residualRatio < 0.1, `residual ${analysis.residualRatio}`);
+ assert.ok(
+ analysis.micToSystemRatio > 0.2 && analysis.micToSystemRatio < 0.3,
+ `ratio ${analysis.micToSystemRatio}`
+ );
+ assert.equal(analysis.shouldMute, true);
+});
+
+test("PCM: the field double-talk profile (corr 0.76–0.83, mic louder than reference) reads as double_talk and does NOT mute", () => {
+ const detector = new MeetingEchoLeakDetector();
+ const reference = fx.makeSeededNoise({ durationMs: REF_MS, amplitude: 0.2, seed: 21 });
+ feedReference(detector, reference);
+ // mic = 1.2·delayed reference + 0.9·independent local speech ⇒ corr = 1.2/√(1.44+0.81) = 0.8
+ const bleed = delayedReferenceSlice(reference, 100, 1.2);
+ const local = fx.scale(
+ fx.makeSeededNoise({ durationMs: (CHUNK * 1000) / 24000, amplitude: 0.2, seed: 99 }),
+ 0.9
+ );
+ const mic = fx.mix(bleed, local);
+
+ const analysis = detector.analyzeMicChunk(fx.toInt16Buffer(mic), REF_MS);
+
+ assert.equal(analysis.state, "double_talk");
+ assert.ok(
+ analysis.correlation >= 0.72 && analysis.correlation <= 0.88,
+ `corr ${analysis.correlation}`
+ );
+ assert.ok(
+ analysis.residualRatio > 0.25 && analysis.residualRatio < 0.5,
+ `residual ${analysis.residualRatio}`
+ );
+ assert.ok(
+ analysis.micToSystemRatio > 1.3,
+ `ratio ${analysis.micToSystemRatio} (louder than reference)`
+ );
+ assert.equal(analysis.shouldMute, false);
+});
+
+test("PCM: uncorrelated local speech reads clean_local with low correlation", () => {
+ const detector = new MeetingEchoLeakDetector();
+ const reference = fx.makeSeededNoise({ durationMs: REF_MS, amplitude: 0.2, seed: 31 });
+ feedReference(detector, reference);
+ const mic = fx.makeSeededNoise({ durationMs: (CHUNK * 1000) / 24000, amplitude: 0.2, seed: 77 });
+
+ const analysis = detector.analyzeMicChunk(fx.toInt16Buffer(mic), REF_MS);
+
+ assert.equal(analysis.state, "clean_local");
+ assert.ok(analysis.correlation < 0.3, `corr ${analysis.correlation}`);
+ assert.equal(analysis.shouldMute, false);
+});
+
+test("PCM (limitation): a bleed copy whose delay falls off the 5 ms lag grid is not detected", () => {
+ const detector = new MeetingEchoLeakDetector();
+ const reference = fx.makeSeededNoise({ durationMs: REF_MS, amplitude: 0.2, seed: 41 });
+ feedReference(detector, reference);
+ const mic = delayedReferenceSlice(reference, 102.5, fx.dbToGain(-12)); // 2460 samples: 60 off the 120-sample grid
+
+ const analysis = detector.analyzeMicChunk(fx.toInt16Buffer(mic), REF_MS);
+
+ assert.equal(
+ analysis.state,
+ "clean_local",
+ "white-noise bleed 60 samples off-grid decorrelates completely"
+ );
+ assert.ok(analysis.correlation < 0.3, `corr ${analysis.correlation}`);
+});
+
+test("PCM (limitation): a bleed copy below MIN_RMS is returned unanalyzed as clean_local", () => {
+ const detector = new MeetingEchoLeakDetector();
+ const reference = fx.makeSeededNoise({ durationMs: REF_MS, amplitude: 0.2, seed: 51 });
+ feedReference(detector, reference);
+ const mic = delayedReferenceSlice(reference, 100, 0.04); // rms ≈ 0.0046 < 0.006
+
+ const analysis = detector.analyzeMicChunk(fx.toInt16Buffer(mic), REF_MS);
+
+ assert.ok(analysis.rms < 0.006, `rms ${analysis.rms}`);
+ assert.equal(analysis.state, "clean_local");
+ assert.equal(analysis.correlation, 0);
+ assert.equal(analysis.shouldMute, false);
+});
diff --git a/test/helpers/meetingMicGate.test.js b/test/helpers/meetingMicGate.test.js
new file mode 100644
index 000000000..4c2f9316d
--- /dev/null
+++ b/test/helpers/meetingMicGate.test.js
@@ -0,0 +1,209 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const gate = require("../../src/helpers/meetingMicGate");
+const fx = require("./harness/pcmFixtures");
+
+test("computeChunkStats matches the inline RMS/peak math (Int16 / 0x7fff)", () => {
+ const buf = fx.toInt16Buffer(new Float32Array([0.5, -0.5, 0.25, -0.25]));
+ const { rms, peak, sampleCount } = gate.computeChunkStats(buf);
+ assert.equal(sampleCount, 4);
+ assert.ok(Math.abs(peak - 16384 / 0x7fff) < 1e-6);
+ const expectedRms = Math.sqrt(((16384 / 0x7fff) ** 2 * 2 + (8192 / 0x7fff) ** 2 * 2) / 4);
+ assert.ok(Math.abs(rms - expectedRms) < 1e-6);
+});
+
+test("computeChunkStats returns zeros for buffers shorter than one sample", () => {
+ assert.deepEqual(gate.computeChunkStats(Buffer.alloc(1)), { rms: 0, peak: 0, sampleCount: 0 });
+ assert.deepEqual(gate.computeChunkStats(Buffer.alloc(0)), { rms: 0, peak: 0, sampleCount: 0 });
+});
+
+test("computeChunkStats honours byteOffset on subarray views (matches a fresh copy of the same samples)", () => {
+ const track = new Float32Array([0.5, -0.5, 0.25, -0.25, 0.75, -0.75]);
+ const view = fx.chunkBuffer(fx.toInt16Buffer(track), 3)[1]; // second 3-sample chunk, byteOffset 6
+ assert.ok(view.byteOffset > 0, `fixture must be an offset view (byteOffset ${view.byteOffset})`);
+ const copy = Buffer.from(view); // fresh buffer, byteOffset 0, same bytes
+ assert.deepEqual(gate.computeChunkStats(view), gate.computeChunkStats(copy));
+ assert.equal(gate.computeChunkStats(view).sampleCount, 3);
+});
+
+const cases = [
+ // [label, mode, source, rms, peak, systemSpeaking, expected]
+ [
+ "streaming mic silence zeroes",
+ "streaming",
+ "mic",
+ 0.001,
+ 0.04,
+ false,
+ { action: "zero", reason: "silence" },
+ ],
+ [
+ "streaming mic silence needs BOTH rms and peak below",
+ "streaming",
+ "mic",
+ 0.001,
+ 0.06,
+ false,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming mic exactly at the silence rms floor is not silent (strict <)",
+ "streaming",
+ "mic",
+ 0.0015,
+ 0.04,
+ false,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming mic exactly at the silence peak floor is not silent (strict <)",
+ "streaming",
+ "mic",
+ 0.001,
+ 0.05,
+ false,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming mic quiet + system speaking zeroes (bleed floor)",
+ "streaming",
+ "mic",
+ 0.01,
+ 0.06,
+ true,
+ { action: "zero", reason: "bleed_floor" },
+ ],
+ [
+ "streaming mic quiet + system silent sends",
+ "streaming",
+ "mic",
+ 0.01,
+ 0.06,
+ false,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming mic at the rms ceiling is not quiet (strict <)",
+ "streaming",
+ "mic",
+ 0.018,
+ 0.06,
+ true,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming mic at the peak ceiling is not quiet (strict <)",
+ "streaming",
+ "mic",
+ 0.01,
+ 0.07,
+ true,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming loud mic sends",
+ "streaming",
+ "mic",
+ 0.1,
+ 0.5,
+ true,
+ { action: "send", reason: null },
+ ],
+ [
+ "streaming system source is never gated",
+ "streaming",
+ "system",
+ 0.0,
+ 0.0,
+ true,
+ { action: "send", reason: null },
+ ],
+ [
+ "local silence skips any source",
+ "local",
+ "system",
+ 0.001,
+ 0.04,
+ false,
+ { action: "skip", reason: "silence" },
+ ],
+ [
+ "local mic quiet + system speaking skips (system-dominant)",
+ "local",
+ "mic",
+ 0.01,
+ 0.06,
+ true,
+ { action: "skip", reason: "system_dominant" },
+ ],
+ [
+ "local system quiet + system speaking is not gated",
+ "local",
+ "system",
+ 0.01,
+ 0.06,
+ true,
+ { action: "send", reason: null },
+ ],
+ ["local loud mic sends", "local", "mic", 0.1, 0.5, true, { action: "send", reason: null }],
+];
+
+for (const [label, mode, source, rms, peak, systemSpeaking, expected] of cases) {
+ test(`resolveMicChunkAction: ${label}`, () => {
+ const verdict = gate.resolveMicChunkAction({
+ mode,
+ source,
+ rms,
+ peak,
+ sampleCount: 800,
+ isSystemSpeaking: () => systemSpeaking,
+ });
+ assert.deepEqual(verdict, expected);
+ });
+}
+
+test("resolveMicChunkAction sends empty chunks unchanged in both modes", () => {
+ for (const mode of ["streaming", "local"]) {
+ assert.deepEqual(
+ gate.resolveMicChunkAction({
+ mode,
+ source: "mic",
+ rms: 0,
+ peak: 0,
+ sampleCount: 0,
+ isSystemSpeaking: () => true,
+ }),
+ { action: "send", reason: null }
+ );
+ }
+});
+
+test("resolveMicChunkAction only consults isSystemSpeaking when the chunk is quiet (preserves the local short-circuit)", () => {
+ let calls = 0;
+ gate.resolveMicChunkAction({
+ mode: "local",
+ source: "mic",
+ rms: 0.5,
+ peak: 0.9,
+ sampleCount: 800,
+ isSystemSpeaking: () => ((calls += 1), true),
+ });
+ assert.equal(calls, 0);
+ gate.resolveMicChunkAction({
+ mode: "local",
+ source: "mic",
+ rms: 0.01,
+ peak: 0.06,
+ sampleCount: 800,
+ isSystemSpeaking: () => ((calls += 1), false),
+ });
+ assert.equal(calls, 1);
+});
+
+test("exports the exact production thresholds", () => {
+ assert.equal(gate.MEETING_MIC_SILENCE_RMS, 0.0015);
+ assert.equal(gate.MEETING_MIC_SILENCE_PEAK, 0.05);
+ assert.equal(gate.MEETING_MIC_BLEED_RMS_CEILING, 0.018);
+ assert.equal(gate.MEETING_MIC_BLEED_PEAK_CEILING, 0.07);
+});
diff --git a/test/helpers/meetingMicHoldback.test.js b/test/helpers/meetingMicHoldback.test.js
index 8bdc45e01..a7aff705f 100644
--- a/test/helpers/meetingMicHoldback.test.js
+++ b/test/helpers/meetingMicHoldback.test.js
@@ -226,3 +226,238 @@ test("segments without a commit time fall back to the capture window only", () =
true
);
});
+
+const {
+ isRiskyMicDuplicateProfile,
+ isDuplicateMicSegment,
+ selectRacingMicEntryIndices,
+ partitionOverlappingPendingMicFinals,
+} = require("../../src/helpers/meetingMicHoldback");
+
+const DUPLICATE_WINDOW = 6000;
+const RETRACT_WINDOW = 4000;
+
+test("isRiskyMicDuplicateProfile: warmup alone is risky, even with no suppression", () => {
+ assert.equal(isRiskyMicDuplicateProfile({ suppression: null, inStartupWarmup: true }), true);
+});
+
+test("characterization: isRiskyMicDuplicateProfile treats systemSpeaking alone as risky (D4b changes this)", () => {
+ assert.equal(
+ isRiskyMicDuplicateProfile({ suppression: { systemSpeaking: true, reason: "clean" } }),
+ true
+ );
+});
+
+test("isRiskyMicDuplicateProfile: bleed evidence, render bleed, or double_talk are risky; clean is not", () => {
+ assert.equal(isRiskyMicDuplicateProfile({ suppression: { reason: "double_talk" } }), true);
+ assert.equal(isRiskyMicDuplicateProfile({ suppression: { hasBleedEvidence: true } }), true);
+ assert.equal(isRiskyMicDuplicateProfile({ suppression: { likelyRenderBleed: true } }), true);
+ // Today's closure yields `undefined` here (last operand of the `||` chain), not `false`;
+ // callers only test truthiness. Phase 1 may normalize the return to a strict boolean.
+ assert.equal(!!isRiskyMicDuplicateProfile({ suppression: { reason: "clean_local" } }), false);
+ assert.equal(isRiskyMicDuplicateProfile({ suppression: null }), false);
+ assert.equal(isRiskyMicDuplicateProfile({}), false);
+});
+
+test("isDuplicateMicSegment: bleed evidence uses the strict matcher; double_talk uses the relaxed matcher", () => {
+ const calls = [];
+ const matcher = (source, text, timestamp, options) => {
+ calls.push({ source, text, timestamp, options });
+ return true;
+ };
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: { hasBleedEvidence: true },
+ hasNearbyTranscriptMatch: matcher,
+ }),
+ true
+ );
+ assert.deepEqual(calls[0], { source: "system", text: "hi", timestamp: 10, options: undefined });
+
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: { reason: "double_talk" },
+ hasNearbyTranscriptMatch: matcher,
+ }),
+ true
+ );
+ assert.deepEqual(calls[1].options, { relaxed: true });
+});
+
+test("isDuplicateMicSegment: bleed evidence without a strict match falls through to double_talk only if flagged", () => {
+ const strictFalseRelaxedTrue = (source, text, timestamp, options) => !!options?.relaxed;
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: { hasBleedEvidence: true, reason: "render_bleed" },
+ hasNearbyTranscriptMatch: strictFalseRelaxedTrue,
+ }),
+ false
+ );
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: { hasBleedEvidence: true, reason: "double_talk" },
+ hasNearbyTranscriptMatch: strictFalseRelaxedTrue,
+ }),
+ true
+ );
+});
+
+test("isDuplicateMicSegment: systemSpeaking-only or no suppression never calls the matcher", () => {
+ let calls = 0;
+ const matcher = () => ((calls += 1), true);
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: { systemSpeaking: true },
+ hasNearbyTranscriptMatch: matcher,
+ }),
+ false
+ );
+ assert.equal(
+ isDuplicateMicSegment({
+ text: "hi",
+ timestamp: 10,
+ suppression: null,
+ hasNearbyTranscriptMatch: matcher,
+ }),
+ false
+ );
+ assert.equal(calls, 0);
+});
+
+const micSeg = (overrides) => ({
+ source: "mic",
+ text: "we should ship on friday",
+ timestamp: NOW - 1000,
+ committedAt: NOW - 900,
+ suppressionReason: null,
+ hasBleedEvidence: false,
+ likelyRenderBleed: false,
+ ...overrides,
+});
+
+test("selectRacingMicEntryIndices removes bleed-flagged mic entries that overlap the arriving system final, newest first", () => {
+ const segments = [
+ { source: "system", text: "unrelated", timestamp: NOW - 5000 },
+ micSeg({ hasBleedEvidence: true, timestamp: NOW - 3000, committedAt: NOW - 2900 }),
+ micSeg({
+ text: "clean speech",
+ suppressionReason: null,
+ timestamp: NOW - 2000,
+ committedAt: NOW - 1900,
+ }),
+ micSeg({ suppressionReason: "double_talk", timestamp: NOW - 1000, committedAt: NOW - 900 }),
+ ];
+ const seen = [];
+ const matcher = (source, text, timestamp, options) => {
+ seen.push({ text, relaxed: !!options?.relaxed, extra: options?.extraSegment });
+ return true;
+ };
+ const indices = selectRacingMicEntryIndices({
+ segments,
+ systemText: "we should ship on friday",
+ systemTimestamp: NOW,
+ hasNearbyTranscriptMatch: matcher,
+ duplicateWindowMs: DUPLICATE_WINDOW,
+ retractWindowMs: RETRACT_WINDOW,
+ });
+ assert.deepEqual(
+ indices,
+ [3, 1],
+ "descending; the non-risky clean entry (index 2) is never removed"
+ );
+ assert.deepEqual(
+ seen.map((s) => s.relaxed),
+ [true, false, false],
+ "double_talk candidates use the relaxed matcher"
+ );
+ assert.deepEqual(seen[0].extra, { text: "we should ship on friday", timestamp: NOW });
+});
+
+test("selectRacingMicEntryIndices skips candidates outside their per-candidate window (6 s bleed / 4 s otherwise)", () => {
+ const segments = [
+ micSeg({ hasBleedEvidence: true, timestamp: NOW - 5500, committedAt: NOW - 5400 }), // within 6 s
+ micSeg({ suppressionReason: "double_talk", timestamp: NOW - 4500, committedAt: NOW - 4400 }), // outside 4 s
+ ];
+ const indices = selectRacingMicEntryIndices({
+ segments,
+ systemText: "x",
+ systemTimestamp: NOW,
+ hasNearbyTranscriptMatch: () => true,
+ duplicateWindowMs: DUPLICATE_WINDOW,
+ retractWindowMs: RETRACT_WINDOW,
+ });
+ assert.deepEqual(indices, [0]);
+});
+
+test("selectRacingMicEntryIndices without a system timestamp evaluates every risky candidate", () => {
+ const segments = [
+ micSeg({ hasBleedEvidence: true, timestamp: NOW - 50_000, committedAt: NOW - 49_000 }),
+ micSeg({ timestamp: NOW - 100 }),
+ ];
+ const indices = selectRacingMicEntryIndices({
+ segments,
+ systemText: "x",
+ systemTimestamp: null,
+ hasNearbyTranscriptMatch: () => true,
+ duplicateWindowMs: DUPLICATE_WINDOW,
+ retractWindowMs: RETRACT_WINDOW,
+ });
+ assert.deepEqual(indices, [0]);
+});
+
+test("characterization: the backward-scan break stops before an older bleed-flagged entry whose commit time still races (Phase 1 flips break→continue)", () => {
+ // From the 2026-08-17 verification: array is committedAt-ordered, windows are per-candidate.
+ const E = micSeg({ hasBleedEvidence: true, timestamp: NOW - 8300, committedAt: NOW - 5300 }); // commit race passes the 6 s window
+ const C = micSeg({ timestamp: NOW - 7500, committedAt: NOW - 4500 }); // non-bleed: fails 4 s on both races, ts < NOW-6000 → break
+ const indices = selectRacingMicEntryIndices({
+ segments: [E, C],
+ systemText: "x",
+ systemTimestamp: NOW,
+ hasNearbyTranscriptMatch: () => true,
+ duplicateWindowMs: DUPLICATE_WINDOW,
+ retractWindowMs: RETRACT_WINDOW,
+ });
+ assert.deepEqual(indices, [], "TODAY: E is never scanned. Phase 1 expects [0].");
+});
+
+test("partitionOverlappingPendingMicFinals splits pending finals by system overlap, preserving order and using relaxed matching for double_talk", () => {
+ const pending = [
+ entry({ text: "a", micSuppression: { reason: "double_talk" } }),
+ entry({ text: "b", micSuppression: null }),
+ entry({ text: "c", micSuppression: { hasBleedEvidence: true } }),
+ ];
+ const seen = [];
+ const matcher = (source, text, timestamp, options) => {
+ seen.push({ text, relaxed: !!options?.relaxed });
+ return text !== "b";
+ };
+ const { kept, removed } = partitionOverlappingPendingMicFinals({
+ pending,
+ systemText: "sys",
+ systemTimestamp: NOW,
+ hasNearbyTranscriptMatch: matcher,
+ });
+ assert.deepEqual(
+ kept.map((p) => p.text),
+ ["b"]
+ );
+ assert.deepEqual(
+ removed.map((p) => p.text),
+ ["a", "c"]
+ );
+ assert.deepEqual(seen, [
+ { text: "a", relaxed: true },
+ { text: "b", relaxed: false },
+ { text: "c", relaxed: false },
+ ]);
+});
diff --git a/test/helpers/openaiRealtimeStreaming.test.js b/test/helpers/openaiRealtimeStreaming.test.js
index 9b75ebaf3..8d69041d9 100644
--- a/test/helpers/openaiRealtimeStreaming.test.js
+++ b/test/helpers/openaiRealtimeStreaming.test.js
@@ -518,3 +518,126 @@ test("completedSegments accumulate across turns", async () => {
assert.equal(streaming.completedSegments.length, 2);
assert.equal(lastFull, "Hello world How are you");
});
+
+test("BYOK session.update is byte-for-byte today's payload when no VAD/language/noise options are passed", async () => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+
+ const connected = streaming.connect({
+ apiKey: "sk-test",
+ model: "gpt-4o-mini-transcribe",
+ // Phase 1 will add these; today connect() must ignore them entirely.
+ language: "en",
+ keyterms: ["OpenWhispr"],
+ sampleRate: 24000,
+ createSocket: async () => socket,
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit("message", JSON.stringify({ type: "session.created" }));
+
+ const updates = socket.sent
+ .map((raw) => JSON.parse(raw))
+ .filter((e) => e.type === "session.update");
+ assert.equal(updates.length, 1, "exactly one session.update after session.created");
+ assert.deepEqual(updates[0], {
+ type: "session.update",
+ session: {
+ type: "transcription",
+ audio: {
+ input: {
+ format: { type: "audio/pcm", rate: 24000 },
+ transcription: { model: "gpt-4o-mini-transcribe" },
+ turn_detection: {
+ type: "server_vad",
+ threshold: 0.6,
+ silence_duration_ms: 600,
+ prefix_padding_ms: 500,
+ },
+ },
+ },
+ },
+ });
+
+ socket.emit("message", JSON.stringify({ type: "session.updated" }));
+ await connected;
+ streaming.cleanup();
+});
+
+test("dictation-style connect (inputRate 16000, custom socket factory) declares the 16kHz format and the same VAD", async () => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ const factoryCalls = [];
+
+ const connected = streaming.connect({
+ apiKey: "tk-secret",
+ model: "voxtral-mini-4b-realtime",
+ inputRate: 16000,
+ createSocket: () => {
+ factoryCalls.push("called");
+ return Promise.resolve(socket);
+ },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ socket.readyState = WS.OPEN;
+ socket.emit("message", JSON.stringify({ type: "session.created" }));
+
+ const [update] = socket.sent
+ .map((raw) => JSON.parse(raw))
+ .filter((e) => e.type === "session.update");
+ assert.equal(factoryCalls.length, 1);
+ assert.deepEqual(update.session.audio.input.format, { type: "audio/pcm", rate: 16000 });
+ assert.equal(update.session.audio.input.transcription.model, "voxtral-mini-4b-realtime");
+ assert.deepEqual(update.session.audio.input.turn_detection, {
+ type: "server_vad",
+ threshold: 0.6,
+ silence_duration_ms: 600,
+ prefix_padding_ms: 500,
+ });
+ assert.equal("noise_reduction" in update.session.audio.input, false);
+ assert.equal("language" in update.session.audio.input.transcription, false);
+
+ socket.emit("message", JSON.stringify({ type: "session.updated" }));
+ await connected;
+ streaming.cleanup();
+});
+
+test("characterization: a final that lands during disconnect()'s commit window reaches onFinalTranscript WITHOUT its timestamp (Phase 1 forwards it)", async () => {
+ const OpenAIRealtimeStreaming = (await load()).default;
+ const streaming = new OpenAIRealtimeStreaming();
+ const socket = makeFakeSocket(WS.CONNECTING);
+ await connectPreconfigured(streaming, socket);
+
+ const calls = [];
+ streaming.onFinalTranscript = (text, timestamp) => calls.push({ text, timestamp });
+ streaming.sendAudio(Buffer.alloc(1600, 1)); // audioBytesSent > 0 so disconnect() commits
+
+ const disconnecting = streaming.disconnect();
+ await new Promise((resolve) => setImmediate(resolve));
+
+ const commits = socket.sent
+ .filter((raw) => typeof raw === "string")
+ .map((raw) => JSON.parse(raw))
+ .filter((e) => e.type === "input_audio_buffer.commit");
+ assert.equal(commits.length, 1, "disconnect() commits the trailing buffer");
+
+ socket.emit("message", JSON.stringify({ type: "input_audio_buffer.speech_started" }));
+ socket.emit(
+ "message",
+ JSON.stringify({
+ type: "conversation.item.input_audio_transcription.completed",
+ transcript: "tail words",
+ })
+ );
+ const result = await disconnecting;
+
+ assert.equal(result.text, "tail words", "the tail is returned to the caller");
+ assert.equal(calls.length, 1, "the tail also reaches the live onFinalTranscript handler");
+ assert.equal(calls[0].text, "tail words");
+ // TODAY the temporary onFinalTranscript wrapper that disconnect() installs while
+ // awaiting the commit forwards only `text` to the previous handler.
+ // Phase 1 changes this line to `typeof calls[0].timestamp === "number"`.
+ assert.equal(calls[0].timestamp, undefined);
+});
diff --git a/test/helpers/pcmFixtures.test.js b/test/helpers/pcmFixtures.test.js
new file mode 100644
index 000000000..5fcb6bcfa
--- /dev/null
+++ b/test/helpers/pcmFixtures.test.js
@@ -0,0 +1,51 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const fx = require("./harness/pcmFixtures");
+
+test("makeSine has the expected length and RMS ≈ amplitude/√2", () => {
+ const sine = fx.makeSine({ frequencyHz: 440, durationMs: 100, amplitude: 0.5 });
+ assert.equal(sine.length, 2400);
+ const expected = 0.5 / Math.SQRT2;
+ assert.ok(Math.abs(fx.rmsOf(sine) - expected) < expected * 0.02, `rms ${fx.rmsOf(sine)}`);
+});
+
+test("makeSeededNoise is deterministic per seed and bounded by amplitude", () => {
+ const a = fx.makeSeededNoise({ durationMs: 50, amplitude: 0.2, seed: 7 });
+ const b = fx.makeSeededNoise({ durationMs: 50, amplitude: 0.2, seed: 7 });
+ const c = fx.makeSeededNoise({ durationMs: 50, amplitude: 0.2, seed: 8 });
+ assert.deepEqual(Array.from(a), Array.from(b));
+ assert.notDeepEqual(Array.from(a), Array.from(c));
+ assert.ok(a.every((v) => v >= -0.2 && v <= 0.2));
+ assert.equal(a.length, 1200);
+});
+
+test("delayBy prepends silence and preserves the payload", () => {
+ const src = fx.makeSine({ frequencyHz: 100, durationMs: 10, amplitude: 0.5 });
+ const delayed = fx.delayBy(src, 5);
+ assert.equal(delayed.length, src.length + 120);
+ assert.ok(delayed.subarray(0, 120).every((v) => v === 0));
+ assert.deepEqual(Array.from(delayed.subarray(120)), Array.from(src));
+});
+
+test("mix sums and clamps; scale multiplies", () => {
+ // Values chosen to be exactly representable in float32 so deepEqual is safe.
+ const one = new Float32Array([0.5, -0.5, 0.75]);
+ const two = new Float32Array([0.5, -0.9]);
+ assert.deepEqual(Array.from(fx.mix(one, two)), [1, -1, 0.75]);
+ assert.deepEqual(Array.from(fx.scale(one, 0.5)), [0.25, -0.25, 0.375]);
+ assert.ok(Math.abs(fx.dbToGain(-12) - 0.2512) < 0.001);
+});
+
+test("toInt16Buffer round-trips within 1 LSB and chunkBuffer splits by sample count", () => {
+ const track = new Float32Array([0, 0.5, -0.5, 1, -1, 2, -2]);
+ const buf = fx.toInt16Buffer(track);
+ assert.equal(buf.length, 14);
+ const view = new Int16Array(buf.buffer, buf.byteOffset, 7);
+ assert.deepEqual(Array.from(view), [0, 16384, -16384, 32767, -32768, 32767, -32768]);
+ const chunks = fx.chunkBuffer(buf, 3);
+ assert.deepEqual(
+ chunks.map((c) => c.length),
+ [6, 6, 2]
+ );
+});
diff --git a/test/helpers/realtimeTokenProviders.test.js b/test/helpers/realtimeTokenProviders.test.js
index 9f08341e6..86bd9beee 100644
--- a/test/helpers/realtimeTokenProviders.test.js
+++ b/test/helpers/realtimeTokenProviders.test.js
@@ -158,3 +158,42 @@ test("missing byok keys throw configuration errors, not token errors", async ()
);
}
});
+
+test('wire bodies: dictation posts the bare {"streams":1}; meetings post model+language+streams', async () => {
+ const { fetchRealtimeTokenForProvider } = await load();
+ const wire = [];
+ const cloudDeps = deps({
+ postServerToken: async (path, body) => {
+ // JSON.stringify drops undefined keys exactly like the real fetch does.
+ wire.push({ path, json: JSON.stringify(body) });
+ return { clientSecret: "cs-single", clientSecrets: ["cs-a", "cs-b"] };
+ },
+ });
+
+ // Dictation: ipcHandlers' connectDictationStreaming passes only { mode, provider }.
+ await fetchRealtimeTokenForProvider("openai-realtime", cloudDeps, { mode: "openwhispr" });
+ // Meeting with system audio.
+ await fetchRealtimeTokenForProvider(
+ "openai-realtime",
+ cloudDeps,
+ { mode: "openwhispr", model: "gpt-4o-mini-transcribe", language: "en" },
+ { streams: 2 }
+ );
+ // Meeting whose system audio is unsupported (connectRealtimeStreaming's single-stream
+ // branch) — still carries model+language; streams defaults to 1.
+ await fetchRealtimeTokenForProvider(
+ "openai-realtime",
+ cloudDeps,
+ { mode: "openwhispr", model: "gpt-4o-mini-transcribe", language: undefined },
+ { streams: 1 }
+ );
+
+ assert.deepEqual(wire, [
+ { path: "/api/openai-realtime-token", json: '{"streams":1}' },
+ {
+ path: "/api/openai-realtime-token",
+ json: '{"model":"gpt-4o-mini-transcribe","language":"en","streams":2}',
+ },
+ { path: "/api/openai-realtime-token", json: '{"model":"gpt-4o-mini-transcribe","streams":1}' },
+ ]);
+});
diff --git a/test/helpers/tinfoilRealtimeStreaming.test.js b/test/helpers/tinfoilRealtimeStreaming.test.js
index 40b7f1edb..89f960e00 100644
--- a/test/helpers/tinfoilRealtimeStreaming.test.js
+++ b/test/helpers/tinfoilRealtimeStreaming.test.js
@@ -196,6 +196,11 @@ test("meeting sessions declare the 24kHz PCM input format", async () => {
const [update] = sentEvents(socket, "session.update");
assert.deepEqual(update.session.audio.input.format, { type: "audio/pcm", rate: 24000 });
assert.equal(update.session.audio.input.transcription.model, "voxtral-mini-4b-realtime");
+ assert.deepEqual(
+ update.session.audio.input.turn_detection,
+ { type: "server_vad", threshold: 0.6, silence_duration_ms: 600, prefix_padding_ms: 500 },
+ "subclass inherits the base VAD; Phase 1 changes this only when options are passed"
+ );
socket.emit("message", JSON.stringify({ type: "session.updated" }));
await connected;
diff --git a/test/stores/meetingRecordingStoreImports.test.js b/test/stores/meetingRecordingStoreImports.test.js
new file mode 100644
index 000000000..145608767
--- /dev/null
+++ b/test/stores/meetingRecordingStoreImports.test.js
@@ -0,0 +1,21 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("meetingRecordingStore still loads under the renderer harness after the reducer extraction", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-meeting-store-import-test-",
+ });
+
+ const store = await vite.ssrLoadModule("/stores/meetingRecordingStore.ts");
+ const reducer = await vite.ssrLoadModule("/stores/meetingSegmentReducer.ts");
+
+ assert.equal(typeof store.startRecording, "function");
+ assert.equal(typeof store.useMeetingRecordingStore?.getState, "function");
+ assert.equal(typeof reducer.reduceMeetingSegmentEvent, "function");
+ const initial = store.useMeetingRecordingStore.getState();
+ assert.deepEqual(initial.segments, []);
+ assert.equal(initial.micPartial, "");
+ assert.equal(initial.systemPartial, "");
+});
diff --git a/test/stores/meetingSegmentReducer.test.js b/test/stores/meetingSegmentReducer.test.js
new file mode 100644
index 000000000..3bb456e1e
--- /dev/null
+++ b/test/stores/meetingSegmentReducer.test.js
@@ -0,0 +1,170 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/stores/meetingSegmentReducer.ts");
+
+const seg = (overrides) => ({ id: "x", text: "t", source: "mic", ...overrides });
+const state = (overrides) => ({ segments: [], micPartial: "", systemPartial: "", ...overrides });
+const deps = (overrides) => ({
+ mintSegmentId: () => "seg-1",
+ decorateFinal: (s) => s,
+ ...overrides,
+});
+
+test("retract removes only rows matching source+timestamp+text exactly, and reports them", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const keep = seg({ id: "a", text: "hello", source: "mic", timestamp: 100 });
+ const gone = seg({ id: "b", text: "hello", source: "mic", timestamp: 200 });
+ const other = seg({ id: "c", text: "hello", source: "system", timestamp: 200 });
+ const r = reduceMeetingSegmentEvent(
+ state({ segments: [keep, gone, other], micPartial: "live" }),
+ { type: "retract", source: "mic", text: "hello", timestamp: 200 },
+ deps()
+ );
+ assert.equal(r.kind, "retract");
+ assert.deepEqual(
+ r.state.segments.map((s) => s.id),
+ ["a", "c"]
+ );
+ assert.deepEqual(
+ r.removed.map((s) => s.id),
+ ["b"]
+ );
+ assert.equal(r.state.micPartial, "live", "retract never touches partials");
+});
+
+test("retract with no match leaves segments intact and reports nothing", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const a = seg({ id: "a", text: "hello", timestamp: 100 });
+ const r = reduceMeetingSegmentEvent(
+ state({ segments: [a] }),
+ { type: "retract", source: "mic", text: "nope", timestamp: 100 },
+ deps()
+ );
+ assert.deepEqual(r.state.segments, [a]);
+ assert.deepEqual(r.removed, []);
+});
+
+test("partial sets only its own source's slot", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const mic = reduceMeetingSegmentEvent(
+ state({ systemPartial: "sys" }),
+ { type: "partial", source: "mic", text: "um" },
+ deps()
+ );
+ assert.deepEqual(mic, {
+ kind: "partial",
+ source: "mic",
+ state: state({ micPartial: "um", systemPartial: "sys" }),
+ });
+ const sys = reduceMeetingSegmentEvent(
+ state({ micPartial: "me" }),
+ { type: "partial", source: "system", text: "they" },
+ deps()
+ );
+ assert.deepEqual(sys, {
+ kind: "partial",
+ source: "system",
+ state: state({ micPartial: "me", systemPartial: "they" }),
+ });
+});
+
+test("final mints an id, normalizes, decorates, appends when newest, and clears only its own partial", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const decorated = [];
+ const r = reduceMeetingSegmentEvent(
+ state({
+ segments: [seg({ id: "a", timestamp: 100 })],
+ micPartial: "live",
+ systemPartial: "sys",
+ }),
+ { type: "final", source: "mic", text: "done", timestamp: 200 },
+ deps({
+ mintSegmentId: () => "seg-42",
+ decorateFinal: (s) => {
+ decorated.push(s.id);
+ return { ...s, speaker: "speaker_0" };
+ },
+ })
+ );
+ assert.equal(r.kind, "final");
+ assert.equal(r.index, 1);
+ assert.deepEqual(
+ decorated,
+ ["seg-42"],
+ "decorateFinal sees the freshly minted, normalized segment"
+ );
+ assert.equal(r.inserted.speaker, "speaker_0");
+ assert.equal(r.inserted.speakerLocked, false, "normalizeTranscriptSegment ran");
+ assert.deepEqual(
+ r.state.segments.map((s) => s.id),
+ ["a", "seg-42"]
+ );
+ assert.equal(r.state.micPartial, "");
+ assert.equal(r.state.systemPartial, "sys");
+});
+
+test("final for the system source clears systemPartial and leaves micPartial", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const r = reduceMeetingSegmentEvent(
+ state({ micPartial: "me", systemPartial: "they" }),
+ { type: "final", source: "system", text: "ok", timestamp: 1 },
+ deps()
+ );
+ assert.equal(r.state.micPartial, "me");
+ assert.equal(r.state.systemPartial, "");
+});
+
+test("insertSegmentByTimestamp: older timestamps insert before newer ones; equal timestamps go after existing (strict >)", async () => {
+ const { insertSegmentByTimestamp } = await load();
+ const base = [seg({ id: "a", timestamp: 100 }), seg({ id: "c", timestamp: 300 })];
+ assert.deepEqual(
+ insertSegmentByTimestamp(base, seg({ id: "b", timestamp: 200 })).segments.map((s) => s.id),
+ ["a", "b", "c"]
+ );
+ assert.deepEqual(
+ insertSegmentByTimestamp(base, seg({ id: "a2", timestamp: 100 })).segments.map((s) => s.id),
+ ["a", "a2", "c"]
+ );
+ assert.deepEqual(
+ insertSegmentByTimestamp(base, seg({ id: "z", timestamp: 50 })).segments.map((s) => s.id),
+ ["z", "a", "c"]
+ );
+ assert.equal(insertSegmentByTimestamp(base, seg({ id: "z", timestamp: 50 })).index, 0);
+});
+
+test("characterization: an incoming final without a timestamp appends at the END (`?? Infinity`), while an existing untimestamped row sorts as 0", async () => {
+ const { insertSegmentByTimestamp } = await load();
+ const base = [
+ seg({ id: "a", timestamp: 100 }),
+ seg({ id: "u" }),
+ seg({ id: "c", timestamp: 300 }),
+ ];
+ assert.deepEqual(
+ insertSegmentByTimestamp(base, seg({ id: "n" })).segments.map((s) => s.id),
+ ["a", "u", "c", "n"]
+ );
+ // A timestamped 200 goes after "u" (treated as 0) and before "c".
+ assert.deepEqual(
+ insertSegmentByTimestamp(base, seg({ id: "m", timestamp: 200 })).segments.map((s) => s.id),
+ ["a", "u", "m", "c"]
+ );
+});
+
+test("reducer never mutates its inputs", async () => {
+ const { reduceMeetingSegmentEvent } = await load();
+ const original = state({ segments: [seg({ id: "a", timestamp: 100 })], micPartial: "x" });
+ const snapshot = JSON.stringify(original);
+ reduceMeetingSegmentEvent(
+ original,
+ { type: "final", source: "mic", text: "y", timestamp: 50 },
+ deps()
+ );
+ reduceMeetingSegmentEvent(
+ original,
+ { type: "retract", source: "mic", text: "t", timestamp: 100 },
+ deps()
+ );
+ reduceMeetingSegmentEvent(original, { type: "partial", source: "mic", text: "p" }, deps());
+ assert.equal(JSON.stringify(original), snapshot);
+});