Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(voice-runtime): gate out quieter voices of other people in live mode

muterCe43ca6e4d8e9
diff --git a/apps/voice-runtime/AGENTS.md b/apps/voice-runtime/AGENTS.md
index 45a9aafb..0b7a6ed0 100644
--- a/apps/voice-runtime/AGENTS.md
+++ b/apps/voice-runtime/AGENTS.md
@@ -34,4 +34,5 @@
- Every track consumer attempt claims its transcript media epoch from TeamHub (`claimVoiceMediaEpoch`) and never counts epochs in memory: a job restarted mid-session (deploy, crash, key change) must not reuse an epoch whose coverage stream an earlier job started.
- Backpressure is bounded. Failure must stop or reconnect the affected track instead of accumulating unbounded PCM.
- Shutdown waits for accepted final/progress callbacks up to a fixed deadline and then exits non-zero if state is uncertain.
+- The Live worker's local gate sends the microphone as silence unless Silero hears speech within `otherSpeakerDb` of the level it learned from the user on this track; quieter voices are other people in the room and neither reach the provider nor pause a reply.
- Never move recording back into the ASR job process; ASR load or failure must never stall the Capture recorder. A recorder never extends an epoch it did not start; TeamHub rejects the conflicting segment and the recorder reports failure.
diff --git a/apps/voice-runtime/acceptance/AGENTS.md b/apps/voice-runtime/acceptance/AGENTS.md
index 423baaf7..76f1b550 100644
--- a/apps/voice-runtime/acceptance/AGENTS.md
+++ b/apps/voice-runtime/acceptance/AGENTS.md
@@ -6,7 +6,7 @@ This directory contains opt-in local acceptance runners for the real Voice media
- `*.ts`: executable acceptance scenarios run through the Voice Runtime package toolchain.
- `live-scenarios/`: opt-in live mode scenarios against xAI with production instructions and tools and mocked tool results (update timing, answer length, silent material, routing to this app's page, the web, the user's computer and apps, background tasks, personal memory). Dump TeamHub's live context first with `LIVE_CONTEXT_OUT=<file> go test -tags voicelivedump ./internal/voicelive -run TestDumpLiveContext` (from `apps/teamhub`), then `LIVE_CONTEXT_FILE=<file> [LIVE_REASONING=none] [LIVE_CUT_OFF_NOTE=off] pnpm --filter @linger/voice-runtime acceptance:live-scenarios [reps] [filter]` (production reasoning is high; `LIVE_CUT_OFF_NOTE=off` leaves out the note a cut-off reply gets, to compare). It prints aggregated metrics only; transcripts go under `.linger-runtime/live-scenarios/`.
-- `live-audio/`: opt-in audio-path scenarios for live mode. Speech synthesized with macOS `say` (Samantha, English) and `ffmpeg` streams in real time into the real LiveVoiceWorker, xAI session, Silero barge-in VAD and Soniox captions; only LiveKit (a real-time playing output) and TeamHub (in-memory tasks, alerts and tool results) are replaced. It measures talk-over and swallowed turns on pauses, barge-in stop time, and when background updates and app events are heard. With the same context dump, `LIVE_CONTEXT_FILE=<file> [LIVE_AUDIO_REPS=n] [LIVE_AUDIO_ONLY=a,b] [LIVE_AUDIO_VAD_MS=ms] pnpm --filter @linger/voice-runtime acceptance:live-audio`. Timelines go under `.linger-runtime/live-audio/`.
+- `live-audio/`: opt-in audio-path scenarios for live mode. Speech synthesized with macOS `say` (Samantha, English) and `ffmpeg` streams in real time into the real LiveVoiceWorker, xAI session, Silero barge-in VAD and Soniox captions; only LiveKit (a real-time playing output) and TeamHub (in-memory tasks, alerts and tool results) are replaced. The microphone carries 24 kHz frames, the rate the worker reads the track at. It measures talk-over and swallowed turns on pauses, barge-in stop time, whether another person in the room (another voice, dulled and reflected, `LIVE_AUDIO_DISTANT_DB` quieter than the user, default 15) cuts a reply off, and when background updates and app events are heard. With the same context dump, `LIVE_CONTEXT_FILE=<file> [LIVE_AUDIO_REPS=n] [LIVE_AUDIO_ONLY=a,b] [LIVE_AUDIO_VAD_MS=ms] [LIVE_AUDIO_DISTANT_DB=db] pnpm --filter @linger/voice-runtime acceptance:live-audio`. Timelines go under `.linger-runtime/live-audio/`.
- Generated PCM, cookies, logs, and provider responses belong under the ignored root `.linger-runtime/`; never add them here.
## Rules
diff --git a/apps/voice-runtime/acceptance/live-audio/live-audio.test.ts b/apps/voice-runtime/acceptance/live-audio/live-audio.test.ts
index 1a081c36..cb9b8827 100644
--- a/apps/voice-runtime/acceptance/live-audio/live-audio.test.ts
+++ b/apps/voice-runtime/acceptance/live-audio/live-audio.test.ts
@@ -27,7 +27,7 @@ const rtc = vi.hoisted(() => {
this.controller.enqueue({
data,
samplesPerChannel: data.length,
- sampleRate: 16_000,
+ sampleRate: 24_000,
channels: 1,
});
}
@@ -129,7 +129,7 @@ const publisher = { identity: `publisher-${sessionId}` };
const ttsDir = mkdtempSync(join(tmpdir(), "live-audio-"));
const ttsCache = new Map<string, Int16Array>();
-/** The words as 16 kHz mono PCM, spoken by a Mandarin system voice. */
+/** The words as 24 kHz mono PCM, the rate the worker reads the track at. */
function speech(text: string) {
let pcm = ttsCache.get(text);
if (!pcm) {
@@ -147,7 +147,7 @@ function speech(text: string) {
"-ac",
"1",
"-ar",
- "16000",
+ "24000",
"-",
],
{ maxBuffer: 1 << 26 },
@@ -158,6 +158,66 @@ function speech(text: string) {
return pcm;
}
+/** RMS of the 32 ms windows that carry speech. */
+function speechLevel(pcm: Int16Array) {
+ let sum = 0;
+ let count = 0;
+ for (let start = 0; start + 512 <= pcm.length; start += 512) {
+ let window = 0;
+ for (let index = start; index < start + 512; index++)
+ window += pcm[index]! * pcm[index]!;
+ if (window / 512 < 100 * 100) continue;
+ sum += window;
+ count += 512;
+ }
+ return Math.sqrt(sum / Math.max(1, count));
+}
+
+const distantCache = new Map<string, Int16Array>();
+/**
+ * Another person in the room: another voice, duller and with reflections as
+ * from across it, `belowDb` quieter than the user's own words.
+ */
+function distantSpeech(text: string, belowDb: number) {
+ const key = `${belowDb}:${text}`;
+ let pcm = distantCache.get(key);
+ if (!pcm) {
+ const aiff = join(ttsDir, `distant-${distantCache.size}.aiff`);
+ execFileSync("say", ["-v", "Daniel", "-o", aiff, text]);
+ const raw = execFileSync(
+ "ffmpeg",
+ [
+ "-loglevel",
+ "error",
+ "-i",
+ aiff,
+ "-af",
+ "lowpass=f=3200,aecho=0.8:0.6:35|70:0.35|0.25",
+ "-f",
+ "s16le",
+ "-ac",
+ "1",
+ "-ar",
+ "24000",
+ "-",
+ ],
+ { maxBuffer: 1 << 26 },
+ );
+ const far = new Int16Array(raw.buffer, raw.byteOffset, raw.length / 2);
+ const gain =
+ (speechLevel(speech(userReference)) / speechLevel(far)) *
+ 10 ** (-belowDb / 20);
+ pcm = far.map((sample) =>
+ Math.max(-32_768, Math.min(32_767, Math.round(sample * gain))),
+ );
+ distantCache.set(key, pcm);
+ }
+ return pcm;
+}
+const userReference = "Research pricing for Notion, Linear and Feishu for me";
+/** How much quieter than the user another person in the room is. */
+const distantDb = Number(env.LIVE_AUDIO_DISTANT_DB || 15);
+
interface Task {
task_id: string;
started_in_this_call: boolean;
@@ -363,7 +423,7 @@ class Call {
this.pump = setInterval(() => {
const due = Math.floor((rtc.now() - start) / 20);
for (; sent < due; sent++)
- track.push(this.mic.shift() ?? new Int16Array(320));
+ track.push(this.mic.shift() ?? new Int16Array(480));
}, 10);
await running;
await this.wait(
@@ -457,18 +517,25 @@ class Call {
}
/** Speaks the segments (text, or a silent gap in ms) and resolves when done. */
- async say(...segments: Array<string | number>) {
+ async say(
+ ...segments: Array<string | number | { distant: string; belowDb: number }>
+ ) {
this.note("mic_start", {
- text: segments.filter((s) => typeof s === "string").join(" … "),
+ text: segments
+ .map((s) => (typeof s === "object" ? `(distant) ${s.distant}` : s))
+ .filter((s) => typeof s === "string")
+ .join(" … "),
});
for (const segment of segments) {
const pcm =
typeof segment === "number"
- ? new Int16Array(segment * 16)
- : speech(segment);
- for (let offset = 0; offset < pcm.length; offset += 320) {
- const frame = new Int16Array(320);
- frame.set(pcm.subarray(offset, offset + 320));
+ ? new Int16Array(segment * 24)
+ : typeof segment === "object"
+ ? distantSpeech(segment.distant, segment.belowDb)
+ : speech(segment);
+ for (let offset = 0; offset < pcm.length; offset += 480) {
+ const frame = new Int16Array(480);
+ frame.set(pcm.subarray(offset, offset + 480));
this.mic.push(frame);
}
}
@@ -503,6 +570,12 @@ class Call {
playing() {
return (this.source?.queuedDuration ?? 0) > 0;
}
+ /** When the reply was first cleared from the output after `from`. */
+ firstClearAfter(from: number) {
+ return (this.source?.clears ?? [])
+ .map((at) => at - this.t0)
+ .find((at) => at >= from);
+ }
/** Waits until the line has been quiet for `quietMs` (output and replies). */
async settle(quietMs = 2_500, limitMs = 60_000) {
const deadline = rtc.now() + limitMs;
@@ -690,6 +763,7 @@ const scenarios: Record<
await call.wait(() => call.firstSoundAfter(asked) !== undefined, 20_000);
await sleep(3_000);
const start = call.at();
+ const playingAtStart = call.playing();
await call.say("Wait, stop for a moment");
const end = call.at();
await call.settle();
@@ -702,9 +776,65 @@ const scenarios: Record<
stopAfterSpeechMs: lastOld
? Math.max(0, Math.round(lastOld.end - start))
: null,
+ clearedAfterMs: (() => {
+ const cleared = call.firstClearAfter(start);
+ return cleared === undefined ? null : Math.round(cleared - start);
+ })(),
+ playingAtStart,
responded: call.firstSoundAfter(end) !== undefined,
};
},
+ // Someone else in the room talks while the live voice replies; the reply
+ // goes on.
+ async backgroundTalk(call) {
+ await call.say(
+ "Explain in detail why so many SaaS products charge per seat",
+ );
+ const asked = call.at();
+ await call.wait(() => call.firstSoundAfter(asked) !== undefined, 20_000);
+ await sleep(2_000);
+ const start = call.at();
+ await call.say({
+ distant:
+ "Did anyone see where I left the charger, I think it was on the desk next to the window",
+ belowDb: distantDb,
+ });
+ const end = call.at();
+ await call.settle();
+ return {
+ interrupted: call.entries("reply_interrupted", start).length > 0,
+ providerHeard: call
+ .entries("xai", start)
+ .some((entry) => entry.event === "input_audio_buffer.speech_started"),
+ playedShare: +(
+ call.soundBetween(start, end) /
+ ((end - start) / 1000)
+ ).toFixed(2),
+ };
+ },
+ // A short aside nearby while the live voice replies.
+ async backgroundAside(call) {
+ await call.say(
+ "Explain in detail why so many SaaS products charge per seat",
+ );
+ const asked = call.at();
+ await call.wait(() => call.firstSoundAfter(asked) !== undefined, 20_000);
+ await sleep(2_000);
+ const start = call.at();
+ await call.say({ distant: "Yeah, okay, sure", belowDb: distantDb });
+ const end = call.at();
+ await call.settle();
+ return {
+ interrupted: call.entries("reply_interrupted", start).length > 0,
+ providerHeard: call
+ .entries("xai", start)
+ .some((entry) => entry.event === "input_audio_buffer.speech_started"),
+ playedShare: +(
+ call.soundBetween(start, end + 1_000) /
+ ((end + 1_000 - start) / 1000)
+ ).toFixed(2),
+ };
+ },
// An event from the user's apps is said, then acted on when asked.
async alert(call) {
const at = call.at();
diff --git a/apps/voice-runtime/src/live-worker.test.ts b/apps/voice-runtime/src/live-worker.test.ts
index 96822781..7a2ea030 100644
--- a/apps/voice-runtime/src/live-worker.test.ts
+++ b/apps/voice-runtime/src/live-worker.test.ts
@@ -317,7 +317,14 @@ async function harness(
return {
async pushPCM(frame: Int16Array) {
through += 512;
- return [{ throughSample: through, speech: frame[0] === 1 }];
+ // 1 is the user's speech, 3 someone speaking farther away.
+ return [
+ {
+ throughSample: through,
+ speech: frame[0] === 1 || frame[0] === 3,
+ levelDb: frame[0] === 3 ? -45 : -20,
+ },
+ ];
},
close: () => undefined,
};
@@ -1033,6 +1040,31 @@ describe("LiveVoiceWorker", () => {
await test.shutdown();
});
+ it("hears quieter speech than the user's own as someone else in the room", async () => {
+ const test = await harness();
+ await answeredTurn(test);
+ await vi.waitFor(() => expect(test.source().frames).toHaveLength(2));
+ test.source().queued = 400;
+ const start = test.session().audio.length;
+ // The user's level is learned from their own words.
+ for (let index = 0; index < 5; index++) test.track.frame(1);
+ for (let index = 0; index < 10; index++) test.track.frame(0);
+ // Someone farther away talks over the reply, longer than a pause needs.
+ for (let index = 0; index < 12; index++) test.track.frame(3);
+ await vi.waitFor(() =>
+ expect(test.session().audio.length).toBe(start + 27),
+ );
+ expect(test.source().clears).toBe(0);
+ // It is gated like quiet: the provider hears silence.
+ expect(
+ test
+ .session()
+ .audio.slice(start + 15)
+ .every((frame) => frame.every((sample) => sample === 0)),
+ ).toBe(true);
+ await test.shutdown();
+ });
+
it("sends silence after a moment of local quiet and the held onset when speech resumes", async () => {
const test = await harness();
const start = test.session().audio.length;
diff --git a/apps/voice-runtime/src/live-worker.ts b/apps/voice-runtime/src/live-worker.ts
index f6f6aad7..57af0a31 100644
--- a/apps/voice-runtime/src/live-worker.ts
+++ b/apps/voice-runtime/src/live-worker.ts
@@ -45,6 +45,7 @@ import {
} from "./livekit-worker.js";
import {
SileroSpeechActivityDetector,
+ type SpeechActivity,
type SpeechActivityDetector,
} from "./voice-activity.js";
import { liveInputRate, xaiSpeedTool } from "./xai-live.js";
@@ -104,6 +105,25 @@ const preRollSamples = liveInputRate * 0.3;
* echo; the pause becomes a barge-in only when server VAD confirms it.
*/
const pauseSpeechSamples = 16_000 * 0.2;
+/**
+ * Speech this far below the user's own level is someone else in the room:
+ * Silero hears any voice, near or far. A speaker 15 dB below the user
+ * (synthesized speech, 2026-11-17) passed Silero in 68% of their speech
+ * windows and this gate in none.
+ */
+const otherSpeakerDb = 10;
+/** Speech fainter than this is never the user's, before their level is known. */
+const faintestSpeechDb = -50;
+/** An open gate stays open this much below its threshold, for word tails. */
+const levelHysteresisDb = 6;
+/**
+ * The learned level follows the user's louder windows at once and softer
+ * ones slowly: an average of every window sat among the soft syllables,
+ * where a nearby speaker's words passed, and those words then pulled it
+ * lower still.
+ */
+const userLevelRise = 0.5;
+const userLevelFall = 0.01;
/** A pause server VAD has not confirmed resumes after this much local quiet. */
const resumeQuietSamples = 16_000 * 0.4;
/** A pause never lasts longer than this. */
@@ -466,6 +486,10 @@ export class LiveVoiceWorker {
private quietRunSamples = 0;
/** The microphone is sent as silence; see quietGateSamples. */
private gated = false;
+ /** The user's speech level on this track, in dBFS; see otherSpeakerDb. */
+ private userLevelDb?: number;
+ /** The last window was the user's speech. */
+ private userSpeaking = false;
/** Microphone frames held while gated, newest last. */
private preRoll: Int16Array[] = [];
private preRollHeld = 0;
@@ -2057,6 +2081,9 @@ export class LiveVoiceWorker {
signal: AbortSignal,
) {
const input = new TrackAudioInput(track, liveInputRate);
+ // Another microphone has a level of its own.
+ this.userLevelDb = undefined;
+ this.userSpeaking = false;
const epoch = this.nextEpoch++;
const generation = Number(
participant.attributes?.["linger.voice_generation"] ?? 0,
@@ -2203,21 +2230,21 @@ export class LiveVoiceWorker {
)
return;
for (const window of activity) {
- if (window.speech) inputMetrics.speechStartedAt ??= receivedAt;
- if (!window.speech && this.speechRunSamples > 0)
- this.speechEndedAt = Date.now();
- if (window.speech && this.quietSince !== undefined) {
+ const speech = this.isUserSpeech(window);
+ if (speech) inputMetrics.speechStartedAt ??= receivedAt;
+ if (!speech && this.speechRunSamples > 0) this.speechEndedAt = Date.now();
+ if (speech && this.quietSince !== undefined) {
if (this.hearing)
this.longestQuietMs = Math.max(
this.longestQuietMs,
receivedAt - this.quietSince,
);
this.quietSince = undefined;
- } else if (!window.speech) this.quietSince ??= receivedAt;
- this.speechRunSamples = window.speech
+ } else if (!speech) this.quietSince ??= receivedAt;
+ this.speechRunSamples = speech
? this.speechRunSamples + detectorWindowSamples
: 0;
- if (window.speech) {
+ if (speech) {
this.quietRunSamples = 0;
this.gated = false;
} else {
@@ -2225,16 +2252,38 @@ export class LiveVoiceWorker {
if (this.quietRunSamples >= quietGateSamples) this.gated = true;
}
if (
- window.speech &&
+ speech &&
this.speechRunSamples >= pauseSpeechSamples &&
this.speechRunSamples - detectorWindowSamples < pauseSpeechSamples
)
this.pausePlayback();
- else if (!window.speech && this.quietRunSamples >= resumeQuietSamples)
+ else if (!speech && this.quietRunSamples >= resumeQuietSamples)
this.resumePlayback("quiet");
}
}
+ /**
+ * Speech near the user's own level. Quieter speech is someone else in the
+ * room and counts as quiet: it is gated and pauses nothing.
+ */
+ private isUserSpeech({ speech, levelDb }: SpeechActivity) {
+ const learned = this.userLevelDb;
+ const threshold =
+ Math.max(
+ faintestSpeechDb,
+ learned === undefined ? faintestSpeechDb : learned - otherSpeakerDb,
+ ) - (this.userSpeaking ? levelHysteresisDb : 0);
+ this.userSpeaking = speech && levelDb >= threshold;
+ if (this.userSpeaking)
+ this.userLevelDb =
+ learned === undefined
+ ? levelDb
+ : learned +
+ (levelDb - learned) *
+ (levelDb > learned ? userLevelRise : userLevelFall);
+ return this.userSpeaking;
+ }
+
private reportBoundary(
epoch: number,
kind: "track_started" | "track_ended",
diff --git a/apps/voice-runtime/src/voice-activity-native.test.ts b/apps/voice-runtime/src/voice-activity-native.test.ts
index f61943dd..c4f28692 100644
--- a/apps/voice-runtime/src/voice-activity-native.test.ts
+++ b/apps/voice-runtime/src/voice-activity-native.test.ts
@@ -5,7 +5,7 @@ describe("production Silero native binding", () => {
it("loads the packaged model and classifies one silent 16 kHz window without a network service", async () => {
const detector = await SileroSpeechActivityDetector.open();
try {
- expect(await detector.pushPCM(new Int16Array(512))).toEqual([
+ expect(await detector.pushPCM(new Int16Array(512))).toMatchObject([
{ throughSample: 512, speech: false },
]);
} finally {
diff --git a/apps/voice-runtime/src/voice-activity.test.ts b/apps/voice-runtime/src/voice-activity.test.ts
index 42a51d00..3c4d21ca 100644
--- a/apps/voice-runtime/src/voice-activity.test.ts
+++ b/apps/voice-runtime/src/voice-activity.test.ts
@@ -32,7 +32,7 @@ describe("Silero human-voice activity adapter", () => {
await opening;
expect(ready).toHaveBeenCalledWith(detector);
expect(model.reset).toHaveBeenCalledOnce();
- expect(await detector.pushPCM(new Int16Array(512).fill(1))).toEqual([
+ expect(await detector.pushPCM(new Int16Array(512).fill(1))).toMatchObject([
{ throughSample: 512, speech: true },
]);
detector.close();
@@ -61,15 +61,16 @@ describe("Silero human-voice activity adapter", () => {
};
const detector = new SileroSpeechActivityDetector(model, 512);
expect(await detector.pushPCM(new Int16Array(320))).toEqual([]);
- expect(await detector.pushPCM(new Int16Array(320))).toEqual([
+ expect(await detector.pushPCM(new Int16Array(320))).toMatchObject([
{ throughSample: 512, speech: true },
]);
- expect(await detector.pushPCM(new Int16Array(384).fill(30_000))).toEqual([
- { throughSample: 1_024, speech: true },
- ]);
- expect(await detector.pushPCM(new Int16Array(512).fill(30_000))).toEqual([
- { throughSample: 1_536, speech: false },
- ]);
+ expect(
+ await detector.pushPCM(new Int16Array(384).fill(30_000)),
+ ).toMatchObject([{ throughSample: 1_024, speech: true }]);
+ const [loud] = await detector.pushPCM(new Int16Array(512).fill(30_000));
+ expect(loud).toMatchObject({ throughSample: 1_536, speech: false });
+ // The level comes with every window, whatever the model says.
+ expect(loud!.levelDb).toBeCloseTo(20 * Math.log10(30_000 / 32_768), 5);
expect(
model.predict.mock.calls.every(([frame]) => frame.length === 512),
).toBe(true);
diff --git a/apps/voice-runtime/src/voice-activity.ts b/apps/voice-runtime/src/voice-activity.ts
index 6bb14c33..3220cceb 100644
--- a/apps/voice-runtime/src/voice-activity.ts
+++ b/apps/voice-runtime/src/voice-activity.ts
@@ -6,6 +6,8 @@ let prewarmed: Promise<SpeechActivityDetector> | undefined;
export interface SpeechActivity {
throughSample: number;
speech: boolean;
+ /** The window's RMS level in dBFS. */
+ levelDb: number;
}
// The detector receives the same mono 16 kHz samples as ASR. Its clock advances
@@ -103,6 +105,7 @@ export class SileroSpeechActivityDetector implements SpeechActivityDetector {
observations.push({
throughSample: this.throughSample,
speech: this.speech,
+ levelDb: levelDb(this.window),
});
this.pending = 0;
}
@@ -116,3 +119,9 @@ export class SileroSpeechActivityDetector implements SpeechActivityDetector {
this.model.reset();
}
}
+
+function levelDb(window: Int16Array) {
+ let sum = 0;
+ for (const sample of window) sum += sample * sample;
+ return 10 * Math.log10(Math.max(sum / window.length, 1) / 32_768 ** 2);
+}