refactor(speech): send transcription and the key check through one request helper

This commit is contained in:
Kelvin Amoaba
2026-11-09 07:49:28 +00:00
parent f715765683
commit 270baa3fd8
2 changed files with 23 additions and 20 deletions
+6 -10
View File
@@ -1,7 +1,6 @@
import { getMainHttpClient } from '../network/http-client'
import { saveOpenAiSpeechApiKey } from './openai-api-key-store'
import {
OPENAI_TRANSCRIPTION_URL,
postOpenAiTranscription,
readOpenAiErrorMessage,
type OpenAiTranscriptionResponse
} from './openai-transcription-client'
@@ -21,14 +20,11 @@ async function rejectUnauthorizedOpenAiKey(apiKey: string): Promise<void> {
let response: Response
try {
// An empty form is refused before any transcription, but only after OpenAI checks the key.
response = await getMainHttpClient().fetch(OPENAI_TRANSCRIPTION_URL, {
method: 'POST',
// Bearer auth only: keep OpenAI's cookies out of the shared desktop session.
credentials: 'omit',
headers: { Authorization: `Bearer ${apiKey}` },
body: new FormData(),
signal: AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS)
})
response = await postOpenAiTranscription(
apiKey,
new FormData(),
AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS)
)
} catch {
return
}
+17 -10
View File
@@ -69,6 +69,22 @@ function encodePcm16Wav(chunks: Float32Array[], sampleRate: number): Buffer<Arra
return buffer
}
/** The one request both transcription and the key check send; the main HTTP client follows the app's proxy. */
export function postOpenAiTranscription(
apiKey: string,
form: FormData,
signal: AbortSignal
): Promise<Response> {
return getMainHttpClient().fetch(OPENAI_TRANSCRIPTION_URL, {
method: 'POST',
// Bearer auth only: keep OpenAI's cookies out of the shared desktop session.
credentials: 'omit',
signal,
headers: { Authorization: `Bearer ${apiKey}` },
body: form
})
}
export function readOpenAiErrorMessage(data: OpenAiTranscriptionResponse): string | undefined {
return typeof data.error?.message === 'string'
? sanitizeOpenAiTranscriptionErrorMessage(data.error.message)
@@ -152,16 +168,7 @@ export class OpenAiTranscriptionSession {
}
private async upload(form: FormData, signal: AbortSignal): Promise<string> {
const response = await getMainHttpClient().fetch(OPENAI_TRANSCRIPTION_URL, {
method: 'POST',
// Bearer auth only: keep OpenAI's cookies out of the shared desktop session.
credentials: 'omit',
signal,
headers: {
Authorization: `Bearer ${this.readApiKey()}`
},
body: form
})
const response = await postOpenAiTranscription(this.readApiKey(), form, signal)
const data = (await response.json().catch(() => ({}))) as OpenAiTranscriptionResponse
if (!response.ok) {