Skip to content

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

fix(transcription): apply BYOK key changes without restarting (#2527)

Idris Gadi7ba7a37bf834
diff --git a/preload.js b/preload.js
index b2dfc7f79..dd58e779c 100644
--- a/preload.js
+++ b/preload.js
@@ -1025,6 +1025,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.on("hotkey-registration-failed", listener);
return () => ipcRenderer.removeListener("hotkey-registration-failed", listener);
},
+ onApiKeyUpdated: registerListener(
+ "api-key-updated",
+ (callback) => (_event, storeKey) => callback(storeKey)
+ ),
onSettingUpdated: (callback) => {
const listener = (_event, data) => callback?.(data);
ipcRenderer.on("setting-updated", listener);
diff --git a/src/helpers/assemblyAiStreaming.js b/src/helpers/assemblyAiStreaming.js
index a543fb207..53e8ee1c5 100644
--- a/src/helpers/assemblyAiStreaming.js
+++ b/src/helpers/assemblyAiStreaming.js
@@ -166,20 +166,21 @@ class AssemblyAiStreaming {
return new Promise((resolve, reject) => {
let settled = false;
+ const socket = new WebSocket(url);
+ this.warmConnection = socket;
+
const warmupTimeout = setTimeout(() => {
if (settled) return;
settled = true;
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
reject(new Error("AssemblyAI warmup connection timeout"));
}, WEBSOCKET_TIMEOUT_MS);
- this.warmConnection = new WebSocket(url);
-
- this.warmConnection.on("open", () => {
+ socket.on("open", () => {
debugLogger.debug("AssemblyAI warm connection socket opened");
});
- this.warmConnection.on("message", (data) => {
+ socket.on("message", (data) => {
try {
const message = JSON.parse(data.toString());
if (message.type === "Begin" && !settled) {
@@ -196,18 +197,26 @@ class AssemblyAiStreaming {
}
});
- this.warmConnection.on("error", (error) => {
+ socket.on("error", (error) => {
clearTimeout(warmupTimeout);
debugLogger.error("AssemblyAI warmup connection error", { error: error.message });
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
if (!settled) {
settled = true;
reject(error);
}
});
- this.warmConnection.on("close", (code, reason) => {
+ socket.on("close", (code, reason) => {
clearTimeout(warmupTimeout);
+ // A dropped socket closes after its replacement may have opened; leave that one be.
+ if (this.warmConnection !== socket) {
+ if (!settled) {
+ settled = true;
+ reject(new Error(`AssemblyAI warmup connection closed before ready (code: ${code})`));
+ }
+ return;
+ }
this.stopKeepAlive();
const wasReady = this.warmConnectionReady;
const savedOptions = this.warmConnectionOptions ? { ...this.warmConnectionOptions } : null;
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 25e8532d7..74bf5b518 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -599,6 +599,11 @@ class AudioManager {
this._onApiKeyChanged = () => {
this.cachedApiKey = null;
this.cachedApiKeyProvider = null;
+ // Replace a socket warmed with the previous key now rather than at the next
+ // start. A key save in Settings is no reason to open the mic.
+ if (!this.isRecording && !this.isProcessing && this.shouldUseStreaming()) {
+ this.warmupStreamingConnection({ warmMic: false });
+ }
};
window.addEventListener("api-key-changed", this._onApiKeyChanged);
@@ -4390,7 +4395,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return this.sttConfig.dictation?.mode === "streaming";
}
- async warmupStreamingConnection({ isSignedIn: isSignedInOverride } = {}) {
+ async warmupStreamingConnection({ isSignedIn: isSignedInOverride, warmMic = true } = {}) {
if (!this.isRecordingAllowedByPolicy()) {
logger.debug("Streaming warmup skipped by workspace policy", {}, "streaming");
return false;
@@ -4446,7 +4451,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// Warm up the OS audio driver by briefly acquiring the mic, then
// releasing. TTL-gated: drivers go cold again after idle, so this must
// re-fire once the warm window lapses (#845).
- await this._warmMicDriverIfCold("streaming");
+ if (warmMic) await this._warmMicDriverIfCold("streaming");
this.warmupFailureStreak = 0;
logger.info(
diff --git a/src/helpers/cortiStreaming.js b/src/helpers/cortiStreaming.js
index d835581ac..0e2017652 100644
--- a/src/helpers/cortiStreaming.js
+++ b/src/helpers/cortiStreaming.js
@@ -35,6 +35,7 @@ class CortiStreaming {
this.sampleRate = SAMPLE_RATE;
this.warmConnection = null;
this.warmConnectionReady = false;
+ this.warmConnectionOptions = null;
this.warmSessionId = null;
this.warmSessionStartedAt = null;
this.keepAliveInterval = null;
@@ -81,6 +82,19 @@ class CortiStreaming {
this.audioBytesSent = 0;
this.sampleRate = options.sampleRate || SAMPLE_RATE;
+ // A warm socket is bound to the region and tenant it opened against.
+ if (
+ this.hasWarmConnection() &&
+ (this.warmConnectionOptions.environment !== environment ||
+ this.warmConnectionOptions.tenant !== tenant)
+ ) {
+ debugLogger.debug("Corti warm connection differs, cold-starting", {
+ warm: [this.warmConnectionOptions.environment, this.warmConnectionOptions.tenant],
+ requested: [environment, tenant],
+ });
+ this.cleanupWarmConnection();
+ }
+
// Reuse the pre-warmed socket for an instant start; cold-connect otherwise.
if (this.useWarmConnection()) {
debugLogger.debug("Corti using warm connection - instant start");
@@ -178,6 +192,7 @@ class CortiStreaming {
}
this.warmConnectionReady = false;
+ this.warmConnectionOptions = options;
this.warmSessionId = null;
this.sampleRate = options.sampleRate || SAMPLE_RATE;
@@ -187,21 +202,22 @@ class CortiStreaming {
return new Promise((resolve, reject) => {
let settled = false;
+ const socket = new WebSocket(url);
+ this.warmConnection = socket;
+
const warmupTimeout = setTimeout(() => {
if (settled) return;
settled = true;
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
reject(new Error("Corti warmup connection timeout"));
}, WEBSOCKET_TIMEOUT_MS);
- this.warmConnection = new WebSocket(url);
-
- this.warmConnection.on("open", () => {
+ socket.on("open", () => {
debugLogger.debug("Corti warm connection opened, sending config");
- this.warmConnection.send(JSON.stringify({ type: "config", configuration }));
+ socket.send(JSON.stringify({ type: "config", configuration }));
});
- this.warmConnection.on("message", (data) => {
+ socket.on("message", (data) => {
let message;
try {
message = JSON.parse(data.toString());
@@ -220,9 +236,9 @@ class CortiStreaming {
}
});
- this.warmConnection.on("error", (error) => {
+ socket.on("error", (error) => {
debugLogger.error("Corti warmup connection error", { error: error.message });
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
if (!settled) {
settled = true;
clearTimeout(warmupTimeout);
@@ -230,8 +246,16 @@ class CortiStreaming {
}
});
- this.warmConnection.on("close", (code, reason) => {
+ socket.on("close", (code, reason) => {
clearTimeout(warmupTimeout);
+ // A dropped socket closes after its replacement may have opened; leave that one be.
+ if (this.warmConnection !== socket) {
+ if (!settled) {
+ settled = true;
+ reject(new Error(`Corti warmup connection closed (code: ${code})`));
+ }
+ return;
+ }
const wasReady = this.warmConnectionReady;
debugLogger.debug("Corti warm connection closed", {
code,
@@ -316,6 +340,7 @@ class CortiStreaming {
this.warmConnection = null;
}
this.warmConnectionReady = false;
+ this.warmConnectionOptions = null;
this.warmSessionId = null;
this.warmSessionStartedAt = null;
}
diff --git a/src/helpers/deepgramStreaming.js b/src/helpers/deepgramStreaming.js
index 530d6ad52..ba432466f 100644
--- a/src/helpers/deepgramStreaming.js
+++ b/src/helpers/deepgramStreaming.js
@@ -295,23 +295,24 @@ class DeepgramStreaming {
resolve();
};
+ const socket = new WebSocket(url, {
+ headers: { Authorization: authorizationHeader(this.mode, token) },
+ });
+ this.warmConnection = socket;
+
const warmupTimeout = setTimeout(() => {
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
reject(new Error("Deepgram warmup connection timeout"));
}, WEBSOCKET_TIMEOUT_MS);
- this.warmConnection = new WebSocket(url, {
- headers: { Authorization: authorizationHeader(this.mode, token) },
- });
-
- this.warmConnection.on("open", () => {
+ socket.on("open", () => {
debugLogger.debug("Deepgram warm connection socket opened");
// Consider the socket warm as soon as it's open. Deepgram may not emit
// Metadata until audio starts, which would make startup warmup appear broken.
resolveWarmup({ via: "open" });
});
- this.warmConnection.on("message", (data) => {
+ socket.on("message", (data) => {
try {
const message = JSON.parse(data.toString());
if (message.type === "Metadata") {
@@ -323,7 +324,7 @@ class DeepgramStreaming {
}
});
- this.warmConnection.on("error", (error) => {
+ socket.on("error", (error) => {
clearTimeout(warmupTimeout);
debugLogger.error("Deepgram warmup connection error", { error: error.message });
// Invalidate cached token on auth failure so next attempt fetches fresh
@@ -331,15 +332,23 @@ class DeepgramStreaming {
this.cachedToken = null;
this.tokenFetchedAt = null;
}
- this.cleanupWarmConnection();
+ if (this.warmConnection === socket) this.cleanupWarmConnection();
if (!settled) {
settled = true;
reject(error);
}
});
- this.warmConnection.on("close", (code, reason) => {
+ socket.on("close", (code, reason) => {
clearTimeout(warmupTimeout);
+ // A dropped socket closes after its replacement may have opened; leave that one be.
+ if (this.warmConnection !== socket) {
+ if (!settled) {
+ settled = true;
+ reject(new Error(`Deepgram warmup connection closed (code: ${code})`));
+ }
+ return;
+ }
this.stopKeepAlive();
const wasReady = this.warmConnectionReady;
const savedOptions = this.warmConnectionOptions ? { ...this.warmConnectionOptions } : null;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 8ed38c978..b548274e8 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1739,9 +1739,28 @@ class IPCHandlers {
return this.windowManager.resizeDictationErrorWindowToContent(surfaceHeight);
});
+ // Counts changes to any key in Settings. A streaming socket keeps the count it
+ // was opened under, so a start never reuses one authenticated before a change.
+ let credentialGeneration = 0;
+ const saveSecretKey = (getter, saver, storeKey) => (event, key) => {
+ if (typeof key !== "string") throw new TypeError("API key must be a string");
+ // Committing an unedited key field saves the same value again.
+ const changed = this.environmentManager[getter]() !== key;
+ const result = this.environmentManager[saver](key);
+ if (!changed) return result;
+ credentialGeneration += 1;
+ // Notify peers by setting name only; leave the editor's pending input alone.
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed() && win.webContents.id !== event.sender.id) {
+ win.webContents.send("api-key-updated", storeKey);
+ }
+ }
+ return result;
+ };
+
for (const k of BYOK_API_KEYS) {
ipcMain.handle(`get-${k.base}-key`, () => this.environmentManager[k.get]());
- ipcMain.handle(`save-${k.base}-key`, (event, key) => this.environmentManager[k.save](key));
+ ipcMain.handle(`save-${k.base}-key`, saveSecretKey(k.get, k.save, k.storeKey));
}
ipcMain.handle("db-save-transcription", async (event, text, rawText, options) => {
@@ -4864,17 +4883,19 @@ class IPCHandlers {
return this.environmentManager.getCortiClientId();
});
- ipcMain.handle("save-corti-client-id", async (event, key) => {
- return this.environmentManager.saveCortiClientId(key);
- });
+ ipcMain.handle(
+ "save-corti-client-id",
+ saveSecretKey("getCortiClientId", "saveCortiClientId", "cortiClientId")
+ );
ipcMain.handle("get-corti-client-secret", async () => {
return this.environmentManager.getCortiClientSecret();
});
- ipcMain.handle("save-corti-client-secret", async (event, key) => {
- return this.environmentManager.saveCortiClientSecret(key);
- });
+ ipcMain.handle(
+ "save-corti-client-secret",
+ saveSecretKey("getCortiClientSecret", "saveCortiClientSecret", "cortiClientSecret")
+ );
ipcMain.handle(
"proxy-corti-transcription",
@@ -4939,17 +4960,23 @@ class IPCHandlers {
return this.environmentManager.getCustomTranscriptionKey();
});
- ipcMain.handle("save-custom-transcription-key", async (event, key) => {
- return this.environmentManager.saveCustomTranscriptionKey(key);
- });
+ ipcMain.handle(
+ "save-custom-transcription-key",
+ saveSecretKey(
+ "getCustomTranscriptionKey",
+ "saveCustomTranscriptionKey",
+ "customTranscriptionApiKey"
+ )
+ );
ipcMain.handle("get-cleanup-custom-key", async () => {
return this.environmentManager.getCleanupCustomKey();
});
- ipcMain.handle("save-cleanup-custom-key", async (event, key) => {
- return this.environmentManager.saveCleanupCustomKey(key);
- });
+ ipcMain.handle(
+ "save-cleanup-custom-key",
+ saveSecretKey("getCleanupCustomKey", "saveCleanupCustomKey", "cleanupCustomApiKey")
+ );
// Enterprise provider key handlers
ipcMain.handle("get-bedrock-region", async () => {
@@ -4967,21 +4994,28 @@ class IPCHandlers {
ipcMain.handle("get-bedrock-access-key-id", async () => {
return this.environmentManager.getBedrockAccessKeyId();
});
- ipcMain.handle("save-bedrock-access-key-id", async (event, key) => {
- return this.environmentManager.saveBedrockAccessKeyId(key);
- });
+ ipcMain.handle(
+ "save-bedrock-access-key-id",
+ saveSecretKey("getBedrockAccessKeyId", "saveBedrockAccessKeyId", "bedrockAccessKeyId")
+ );
ipcMain.handle("get-bedrock-secret-access-key", async () => {
return this.environmentManager.getBedrockSecretAccessKey();
});
- ipcMain.handle("save-bedrock-secret-access-key", async (event, key) => {
- return this.environmentManager.saveBedrockSecretAccessKey(key);
- });
+ ipcMain.handle(
+ "save-bedrock-secret-access-key",
+ saveSecretKey(
+ "getBedrockSecretAccessKey",
+ "saveBedrockSecretAccessKey",
+ "bedrockSecretAccessKey"
+ )
+ );
ipcMain.handle("get-bedrock-session-token", async () => {
return this.environmentManager.getBedrockSessionToken();
});
- ipcMain.handle("save-bedrock-session-token", async (event, key) => {
- return this.environmentManager.saveBedrockSessionToken(key);
- });
+ ipcMain.handle(
+ "save-bedrock-session-token",
+ saveSecretKey("getBedrockSessionToken", "saveBedrockSessionToken", "bedrockSessionToken")
+ );
ipcMain.handle("get-azure-endpoint", async () => {
return this.environmentManager.getAzureEndpoint();
});
@@ -4991,9 +5025,10 @@ class IPCHandlers {
ipcMain.handle("get-azure-api-key", async () => {
return this.environmentManager.getAzureApiKey();
});
- ipcMain.handle("save-azure-api-key", async (event, key) => {
- return this.environmentManager.saveAzureApiKey(key);
- });
+ ipcMain.handle(
+ "save-azure-api-key",
+ saveSecretKey("getAzureApiKey", "saveAzureApiKey", "azureApiKey")
+ );
ipcMain.handle("get-azure-deployment", async () => {
return this.environmentManager.getAzureDeployment();
});
@@ -5021,9 +5056,10 @@ class IPCHandlers {
ipcMain.handle("get-vertex-api-key", async () => {
return this.environmentManager.getVertexApiKey();
});
- ipcMain.handle("save-vertex-api-key", async (event, key) => {
- return this.environmentManager.saveVertexApiKey(key);
- });
+ ipcMain.handle(
+ "save-vertex-api-key",
+ saveSecretKey("getVertexApiKey", "saveVertexApiKey", "vertexApiKey")
+ );
// Enterprise provider test connection
ipcMain.handle("test-enterprise-connection", async (event, provider, config) => {
@@ -8742,14 +8778,19 @@ class IPCHandlers {
};
// What a dictation connection was opened for; a start or warmup reuses one
- // only when nothing about the route changed.
- const dictationConnectionKey = (options) =>
- JSON.stringify([
- options.provider || "openai-realtime",
+ // only when nothing about the route changed and, for a connection that reads
+ // a saved key, no key was saved since.
+ const dictationConnectionKey = (options) => {
+ const provider = options.provider || "openai-realtime";
+ const readsSavedKey = options.mode === "byok" || provider === "tinfoil-realtime";
+ return JSON.stringify([
+ provider,
options.mode,
options.model,
options.baseUrl,
+ readsSavedKey ? credentialGeneration : null,
]);
+ };
const connectDictationStreaming = async (event, options) => {
// Older renderers did not label the OpenAI dictation adapter. Dictation
@@ -10954,6 +10995,23 @@ class IPCHandlers {
? fetchRealtimeToken(event, { mode: "byok", provider: "assemblyai-realtime" })
: fetchStreamingToken(event);
+ // A warm socket opened before the latest key save still carries the old key;
+ // dropping it sends the start out on a fresh connect with the new one. Starts
+ // check right before connecting, because a warmup that was still minting can
+ // open its socket during the start's own token fetch.
+ const dropStaleWarmConnection = (streaming) => {
+ if (streaming.warmConnectionOptions?.credentialGeneration !== credentialGeneration) {
+ streaming.cleanupWarmConnection();
+ }
+ };
+
+ // A warmup replaces a stale ready socket instead of reporting it warm, so the
+ // next start finds one with the new key. A socket still opening is left to the
+ // start: closing it mid-handshake would fail the warmup that opened it.
+ const dropStaleReadyWarmConnection = (streaming) => {
+ if (streaming.hasWarmConnection()) dropStaleWarmConnection(streaming);
+ };
+
ipcMain.handle("assemblyai-streaming-warmup", async (event, options = {}) => {
try {
const byok = options.mode === "byok";
@@ -10965,19 +11023,26 @@ class IPCHandlers {
this.assemblyAiStreaming = new AssemblyAiStreaming();
}
this.assemblyAiStreaming.adoptMode(options);
+ if (byok) dropStaleReadyWarmConnection(this.assemblyAiStreaming);
if (this.assemblyAiStreaming.hasWarmConnection()) {
debugLogger.debug("AssemblyAI connection already warm", {}, "streaming");
return { success: true, alreadyWarm: true };
}
+ // Read before the key is, so a save during the mint marks this socket stale.
+ const generation = credentialGeneration;
let token = byok ? null : this.assemblyAiStreaming.getCachedToken();
if (!token) {
debugLogger.debug("Fetching new streaming token for warmup", { byok }, "streaming");
token = await fetchAssemblyAiToken(event, byok);
}
- await this.assemblyAiStreaming.warmup({ ...options, token });
+ await this.assemblyAiStreaming.warmup({
+ ...options,
+ token,
+ credentialGeneration: generation,
+ });
debugLogger.debug("AssemblyAI connection warmed up", {}, "streaming");
return { success: true };
@@ -11060,6 +11125,7 @@ class IPCHandlers {
}
};
+ if (byok) dropStaleWarmConnection(this.assemblyAiStreaming);
await this.assemblyAiStreaming.connect({ ...options, token });
debugLogger.debug("AssemblyAI streaming started", {}, "streaming");
@@ -11221,12 +11287,14 @@ class IPCHandlers {
this.deepgramStreaming.adoptMode(options);
setDeepgramTokenRefreshFn(event, byok);
+ if (byok) dropStaleReadyWarmConnection(this.deepgramStreaming);
if (this.deepgramStreaming.hasWarmConnection()) {
debugLogger.debug("Deepgram connection already warm", {}, "streaming");
return { success: true, alreadyWarm: true };
}
+ const generation = credentialGeneration;
let token = byok ? null : this.deepgramStreaming.getCachedToken();
if (!token) {
debugLogger.debug(
@@ -11237,7 +11305,11 @@ class IPCHandlers {
token = await fetchDeepgramToken(event, byok);
}
- await this.deepgramStreaming.warmup({ ...options, token });
+ await this.deepgramStreaming.warmup({
+ ...options,
+ token,
+ credentialGeneration: generation,
+ });
debugLogger.debug("Deepgram connection warmed up", {}, "streaming");
return { success: true };
@@ -11276,6 +11348,7 @@ class IPCHandlers {
this.deepgramStreaming = new DeepgramStreaming();
}
this.deepgramStreaming.adoptMode(options);
+ if (byok) dropStaleWarmConnection(this.deepgramStreaming);
setDeepgramTokenRefreshFn(event, byok);
@@ -11437,6 +11510,11 @@ class IPCHandlers {
return streaming;
};
+ // What a Gemini connection authenticated with: a managed one never serves a
+ // BYOK start or the reverse, and a BYOK one is not reused after a key save.
+ const geminiConnectionKey = (options) =>
+ options.mode === "byok" ? `byok:${credentialGeneration}` : "managed";
+
const connectGeminiStreaming = (event, options) => {
if (geminiConnectInFlight) return geminiConnectInFlight;
geminiConnectInFlight = (async () => {
@@ -11447,6 +11525,7 @@ class IPCHandlers {
// Buffer before the token fetch (a real network round trip) so
// gemini-streaming-send has somewhere to put the first frames.
streaming.beginConnecting();
+ streaming.connectionKey = geminiConnectionKey(options);
const token = await fetchRealtimeToken(event, tokenOptions);
await streaming.connect({
...options,
@@ -11484,7 +11563,10 @@ class IPCHandlers {
try {
const streaming = ensureGeminiStreaming(event);
if (geminiConnectInFlight) await geminiConnectInFlight;
- const usedWarmConnection = streaming.isConnected && !options.forceNew;
+ const usedWarmConnection =
+ streaming.isConnected &&
+ !options.forceNew &&
+ streaming.connectionKey === geminiConnectionKey(options);
if (!usedWarmConnection) {
if (streaming.isConnected) await streaming.disconnect(false);
await connectGeminiStreaming(event, options);
@@ -11565,9 +11647,11 @@ class IPCHandlers {
if (!this.cortiStreaming) {
this.cortiStreaming = new CortiStreaming();
}
+ dropStaleReadyWarmConnection(this.cortiStreaming);
if (this.cortiStreaming.hasWarmConnection() || this.cortiStreaming.isConnected) {
return { success: true, alreadyWarm: true };
}
+ const generation = credentialGeneration;
const { token, environment, tenant } = await this._mintStoredCortiToken(options);
await this.cortiStreaming.warmup({
token,
@@ -11575,6 +11659,7 @@ class IPCHandlers {
tenant,
language: options.language,
keyterms: options.keyterms,
+ credentialGeneration: generation,
});
return { success: true };
} catch (error) {
@@ -11607,6 +11692,7 @@ class IPCHandlers {
if (win && !win.isDestroyed()) win.webContents.send("corti-session-end", data);
};
+ dropStaleWarmConnection(this.cortiStreaming);
await this.cortiStreaming.connect({
token,
environment,
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 8d960595f..0abd72985 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -1402,6 +1402,7 @@ type SecretProvider = keyof typeof SECRET_IPC_SAVERS;
const secretSaveTimers: Partial<Record<SecretProvider, ReturnType<typeof setTimeout>>> = {};
function debouncedSaveSecret(provider: SecretProvider, key: string) {
if (!isBrowser) return;
+ debouncedPersistToEnv();
const timer = secretSaveTimers[provider];
if (timer) clearTimeout(timer);
secretSaveTimers[provider] = setTimeout(() => {
@@ -1459,25 +1460,21 @@ function invalidateApiKeyCaches(
| "openrouter"
| "corti"
) {
- if (provider) {
- if (_ReasoningService) {
- _ReasoningService.clearApiKeyCache(provider);
- } else {
- import("../services/ReasoningService")
- .then((mod) => {
- _ReasoningService = mod.default;
- _ReasoningService.clearApiKeyCache(provider);
- })
- .catch(() => {});
- }
+ if (_ReasoningService) {
+ _ReasoningService.clearApiKeyCache(provider);
+ } else {
+ import("../services/ReasoningService")
+ .then((mod) => {
+ _ReasoningService = mod.default;
+ _ReasoningService.clearApiKeyCache(provider);
+ })
+ .catch(() => {});
}
if (isBrowser) window.dispatchEvent(new Event("api-key-changed"));
- debouncedPersistToEnv();
}
// Uniform BYOK key setter: persist to the secure store (debounced) and clear
-// the provider's cached key. cacheProvider is omitted where there is no scoped
-// cache to clear (xai), preserving prior behavior.
+// the provider's cached key, or all caches when no scoped provider is given.
function createSecretSetter(
storeKey: string,
saver: SecretProvider,
@@ -2249,17 +2246,14 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setBedrockAccessKeyId: (key: string) => {
set({ bedrockAccessKeyId: key });
debouncedSaveSecret("bedrockAccessKeyId", key);
- debouncedPersistToEnv();
},
setBedrockSecretAccessKey: (key: string) => {
set({ bedrockSecretAccessKey: key });
debouncedSaveSecret("bedrockSecretAccessKey", key);
- debouncedPersistToEnv();
},
setBedrockSessionToken: (key: string) => {
set({ bedrockSessionToken: key });
debouncedSaveSecret("bedrockSessionToken", key);
- debouncedPersistToEnv();
},
setAzureEndpoint: (value: string) => {
if (isBrowser) localStorage.setItem("azureEndpoint", value);
@@ -2270,7 +2264,6 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setAzureApiKey: (key: string) => {
set({ azureApiKey: key });
debouncedSaveSecret("azureApiKey", key);
- debouncedPersistToEnv();
},
setAzureDeploymentName: (value: string) => {
if (isBrowser) localStorage.setItem("azureDeploymentName", value);
@@ -2303,7 +2296,6 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setVertexApiKey: (key: string) => {
set({ vertexApiKey: key });
debouncedSaveSecret("vertexApiKey", key);
- debouncedPersistToEnv();
},
setDictationKey: (key: string) => {
@@ -3292,6 +3284,34 @@ export async function initializeSettings(): Promise<void> {
if (!isBrowser) return;
const state = useSettingsStore.getState();
+ let hydratingSecrets = true;
+ const pendingSecretUpdates = new Set<string>();
+
+ // Queue updates until hydration can no longer overwrite them.
+ const refreshApiKey = async (storeKey: string) => {
+ if (!STALE_SECRET_LOCALSTORAGE_KEYS.some((key) => key === storeKey)) return;
+ if (hydratingSecrets) {
+ pendingSecretUpdates.add(storeKey);
+ return;
+ }
+ const saver =
+ SECRET_IPC_SAVERS[storeKey as SecretProvider] ||
+ SECRET_IPC_SAVERS[storeKey.replace(/ApiKey$/, "") as SecretProvider];
+ if (!saver) return;
+ const getter = window.electronAPI?.[
+ saver.replace(/^save/, "get") as keyof typeof window.electronAPI
+ ] as (() => Promise<string | null>) | undefined;
+ if (!getter) return;
+ try {
+ const key = await getter();
+ if (key !== null && typeof key !== "string") return;
+ useSettingsStore.setState({ [storeKey]: key || "" });
+ invalidateApiKeyCaches();
+ } catch {
+ logger.warn("Failed to refresh API key", { storeKey }, "settings");
+ }
+ };
+ window.electronAPI?.onApiKeyUpdated?.(refreshApiKey);
if (window.electronAPI) {
// Preferences are already in localStorage; do not wait for secret or provider hydration.
@@ -3451,6 +3471,10 @@ export async function initializeSettings(): Promise<void> {
{ error: (err as Error).message },
"settings"
);
+ } finally {
+ hydratingSecrets = false;
+ await Promise.all([...pendingSecretUpdates].map(refreshApiKey));
+ pendingSecretUpdates.clear();
}
// Sync dictation key from main process.
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 2dc5439d5..dbb7feabb 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -2230,6 +2230,7 @@ declare global {
onHotkeyRegistrationFailed?: (
callback: (data: { hotkey: string; error: string; suggestions: string[] }) => void
) => () => void;
+ onApiKeyUpdated?: (callback: (storeKey: string) => void) => () => void;
onSettingUpdated?: (callback: (data: { key: string; value: unknown }) => void) => () => void;
onDictationKeyActive?: (callback: (key: string) => void) => () => void;
onLinuxPttPermissionDenied?: (callback: () => void) => () => void;
diff --git a/test/helpers/apiKeyUpdatesIpc.test.js b/test/helpers/apiKeyUpdatesIpc.test.js
new file mode 100644
index 000000000..9e6d1cbdd
--- /dev/null
+++ b/test/helpers/apiKeyUpdatesIpc.test.js
@@ -0,0 +1,459 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const { BYOK_API_KEYS } = require("../../src/config/secretKeys");
+const { deferred } = require("./harness/deferred");
+
+const bindings = [
+ ...BYOK_API_KEYS.map((key) => ({ ...key, channel: `save-${key.base}-key` })),
+ ...[
+ ["corti-client-id", "cortiClientId", "saveCortiClientId"],
+ ["corti-client-secret", "cortiClientSecret", "saveCortiClientSecret"],
+ ["custom-transcription-key", "customTranscriptionApiKey", "saveCustomTranscriptionKey"],
+ ["cleanup-custom-key", "cleanupCustomApiKey", "saveCleanupCustomKey"],
+ ["bedrock-access-key-id", "bedrockAccessKeyId", "saveBedrockAccessKeyId"],
+ ["bedrock-secret-access-key", "bedrockSecretAccessKey", "saveBedrockSecretAccessKey"],
+ ["bedrock-session-token", "bedrockSessionToken", "saveBedrockSessionToken"],
+ ["azure-api-key", "azureApiKey", "saveAzureApiKey"],
+ ["vertex-api-key", "vertexApiKey", "saveVertexApiKey"],
+ ].map(([channel, storeKey, save]) => ({
+ channel: `save-${channel}`,
+ storeKey,
+ save,
+ get: save.replace(/^save/, "get"),
+ })),
+];
+const handlers = new Map();
+const keys = new Map();
+const notifications = [];
+const editor = { id: 1 };
+const windows = [1, 2, 3].map((id) => ({
+ isDestroyed: () => id === 3,
+ webContents: { id, send: (...args) => notifications.push([id, ...args]) },
+}));
+const mintToken = async (key) => `token-${key}`;
+let fetchToken = mintToken;
+const environmentManager = Object.fromEntries(
+ bindings.flatMap(({ get, save, storeKey }) => [
+ [get, () => keys.get(storeKey) || ""],
+ [
+ save,
+ (key) => {
+ keys.set(storeKey, key);
+ return { success: true };
+ },
+ ],
+ ])
+);
+
+// The warm-socket contract the real clients share: a warmup records its options
+// only when it opens the socket (one already open or opening wins), cleanup
+// forgets both, and connect rides a warm socket when one is there.
+class FakeStreaming {
+ warmToken = null;
+ warmConnectionOptions = null;
+ cachedToken = null;
+ isConnected = false;
+ rodeWarm = false;
+ disconnects = 0;
+ adoptMode() {}
+ beginConnecting() {}
+ setTokenRefreshFn() {}
+ getCachedToken() {
+ return this.cachedToken;
+ }
+ cacheToken(token) {
+ this.cachedToken = token;
+ }
+ hasWarmConnection() {
+ return this.warmToken !== null;
+ }
+ cleanupWarmConnection() {
+ this.warmToken = null;
+ this.warmConnectionOptions = null;
+ }
+ cleanupAll() {
+ this.cleanupWarmConnection();
+ }
+ async warmup(options) {
+ if (this.warmToken !== null) return;
+ this.warmToken = options.token;
+ this.warmConnectionOptions = options;
+ }
+ async connect({ token, apiKey }) {
+ this.rodeWarm = this.warmToken !== null;
+ this.token = this.warmToken || token || apiKey;
+ this.warmToken = null;
+ this.isConnected = true;
+ }
+ async disconnect() {
+ this.disconnects += 1;
+ this.isConnected = false;
+ this.warmToken = null;
+ return { text: "" };
+ }
+}
+class FakeOrukeet extends FakeStreaming {}
+
+const modulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+const electron = {
+ app: {
+ getPath: () => "/tmp",
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ on() {},
+ isPackaged: false,
+ },
+ ipcMain: { handle: (name, fn) => handlers.set(name, fn), on() {}, removeHandler() {} },
+ BrowserWindow: {
+ getAllWindows: () => windows,
+ fromWebContents: () => windows[1],
+ },
+ net: {
+ // BYOK mints present the saved key; managed ones present the account session.
+ fetch: async (_url, init) => ({
+ ok: true,
+ json: async () => {
+ const token = await fetchToken(init.headers.Authorization);
+ return { token, clientSecret: token };
+ },
+ }),
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+};
+Module._load = function (request, parent, isMain) {
+ if (request === "electron") return electron;
+ if (parent?.filename === modulePath) {
+ if (
+ [
+ "./assemblyAiStreaming",
+ "./deepgramStreaming",
+ "./cortiStreaming",
+ "./openaiRealtimeStreaming",
+ ].includes(request)
+ )
+ return FakeStreaming;
+ if (request === "./orukeetStreaming")
+ return { OrukeetStreaming: FakeOrukeet, MANAGED_STREAM_OPTIONS: {} };
+ if (request === "./geminiLiveStreaming")
+ return { GeminiLiveStreaming: FakeStreaming, GEMINI_LIVE_MODEL: "gemini-live" };
+ if (request === "./debugLogger") return new Proxy({}, { get: () => () => {} });
+ if (request === "./tokenStore")
+ return {
+ get: () => "account",
+ getState: () => ({ token: "account", generation: 1 }),
+ subscribe: () => () => {},
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (_target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+const target = {
+ environmentManager,
+ assemblyAiStreaming: null,
+ deepgramStreaming: null,
+ cortiStreaming: null,
+ geminiStreaming: null,
+ _dictationStreaming: null,
+ _dictationConnectPromise: null,
+ _dictationIdleTimer: null,
+ _mintStoredCortiToken: async () => ({
+ token: await fetchToken(environmentManager.getCortiClientSecret()),
+ environment: "us",
+ tenant: "base",
+ }),
+};
+test.before(() => {
+ const IPCHandlers = require(modulePath);
+ IPCHandlers.prototype.setupHandlers.call(
+ new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ })
+ );
+});
+const invoke = (channel, ...args) => handlers.get(channel)({ sender: editor }, ...args);
+
+// Managed starts mint from the account, which needs an API URL.
+function withManagedApi(t) {
+ const previous = process.env.OPENWHISPR_API_URL;
+ process.env.OPENWHISPR_API_URL = "https://api.openwhispr.test";
+ t.after(() => {
+ if (previous === undefined) delete process.env.OPENWHISPR_API_URL;
+ else process.env.OPENWHISPR_API_URL = previous;
+ });
+}
+
+// Gemini keeps one connection, warm or live, so its start reports the reuse.
+const rodeWarm = (provider, property, result) =>
+ provider === "gemini" ? result.usedWarmConnection : target[property].rodeWarm;
+
+test("every secret saver notifies peers by name only, including removal", () => {
+ for (const { channel, storeKey, get } of bindings) {
+ for (const value of ["secret-sentinel", ""]) {
+ notifications.length = 0;
+ assert.deepEqual(invoke(channel, value), { success: true });
+ assert.equal(environmentManager[get](), value);
+ assert.deepEqual(notifications, [[2, "api-key-updated", storeKey]]);
+ notifications.length = 0;
+ assert.deepEqual(invoke(channel, value), { success: true });
+ assert.deepEqual(notifications, [], `${storeKey} re-saved unchanged`);
+ }
+ }
+ assert.throws(
+ () => invoke("save-custom-transcription-key", { key: "secret-sentinel" }),
+ TypeError
+ );
+});
+
+// provider, the instance it keeps, the saver of the key it reads, and the session
+// token that key mints.
+const STREAMING = [
+ ["assemblyai", "assemblyAiStreaming", "save-assemblyai-key", (key) => `token-${key}`],
+ ["deepgram", "deepgramStreaming", "save-deepgram-key", (key) => key],
+ ["corti", "cortiStreaming", "save-corti-client-secret", (key) => `token-${key}`],
+ ["gemini", "geminiStreaming", "save-gemini-key", (key) => key],
+];
+
+for (const [provider, property, saveChannel, tokenFor] of STREAMING) {
+ test(`${provider}: a BYOK start rides the socket its warmup opened`, async () => {
+ target[property] = null;
+ invoke(saveChannel, "A");
+ assert.deepEqual(await invoke(`${provider}-streaming-warmup`, { mode: "byok" }), {
+ success: true,
+ });
+ const result = await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ assert.equal(result.success, true);
+ assert.equal(rodeWarm(provider, property, result), true);
+ assert.equal(target[property].token, tokenFor("A"));
+ });
+
+ test(`${provider}: a key saved after the warmup reaches the next start`, async () => {
+ target[property] = null;
+ invoke(saveChannel, "A");
+ await invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ invoke(saveChannel, "B");
+ const result = await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ assert.equal(result.success, true);
+ assert.equal(rodeWarm(provider, property, result), false);
+ assert.equal(target[property].token, tokenFor("B"));
+ });
+
+ test(`${provider}: a warmup after a key save does not vouch for the socket it finds`, async () => {
+ target[property] = null;
+ invoke(saveChannel, "A");
+ await invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ invoke(saveChannel, "B");
+ const warmup = await invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ const result = await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ assert.equal(target[property].token, tokenFor("B"));
+ // Gemini's warm connection is also its live one, so only a start replaces it.
+ if (provider === "gemini") {
+ assert.equal(warmup.alreadyWarm, true);
+ assert.equal(rodeWarm(provider, property, result), false);
+ } else {
+ assert.deepEqual(warmup, { success: true });
+ assert.equal(rodeWarm(provider, property, result), true);
+ }
+ });
+
+ test(`${provider}: re-saving the unchanged key keeps the warm socket`, async () => {
+ target[property] = null;
+ invoke(saveChannel, "A");
+ await invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ invoke(saveChannel, "A");
+ const result = await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ assert.equal(rodeWarm(provider, property, result), true);
+ assert.equal(target[property].token, tokenFor("A"));
+ });
+
+ test(`${provider}: a key saved mid-session leaves the live session alone`, async () => {
+ target[property] = null;
+ invoke(saveChannel, "A");
+ await invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ const live = target[property];
+ invoke(saveChannel, "B");
+ assert.equal(target[property], live);
+ assert.equal(live.isConnected, true);
+ assert.equal(live.disconnects, 0);
+ });
+}
+
+for (const [provider, property, saveChannel] of STREAMING.filter(([name]) => name !== "corti")) {
+ test(`${provider}: a key save leaves a managed warm socket in place`, async (t) => {
+ withManagedApi(t);
+ target[property] = null;
+ assert.deepEqual(await invoke(`${provider}-streaming-warmup`, { mode: "openwhispr" }), {
+ success: true,
+ });
+ invoke(saveChannel, "B");
+ const result = await invoke(`${provider}-streaming-start`, { mode: "openwhispr" });
+ assert.equal(result.success, true);
+ assert.equal(rodeWarm(provider, property, result), true);
+ });
+}
+
+for (const [provider, property, saveChannel] of STREAMING.filter(([name]) =>
+ ["assemblyai", "corti"].includes(name)
+)) {
+ test(`${provider}: a key saved while the warmup mints is not ridden by the next start`, async (t) => {
+ t.after(() => (fetchToken = mintToken));
+ target[property] = null;
+ invoke(saveChannel, "A");
+ const minted = deferred();
+ fetchToken = async (key) => {
+ await minted.promise;
+ return mintToken(key);
+ };
+ const warming = invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ invoke(saveChannel, "B");
+ minted.resolve();
+ assert.deepEqual(await warming, { success: true });
+ const result = await invoke(`${provider}-streaming-start`, { mode: "byok" });
+ assert.equal(result.success, true);
+ assert.equal(rodeWarm(provider, property, result), false);
+ assert.equal(target[property].token, "token-B");
+ });
+
+ test(`${provider}: a start overlapping an old-key warmup does not ride its socket`, async (t) => {
+ t.after(() => (fetchToken = mintToken));
+ target[property] = null;
+ invoke(saveChannel, "A");
+ const minted = { A: deferred(), B: deferred() };
+ fetchToken = async (key) => {
+ await minted[key].promise;
+ return mintToken(key);
+ };
+ const warming = invoke(`${provider}-streaming-warmup`, { mode: "byok" });
+ invoke(saveChannel, "B");
+ const starting = invoke(`${provider}-streaming-start`, { mode: "byok" });
+ minted.A.resolve();
+ // The old-key socket opens while the start is still minting with the new key.
+ await warming;
+ minted.B.resolve();
+ const result = await starting;
+ assert.equal(result.success, true);
+ assert.equal(rodeWarm(provider, property, result), false);
+ assert.equal(target[property].token, "token-B");
+ });
+}
+
+test("assemblyai: a socket opened on the old key loses to the save, even when it wins the race", async (t) => {
+ t.after(() => (fetchToken = mintToken));
+ target.assemblyAiStreaming = null;
+ invoke("save-assemblyai-key", "A");
+ const minted = { A: deferred(), B: deferred() };
+ fetchToken = async (key) => {
+ await minted[key].promise;
+ return mintToken(key);
+ };
+ const first = invoke("assemblyai-streaming-warmup", { mode: "byok" });
+ invoke("save-assemblyai-key", "B");
+ const second = invoke("assemblyai-streaming-warmup", { mode: "byok" });
+ minted.A.resolve();
+ await first;
+ // The second warmup finds the first one's socket open and keeps it.
+ minted.B.resolve();
+ await second;
+ const result = await invoke("assemblyai-streaming-start", { mode: "byok" });
+ assert.equal(result.success, true);
+ assert.equal(target.assemblyAiStreaming.rodeWarm, false);
+ assert.equal(target.assemblyAiStreaming.token, "token-B");
+});
+
+test("gemini: a warm socket never crosses between managed and BYOK", async (t) => {
+ withManagedApi(t);
+ target.geminiStreaming = null;
+ invoke("save-gemini-key", "A");
+ await invoke("gemini-streaming-warmup", { mode: "openwhispr" });
+ let result = await invoke("gemini-streaming-start", { mode: "byok" });
+ assert.equal(result.usedWarmConnection, false);
+ assert.equal(target.geminiStreaming.token, "A");
+ await invoke("gemini-streaming-stop");
+ await invoke("gemini-streaming-warmup", { mode: "byok" });
+ result = await invoke("gemini-streaming-start", { mode: "openwhispr" });
+ assert.equal(result.usedWarmConnection, false);
+ assert.equal(target.geminiStreaming.token, "token-Bearer account");
+});
+
+// Tinfoil reads the saved key whatever the transcription mode says.
+for (const [provider, saveChannel, mode] of [
+ ["openai-realtime", "save-openai-key", "byok"],
+ ["tinfoil-realtime", "save-tinfoil-key", "byok"],
+ ["tinfoil-realtime", "save-tinfoil-key", "openwhispr"],
+ ["orukeet", "save-custom-transcription-key", "byok"],
+]) {
+ const options = { mode, provider, baseUrl: "https://example.com/v1" };
+
+ test(`${provider} (${mode}): a start rides the connection its warmup opened`, async (t) => {
+ t.after(() => invoke("dictation-realtime-stop"));
+ target._dictationStreaming = null;
+ invoke(saveChannel, "A");
+ assert.deepEqual(await invoke("dictation-realtime-warmup", options), { success: true });
+ const warmed = target._dictationStreaming;
+ assert.equal((await invoke("dictation-realtime-start", options)).success, true);
+ assert.equal(target._dictationStreaming, warmed);
+ assert.equal(warmed.token, "A");
+ });
+
+ test(`${provider} (${mode}): a key saved after the warmup reaches the next start`, async (t) => {
+ t.after(() => invoke("dictation-realtime-stop"));
+ target._dictationStreaming = null;
+ invoke(saveChannel, "A");
+ await invoke("dictation-realtime-warmup", options);
+ const warmed = target._dictationStreaming;
+ invoke(saveChannel, "B");
+ assert.equal((await invoke("dictation-realtime-start", options)).success, true);
+ assert.notEqual(target._dictationStreaming, warmed);
+ assert.equal(target._dictationStreaming.token, "B");
+ });
+
+ test(`${provider} (${mode}): a key saved mid-session leaves the live session alone`, async (t) => {
+ t.after(() => invoke("dictation-realtime-stop"));
+ target._dictationStreaming = null;
+ invoke(saveChannel, "A");
+ await invoke("dictation-realtime-warmup", options);
+ await invoke("dictation-realtime-start", options);
+ const live = target._dictationStreaming;
+ invoke(saveChannel, "B");
+ assert.equal(target._dictationStreaming, live);
+ assert.equal(live.isConnected, true);
+ assert.equal(live.disconnects, 0);
+ });
+}
+
+test("openai-realtime: a key save leaves a managed warm connection in place", async (t) => {
+ withManagedApi(t);
+ t.after(() => invoke("dictation-realtime-stop"));
+ const options = { mode: "openwhispr", provider: "openai-realtime" };
+ target._dictationStreaming = null;
+ assert.deepEqual(await invoke("dictation-realtime-warmup", options), { success: true });
+ const warmed = target._dictationStreaming;
+ invoke("save-openai-key", "B");
+ assert.equal((await invoke("dictation-realtime-start", options)).success, true);
+ assert.equal(target._dictationStreaming, warmed);
+});
+
+test("an unknown realtime provider still fails closed", async () => {
+ const result = await invoke("dictation-realtime-warmup", { mode: "byok", provider: "unknown" });
+ assert.equal(result.success, false);
+ assert.match(result.error, /Unsupported realtime token provider/);
+});
diff --git a/test/helpers/settingsStoreApiKeyUpdates.test.js b/test/helpers/settingsStoreApiKeyUpdates.test.js
new file mode 100644
index 000000000..8b5bd02fa
--- /dev/null
+++ b/test/helpers/settingsStoreApiKeyUpdates.test.js
@@ -0,0 +1,226 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { BYOK_API_KEYS } = require("../../src/config/secretKeys");
+const { deferred } = require("./harness/deferred");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installMicCaptureGlobals,
+} = require("../lib/rendererTestHarness");
+
+const bindings = [
+ ...BYOK_API_KEYS,
+ ...[
+ ["customTranscriptionApiKey", "getCustomTranscriptionKey"],
+ ["cleanupCustomApiKey", "getCleanupCustomKey"],
+ ["cortiClientId", "getCortiClientId"],
+ ["cortiClientSecret", "getCortiClientSecret"],
+ ["bedrockAccessKeyId", "getBedrockAccessKeyId"],
+ ["bedrockSecretAccessKey", "getBedrockSecretAccessKey"],
+ ["bedrockSessionToken", "getBedrockSessionToken"],
+ ["azureApiKey", "getAzureApiKey"],
+ ["vertexApiKey", "getVertexApiKey"],
+ ].map(([storeKey, get]) => ({ storeKey, get })),
+];
+
+async function loadSettings(t, overrides = {}) {
+ const keys = new Map(bindings.map(({ storeKey }) => [storeKey, `old-${storeKey}`]));
+ const events = new EventTarget();
+ let update;
+ const api = Object.fromEntries(
+ bindings.map(({ storeKey, get }) => [get, async () => keys.get(storeKey)])
+ );
+ const { window, storage } = installBrowserGlobals(t, {
+ initialStorage: { _dictationAgentSeeded: "1", customDictionary: '["OpenWhispr"]' },
+ window: {
+ addEventListener: events.addEventListener.bind(events),
+ removeEventListener: events.removeEventListener.bind(events),
+ dispatchEvent: events.dispatchEvent.bind(events),
+ cacheClears: [],
+ warnings: [],
+ electronAPI: {
+ ...api,
+ setDictionary: async () => {},
+ onApiKeyUpdated: (callback) => {
+ update = callback;
+ },
+ ...overrides,
+ },
+ },
+ });
+ installMicCaptureGlobals(t);
+ const vite = await createRendererServer(t, {
+ mockModules: {
+ "/services/ReasoningService":
+ "export default { clearApiKeyCache: (...args) => window.cacheClears.push(args) };",
+ "/utils/logger": `export default {
+ debug() {}, info() {}, error() {}, logReasoning() {},
+ warn: (...args) => window.warnings.push(args)
+ };`,
+ },
+ });
+ await vite.ssrLoadModule("/services/ReasoningService");
+ const settings = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ return { ...settings, keys, storage, window, vite, update: (key) => update(key) };
+}
+
+test("all registered secrets refresh in memory without persistence or save loops", async (t) => {
+ const context = await loadSettings(t);
+ await context.initializeSettings();
+ const changes = [];
+ let saves = 0;
+ let persists = 0;
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ context.window.addEventListener("api-key-changed", () => changes.push(true));
+ context.window.electronAPI.saveAllKeysToEnv = async () => {
+ persists += 1;
+ };
+ for (const { storeKey, get } of bindings) {
+ context.window.electronAPI[get.replace(/^get/, "save")] = async () => {
+ saves += 1;
+ };
+ for (const value of [`new-${storeKey}`, ""]) {
+ context.keys.set(storeKey, value);
+ await context.update(storeKey);
+ assert.equal(context.useSettingsStore.getState()[storeKey], value, storeKey);
+ assert.equal(context.storage.getItem(storeKey), null, storeKey);
+ }
+ }
+ t.mock.timers.tick(1000);
+ assert.equal(saves, 0);
+ assert.equal(persists, 0);
+ assert.equal(changes.length, bindings.length * 2);
+ await context.vite.ssrLoadModule("/services/ReasoningService");
+ assert.equal(context.window.cacheClears.length, bindings.length * 2);
+ assert.ok(context.window.cacheClears.every(([provider]) => provider === undefined));
+});
+
+test("the next batch dictation reads the changed key, not its populated cache", async (t) => {
+ const context = await loadSettings(t);
+ await context.initializeSettings();
+ const { default: AudioManager } = await context.vite.ssrLoadModule("/helpers/audioManager.js");
+ const manager = new AudioManager();
+ try {
+ for (const [provider, storeKey] of [
+ ["openai", "openaiApiKey"],
+ ["groq", "groqApiKey"],
+ ["custom", "customTranscriptionApiKey"],
+ ]) {
+ context.useSettingsStore.setState({
+ useLocalWhisper: false,
+ transcriptionMode: "providers",
+ cloudTranscriptionMode: "byok",
+ cloudTranscriptionProvider: provider,
+ });
+ assert.equal(await manager.getAPIKey(), `old-${storeKey}`);
+ context.keys.set(storeKey, `new-${storeKey}`);
+ await context.update(storeKey);
+ assert.equal(await manager.getAPIKey(), `new-${storeKey}`);
+ context.keys.set(storeKey, "");
+ await context.update(storeKey);
+ if (provider === "custom") assert.equal(await manager.getAPIKey(), null);
+ else await assert.rejects(() => manager.getAPIKey(), { code: "API_KEY_MISSING" });
+ }
+ } finally {
+ manager.cleanup();
+ }
+});
+
+test("a changed key re-warms streaming dictation without opening the mic", async (t) => {
+ const warmups = [];
+ const context = await loadSettings(t, {
+ deepgramStreamingWarmup: async (options) => {
+ warmups.push(options);
+ return { success: true };
+ },
+ });
+ await context.initializeSettings();
+ const { default: AudioManager } = await context.vite.ssrLoadModule("/helpers/audioManager.js");
+ const manager = new AudioManager();
+ const runs = [];
+ const warmup = manager.warmupStreamingConnection.bind(manager);
+ manager.warmupStreamingConnection = (options) => {
+ runs.push(warmup(options));
+ return runs.at(-1);
+ };
+ let micOpens = 0;
+ const { getUserMedia } = navigator.mediaDevices;
+ navigator.mediaDevices.getUserMedia = (...args) => {
+ micOpens += 1;
+ return getUserMedia(...args);
+ };
+ try {
+ context.useSettingsStore.setState({
+ useLocalWhisper: false,
+ transcriptionMode: "providers",
+ cloudTranscriptionMode: "byok",
+ cloudTranscriptionProvider: "deepgram",
+ });
+ context.keys.set("deepgramApiKey", "new-deepgramApiKey");
+ await context.update("deepgramApiKey");
+ assert.equal(runs.length, 1);
+ assert.equal(await runs[0], true);
+ assert.equal(warmups[0].mode, "byok");
+ assert.equal(micOpens, 0);
+
+ // A dictation in progress keeps its connection; the post-dictation re-warm
+ // picks the new key up.
+ manager.isRecording = true;
+ context.keys.set("deepgramApiKey", "newer-deepgramApiKey");
+ await context.update("deepgramApiKey");
+ assert.equal(runs.length, 1);
+ } finally {
+ manager.cleanup();
+ }
+});
+
+for (const { name, value, failHydration } of [
+ { name: "replacement", value: "new-custom" },
+ { name: "removal", value: "" },
+ { name: "failed hydration", value: "new-custom", failHydration: true },
+]) {
+ test(`startup ${name} survives hydration`, { timeout: 15_000 }, async (t) => {
+ const started = deferred();
+ const held = deferred();
+ let reads = 0;
+ const context = await loadSettings(t, {
+ getCustomTranscriptionKey: async () => {
+ if (++reads > 1) return value;
+ started.resolve();
+ await held.promise;
+ if (failHydration) throw new Error("hydration failed");
+ return "old-custom";
+ },
+ });
+ const initialization = context.initializeSettings();
+ await started.promise;
+ await context.update("customTranscriptionApiKey");
+ held.resolve();
+ await initialization;
+ assert.equal(context.useSettingsStore.getState().customTranscriptionApiKey, value);
+ assert.equal(reads, 2);
+ assert.equal(context.storage.getItem("customTranscriptionApiKey"), null);
+ });
+}
+
+test("unknown settings cannot invoke getters, and refresh errors cannot log secrets", async (t) => {
+ const context = await loadSettings(t);
+ await context.initializeSettings();
+ let forbiddenReads = 0;
+ context.window.electronAPI.getDictationKey = async () => {
+ forbiddenReads += 1;
+ return "not-a-secret";
+ };
+ await context.update("dictationKey");
+ assert.equal(forbiddenReads, 0);
+ context.window.electronAPI.getCustomTranscriptionKey = async () => {
+ throw new Error("secret-leak-marker");
+ };
+ await context.update("customTranscriptionApiKey");
+ assert.ok(context.window.warnings.length > 0);
+ assert.ok(!JSON.stringify(context.window.warnings).includes("secret-leak-marker"));
+ assert.equal(
+ context.useSettingsStore.getState().customTranscriptionApiKey,
+ "old-customTranscriptionApiKey"
+ );
+});
diff --git a/test/helpers/streamingConnectionLifecycle.test.js b/test/helpers/streamingConnectionLifecycle.test.js
index 50f1c1e15..f123d826c 100644
--- a/test/helpers/streamingConnectionLifecycle.test.js
+++ b/test/helpers/streamingConnectionLifecycle.test.js
@@ -1,5 +1,6 @@
const test = require("node:test");
const assert = require("node:assert/strict");
+const { WebSocketServer } = require("ws");
const AssemblyAiStreaming = require("../../src/helpers/assemblyAiStreaming");
const CortiStreaming = require("../../src/helpers/cortiStreaming");
@@ -38,3 +39,104 @@ for (const [name, StreamingClient, notifyMethod] of clients) {
assert.deepEqual(errors, ["socket failed"]);
});
}
+
+// Completes each client's warm handshake: AssemblyAI waits for Begin, Corti for
+// CONFIG_ACCEPTED after its config message, Deepgram only for the open.
+async function withWarmServer(run) {
+ const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
+ await new Promise((resolve) => server.once("listening", resolve));
+ server.on("connection", (socket) => {
+ socket.send(JSON.stringify({ type: "Begin", id: "warm-session" }));
+ socket.on("message", (data, isBinary) => {
+ if (!isBinary && JSON.parse(data).type === "config") {
+ socket.send(JSON.stringify({ type: "CONFIG_ACCEPTED", sessionId: "warm-session" }));
+ }
+ });
+ });
+ try {
+ await run(`ws://127.0.0.1:${server.address().port}`, server);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+// ipcHandlers.js reads warmConnectionOptions to tell a warm socket opened before
+// the latest key save from one opened after it.
+for (const [name, StreamingClient] of [
+ ["AssemblyAI", AssemblyAiStreaming],
+ ["Deepgram", DeepgramStreaming],
+ ["Corti", CortiStreaming],
+]) {
+ test(`${name} keeps the options its warm socket opened with until it is dropped`, async () => {
+ await withWarmServer(async (url) => {
+ const streaming = new StreamingClient();
+ streaming.buildWebSocketUrl = () => url;
+ const opened = { token: "t", environment: "us", tenant: "base", credentialGeneration: 1 };
+ try {
+ await streaming.warmup(opened);
+ await streaming.warmup({ ...opened, credentialGeneration: 2 });
+ assert.equal(streaming.hasWarmConnection(), true);
+ assert.equal(streaming.warmConnectionOptions.credentialGeneration, 1);
+ streaming.cleanupWarmConnection();
+ assert.equal(streaming.warmConnectionOptions, null);
+ } finally {
+ streaming.cleanupWarmConnection();
+ }
+ });
+ });
+}
+
+// ipcHandlers.js drops a stale warm socket and warms a new one straight away; the
+// dropped socket's close arrives afterwards and must not tear the new one down.
+for (const [name, StreamingClient] of [
+ ["AssemblyAI", AssemblyAiStreaming],
+ ["Deepgram", DeepgramStreaming],
+ ["Corti", CortiStreaming],
+]) {
+ test(`${name} keeps a replacement warm socket when the dropped one closes`, async () => {
+ await withWarmServer(async (url) => {
+ const streaming = new StreamingClient();
+ streaming.buildWebSocketUrl = () => url;
+ const options = { token: "t", environment: "us", tenant: "base", credentialGeneration: 1 };
+ try {
+ await streaming.warmup(options);
+ const dropped = streaming.warmConnection;
+ const droppedClosed = new Promise((resolve) => dropped.once("close", resolve));
+ streaming.cleanupWarmConnection();
+ await streaming.warmup({ ...options, credentialGeneration: 2 });
+ await droppedClosed;
+ assert.equal(streaming.hasWarmConnection(), true);
+ assert.equal(streaming.warmConnectionOptions.credentialGeneration, 2);
+ assert.equal(streaming.rewarmTimer ?? null, null);
+ } finally {
+ streaming.cleanupWarmConnection();
+ }
+ });
+ });
+}
+
+// A Corti socket is opened against one region and tenant, so a start for
+// another must not ride it.
+for (const [label, requested, connections] of [
+ ["rides a warm socket for the same region and tenant", {}, 1],
+ ["cold-starts when the region changed", { environment: "eu" }, 2],
+ ["cold-starts when the tenant changed", { tenant: "other" }, 2],
+]) {
+ test(`Corti ${label}`, async () => {
+ await withWarmServer(async (url, server) => {
+ let opened = 0;
+ server.on("connection", () => (opened += 1));
+ const streaming = new CortiStreaming();
+ streaming.buildWebSocketUrl = () => url;
+ const warm = { token: "t", environment: "us", tenant: "base" };
+ try {
+ await streaming.warmup(warm);
+ await streaming.connect({ ...warm, ...requested });
+ assert.equal(opened, connections);
+ } finally {
+ streaming.cleanupWarmConnection();
+ streaming.cleanup();
+ }
+ });
+ });
+}