Skip to content

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

fix(meetings): harden the Tinfoil commit adaptation

Alcahest1a0fabdc5b31
diff --git a/src/helpers/tinfoilRealtimeStreaming.js b/src/helpers/tinfoilRealtimeStreaming.js
index e54675722..c1f4312e8 100644
--- a/src/helpers/tinfoilRealtimeStreaming.js
+++ b/src/helpers/tinfoilRealtimeStreaming.js
@@ -11,6 +11,14 @@ const COMMIT_IDLE_MS = 600;
// Bounds the text lost on abrupt socket death and keeps segments flowing to diarization.
const MAX_UTTERANCE_MS = 30000;
const COMMIT_ACK_TIMEOUT_MS = 10000;
+// Mirrors the base class's disconnect timeout so a dead server can't hang the stop.
+const COMMIT_DRAIN_TIMEOUT_MS = 3000;
+
+// Matches the empty-buffer signatures the base class tolerates at disconnect.
+const isEmptyBufferError = (error) =>
+ error?.code === "input_audio_buffer_commit_empty" ||
+ (error?.message || "").includes("buffer too small") ||
+ (error?.message || "").includes("commit_empty");
// Tinfoil's transcription intent has no server VAD, so utterance boundaries
// are decided client-side from the delta stream and committed explicitly.
@@ -21,7 +29,10 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
this._commitTimer = null;
this._commitInFlight = false;
this._commitSentAt = 0;
+ this._commitDrain = null;
+ this._commitDrainResolve = null;
this._lastDeltaAt = 0;
+ this._emptyCommitStreak = 0;
}
// Audio must only ever reach the attested Tinfoil socket, so a
@@ -37,26 +48,55 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
}
handleMessage(data) {
- let type;
+ let event;
try {
- type = JSON.parse(data.toString()).type;
+ event = JSON.parse(data.toString());
} catch {
// Malformed frames are logged by the base handler.
+ super.handleMessage(data);
+ return;
}
- if (type === "conversation.item.input_audio_transcription.delta") {
- this._lastDeltaAt = Date.now();
- // No speech_started events without server VAD; the first delta of an
- // utterance is the closest signal for the mic-suppression window.
- if (!this.speechStartedAt) this.speechStartedAt = this._lastDeltaAt;
- } else if (
- type === "conversation.item.input_audio_transcription.completed" ||
- type === "error"
- ) {
- this._commitInFlight = false;
+ if (event.type === "conversation.item.input_audio_transcription.delta") {
+ // Only real text moves the idle clock; without server VAD the first delta
+ // of an utterance is also the speech-start signal for mic suppression.
+ if (event.delta) {
+ this._lastDeltaAt = Date.now();
+ if (!this.speechStartedAt) this.speechStartedAt = this._lastDeltaAt;
+ }
+ } else if (event.type === "conversation.item.input_audio_transcription.completed") {
+ this._emptyCommitStreak = 0;
+ this._settleCommit();
+ } else if (event.type === "error") {
+ const wasTimerCommit = this._commitInFlight;
+ this._settleCommit();
+ if (wasTimerCommit && isEmptyBufferError(event.error)) {
+ this._handleEmptyCommitReply();
+ return;
+ }
}
super.handleMessage(data);
}
+ // An empty-buffer reply to a timer commit is benign (a lost completed or a
+ // double commit); surfacing it would flash an error mid-meeting.
+ _handleEmptyCommitReply() {
+ this._emptyCommitStreak += 1;
+ // Restart the idle window so a late completed can land before any retry.
+ this._lastDeltaAt = Date.now();
+ if (this._emptyCommitStreak >= 2) {
+ // A second empty reply means this text can't finalize; drop it rather
+ // than loop commits forever. A late completed would still deliver it.
+ debugLogger.error("Tinfoil Realtime utterance could not be finalized, dropping partial", {
+ partialLength: this.currentPartial.length,
+ });
+ this.currentPartial = "";
+ this.speechStartedAt = null;
+ this._emptyCommitStreak = 0;
+ return;
+ }
+ debugLogger.debug("Tinfoil Realtime empty commit reply, awaiting late completed");
+ }
+
_markConnected() {
super._markConnected();
this._startCommitTimer();
@@ -81,7 +121,7 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
// A commit the server never answered must not block the session forever.
if (now - this._commitSentAt >= COMMIT_ACK_TIMEOUT_MS) {
debugLogger.debug("Tinfoil Realtime commit unanswered, re-arming");
- this._commitInFlight = false;
+ this._settleCommit();
}
return;
}
@@ -92,17 +132,46 @@ class TinfoilRealtimeStreaming extends OpenAIRealtimeStreaming {
if (idleFor < COMMIT_IDLE_MS && utteranceAge < MAX_UTTERANCE_MS) return;
this._commitInFlight = true;
this._commitSentAt = now;
+ this._commitDrain = new Promise((resolve) => {
+ this._commitDrainResolve = resolve;
+ });
try {
this.ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
} catch (err) {
- this._commitInFlight = false;
+ this._settleCommit();
debugLogger.debug("Tinfoil Realtime commit send failed", { error: err.message });
}
}
+ _settleCommit() {
+ this._commitInFlight = false;
+ if (this._commitDrainResolve) {
+ this._commitDrainResolve();
+ this._commitDrainResolve = null;
+ this._commitDrain = null;
+ }
+ }
+
+ // The base flush resolves on the first completed, so a commit the timer
+ // already sent must finalize first or its tail transcript is lost.
+ async disconnect() {
+ this._stopCommitTimer();
+ if (this._commitInFlight && this._commitDrain) {
+ let timer;
+ await Promise.race([
+ this._commitDrain,
+ new Promise((resolve) => {
+ timer = setTimeout(resolve, COMMIT_DRAIN_TIMEOUT_MS);
+ }),
+ ]);
+ clearTimeout(timer);
+ }
+ return super.disconnect();
+ }
+
cleanup() {
this._stopCommitTimer();
- this._commitInFlight = false;
+ this._settleCommit();
super.cleanup();
}
}
diff --git a/test/helpers/tinfoilRealtimeStreaming.test.js b/test/helpers/tinfoilRealtimeStreaming.test.js
index d5119e67c..afee9b46f 100644
--- a/test/helpers/tinfoilRealtimeStreaming.test.js
+++ b/test/helpers/tinfoilRealtimeStreaming.test.js
@@ -46,6 +46,13 @@ function completed(transcript) {
return JSON.stringify({ type: COMPLETED_EVENT, transcript });
}
+function commitEmptyError() {
+ return JSON.stringify({
+ type: "error",
+ error: { code: "input_audio_buffer_commit_empty", message: "buffer too small" },
+ });
+}
+
// Wires a connected instance directly, mirroring the existing realtime test
// style: cadence behavior is driven through handleMessage + mocked timers.
async function makeConnected() {
@@ -331,3 +338,168 @@ test("cleanup() stops the commit timer so a dead instance never commits", (t) =>
assert.equal(sentCommits(socket).length, 0);
})();
});
+
+// -- disconnect drain: an in-flight timer commit must finalize before the flush --
+
+test("disconnect() drains the in-flight timer commit so the tail transcript still lands", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ const socket = streaming.ws;
+ streaming.sendAudio(Buffer.alloc(480));
+
+ streaming.handleMessage(delta("first utterance"));
+ t.mock.timers.tick(850);
+ assert.equal(sentCommits(socket).length, 1, "timer commit in flight");
+ streaming.handleMessage(delta("tail spoken after the commit"));
+
+ const disconnected = streaming.disconnect();
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(sentCommits(socket).length, 1, "flush must wait for the in-flight commit");
+
+ streaming.handleMessage(completed("first utterance"));
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(sentCommits(socket).length, 2, "flush commit follows the drained completed");
+
+ streaming.handleMessage(completed("tail spoken after the commit"));
+ const result = await disconnected;
+ assert.equal(result.text, "first utterance tail spoken after the commit");
+ })();
+});
+
+test("disconnect() with an unanswered commit resolves within the bounded deadlines", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ streaming.sendAudio(Buffer.alloc(480));
+ streaming.handleMessage(delta("hello"));
+ t.mock.timers.tick(850);
+ assert.equal(sentCommits(streaming.ws).length, 1);
+
+ const disconnected = streaming.disconnect();
+ await new Promise((resolve) => setImmediate(resolve));
+ t.mock.timers.tick(3000);
+ await new Promise((resolve) => setImmediate(resolve));
+ t.mock.timers.tick(3000);
+ const result = await disconnected;
+ assert.equal(result.text, "", "resolves with accumulated text instead of hanging");
+ })();
+});
+
+// -- empty-commit replies: benign for timer commits, bounded against loops --
+
+test("empty-buffer reply to a timer commit is swallowed and retried after a fresh idle window", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ let surfaced = 0;
+ streaming.onError = () => {
+ surfaced += 1;
+ };
+
+ streaming.handleMessage(delta("hello"));
+ t.mock.timers.tick(850);
+ assert.equal(sentCommits(streaming.ws).length, 1);
+
+ streaming.handleMessage(commitEmptyError());
+ assert.equal(surfaced, 0, "benign empty reply must not reach the meeting error channel");
+ assert.equal(streaming._commitInFlight, false);
+
+ t.mock.timers.tick(250);
+ assert.equal(sentCommits(streaming.ws).length, 1, "no instant re-commit before the idle window");
+ t.mock.timers.tick(600);
+ assert.equal(sentCommits(streaming.ws).length, 2, "retry follows a full idle window");
+ })();
+});
+
+test("a second empty-buffer reply drops the unfinalizable partial instead of looping commits", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ let surfaced = 0;
+ streaming.onError = () => {
+ surfaced += 1;
+ };
+
+ streaming.handleMessage(delta("hello"));
+ t.mock.timers.tick(850);
+ streaming.handleMessage(commitEmptyError());
+ t.mock.timers.tick(850);
+ assert.equal(sentCommits(streaming.ws).length, 2, "one retry after the first empty reply");
+
+ streaming.handleMessage(commitEmptyError());
+ assert.equal(surfaced, 0);
+ assert.equal(streaming.currentPartial, "", "unfinalizable partial dropped");
+ assert.equal(streaming.speechStartedAt, null);
+
+ t.mock.timers.tick(5000);
+ assert.equal(sentCommits(streaming.ws).length, 2, "no commit loop after dropping the partial");
+ })();
+});
+
+test("empty-buffer error with no timer commit in flight still reaches onError", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ let errMsg = null;
+ streaming.onError = (err) => {
+ errMsg = err.message;
+ };
+
+ streaming.handleMessage(commitEmptyError());
+
+ assert.equal(errMsg, "buffer too small", "base disconnect-flush tolerance must still see it");
+ })();
+});
+
+test("server errors during an in-flight commit still surface", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+ let errMsg = null;
+ streaming.onError = (err) => {
+ errMsg = err.message;
+ };
+
+ streaming.handleMessage(delta("hello"));
+ t.mock.timers.tick(850);
+ streaming.handleMessage(
+ JSON.stringify({ type: "error", error: { code: "server_error", message: "something broke" } })
+ );
+
+ assert.equal(errMsg, "something broke");
+ assert.equal(streaming._commitInFlight, false);
+ })();
+});
+
+// -- empty delta frames must not touch the utterance timers --
+
+test("an empty delta frame does not stamp speechStartedAt", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+
+ streaming.handleMessage(delta(""));
+ assert.equal(streaming.speechStartedAt, null, "an empty frame is not speech");
+
+ t.mock.timers.tick(250);
+ streaming.handleMessage(delta("real"));
+ assert.equal(streaming.speechStartedAt, 100250);
+ })();
+});
+
+test("empty delta frames do not starve the idle commit", (t) => {
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"], now: 100000 });
+ return (async () => {
+ const streaming = await makeConnected();
+
+ streaming.handleMessage(delta("hi"));
+ t.mock.timers.tick(250);
+ streaming.handleMessage(delta(""));
+ t.mock.timers.tick(250);
+ streaming.handleMessage(delta(""));
+ t.mock.timers.tick(250);
+
+ assert.equal(sentCommits(streaming.ws).length, 1, "empty frames must not reset the idle clock");
+ })();
+});