Add OpenAI cloud speech transcription (#4707)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-06-07 16:22:16 -07:00
committed by GitHub
co-authored by Orca
parent e934029e0e
commit aa0d2ff461
22 changed files with 991 additions and 111 deletions
+32
View File
@@ -7,6 +7,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
description:
'Highest accuracy for 25 European languages. Punctuation, capitalization, and word-level timestamps.',
type: 'transducer',
provider: 'local',
language: 'multilingual',
sizeBytes: 180_000_000,
downloadUrl:
@@ -25,6 +26,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
description:
'English only. Faster than v3 with similar accuracy. Punctuation and capitalization.',
type: 'transducer',
provider: 'local',
language: 'en',
sizeBytes: 170_000_000,
downloadUrl:
@@ -41,6 +43,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
label: 'Zipformer Bilingual',
description: 'Chinese + English with code-switching. Low-latency real-time streaming.',
type: 'transducer',
provider: 'local',
language: 'zh-en',
sizeBytes: 130_000_000,
downloadUrl:
@@ -63,6 +66,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
description:
'Chinese (Mandarin + dialects) + English. Strong on accented and regional Chinese.',
type: 'paraformer',
provider: 'local',
language: 'zh-en',
sizeBytes: 115_000_000,
downloadUrl:
@@ -78,6 +82,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
label: 'Zipformer Streaming EN',
description: 'English only. Lightweight 20M-param model, good balance of speed and size.',
type: 'transducer',
provider: 'local',
language: 'en',
sizeBytes: 128_000_000,
downloadUrl:
@@ -99,6 +104,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
label: 'Zipformer Streaming ZH',
description: 'Chinese only. Ultra-lightweight 14M-param model, ideal for low-resource devices.',
type: 'transducer',
provider: 'local',
language: 'zh',
sizeBytes: 74_000_000,
downloadUrl:
@@ -120,6 +126,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
label: 'Whisper Tiny',
description: '90+ languages. Lower accuracy than Parakeet but broadest language coverage.',
type: 'whisper',
provider: 'local',
language: 'multilingual',
sizeBytes: 116_000_000,
downloadUrl:
@@ -129,9 +136,34 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
files: ['tiny-encoder.onnx', 'tiny-decoder.onnx', 'tiny-tokens.txt'],
sampleRate: 16000,
streaming: false
},
{
id: 'openai-gpt-4o-mini-transcribe',
label: 'GPT-4o mini Transcribe',
description:
'Cloud transcription with strong accuracy and low cost. Requires an OpenAI API key.',
type: 'openai',
provider: 'openai',
language: 'multilingual',
sampleRate: 16000,
streaming: false
},
{
id: 'openai-gpt-4o-transcribe',
label: 'GPT-4o Transcribe',
description: 'Cloud transcription with higher accuracy. Requires an OpenAI API key.',
type: 'openai',
provider: 'openai',
language: 'multilingual',
sampleRate: 16000,
streaming: false
}
]
export function getCatalogModel(id: string): SpeechModelManifest | undefined {
return SPEECH_MODEL_CATALOG.find((m) => m.id === id)
}
export function isLocalSpeechModel(manifest: SpeechModelManifest): boolean {
return manifest.provider === 'local'
}
+32 -1
View File
@@ -6,7 +6,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SPEECH_MODEL_CATALOG } from './model-catalog'
import { ModelManager } from './model-manager'
const { httpsGetMock, spawnMock } = vi.hoisted(() => ({
const { hasOpenAiSpeechApiKeyMock, httpsGetMock, spawnMock } = vi.hoisted(() => ({
hasOpenAiSpeechApiKeyMock: vi.fn(),
httpsGetMock: vi.fn(),
spawnMock: vi.fn()
}))
@@ -27,6 +28,10 @@ vi.mock('https', async () => {
return { ...(actual as Record<string, unknown>), get: httpsGetMock }
})
vi.mock('./openai-api-key-store', () => ({
hasOpenAiSpeechApiKey: hasOpenAiSpeechApiKeyMock
}))
type ModelManagerInternals = {
verifyArchiveSha256: (archivePath: string, expectedSha256: string) => Promise<void>
downloadFile: (
@@ -48,11 +53,16 @@ type ModelManagerInternals = {
describe('ModelManager', () => {
beforeEach(() => {
httpsGetMock.mockReset()
hasOpenAiSpeechApiKeyMock.mockReset()
hasOpenAiSpeechApiKeyMock.mockReturnValue(false)
spawnMock.mockReset()
})
it('requires pinned SHA-256 hashes for every catalog archive', () => {
for (const manifest of SPEECH_MODEL_CATALOG) {
if (manifest.provider !== 'local') {
continue
}
expect(manifest.archiveSha256).toMatch(/^[a-f0-9]{64}$/)
}
})
@@ -93,6 +103,27 @@ describe('ModelManager', () => {
}
})
it('marks OpenAI transcription models ready only when an API key is configured', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-'))
try {
const manager = new ModelManager(dir)
await expect(manager.getModelState('openai-gpt-4o-mini-transcribe')).resolves.toEqual({
id: 'openai-gpt-4o-mini-transcribe',
status: 'not-downloaded'
})
hasOpenAiSpeechApiKeyMock.mockReturnValue(true)
await expect(manager.getModelState('openai-gpt-4o-mini-transcribe')).resolves.toEqual({
id: 'openai-gpt-4o-mini-transcribe',
status: 'ready'
})
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('aborts an in-flight model download request when cancelled', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-'))
try {
+25 -1
View File
@@ -13,7 +13,8 @@ import type {
SpeechModelState,
SpeechModelStatus
} from '../../shared/speech-types'
import { SPEECH_MODEL_CATALOG, getCatalogModel } from './model-catalog'
import { SPEECH_MODEL_CATALOG, getCatalogModel, isLocalSpeechModel } from './model-catalog'
import { hasOpenAiSpeechApiKey } from './openai-api-key-store'
import { resolveTarExecutable } from './tar-executable'
type DownloadHandle = {
@@ -68,6 +69,13 @@ export class ModelManager {
return { id: modelId, status: 'error', error: 'Unknown model' }
}
if (manifest.provider === 'openai') {
return {
id: modelId,
status: hasOpenAiSpeechApiKey() ? 'ready' : 'not-downloaded'
}
}
const modelDir = this.getModelDir(modelId)
if (existsSync(modelDir) && this.validateModelFiles(manifest, modelDir)) {
const state: SpeechModelState = { id: modelId, status: 'ready' }
@@ -97,6 +105,9 @@ export class ModelManager {
}
private validateModelFiles(manifest: SpeechModelManifest, modelDir: string): boolean {
if (!manifest.files) {
return false
}
return manifest.files.every((f) => existsSync(join(modelDir, f)))
}
@@ -109,6 +120,12 @@ export class ModelManager {
if (!manifest) {
throw new Error(`Unknown model: ${modelId}`)
}
if (!isLocalSpeechModel(manifest)) {
throw new Error(`Model does not support downloads: ${modelId}`)
}
if (!manifest.downloadUrl || !manifest.archiveSha256 || !manifest.sizeBytes) {
throw new Error(`Model download metadata missing: ${modelId}`)
}
const modelDir = this.getModelDir(modelId)
if (existsSync(modelDir) && this.validateModelFiles(manifest, modelDir)) {
@@ -213,6 +230,10 @@ export class ModelManager {
if (!getCatalogModel(modelId)) {
throw new Error(`Unknown model: ${modelId}`)
}
const manifest = getCatalogModel(modelId)
if (!manifest || !isLocalSpeechModel(manifest)) {
throw new Error(`Model does not support deletion: ${modelId}`)
}
this.cancelDownload(modelId)
const modelDir = this.getModelDir(modelId)
if (existsSync(modelDir)) {
@@ -542,6 +563,9 @@ export class ModelManager {
}
private async flattenNestedDir(modelDir: string, manifest: SpeechModelManifest): Promise<void> {
if (!manifest.files) {
return
}
const entries = await readdir(modelDir, { withFileTypes: true })
for (const entry of entries) {
if (entry.isDirectory()) {
@@ -0,0 +1,88 @@
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import type * as Os from 'os'
import { join } from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const safeStorageMock = vi.hoisted(() => ({
decryptString: vi.fn((value: Buffer) => value.toString('utf8')),
encryptString: vi.fn((value: string) => Buffer.from(value)),
isEncryptionAvailable: vi.fn(() => true)
}))
let tempHome = ''
async function loadStoreModule() {
vi.resetModules()
vi.doMock('electron', () => ({
safeStorage: safeStorageMock
}))
vi.doMock('os', async () => {
const actual = await vi.importActual<typeof Os>('os')
return { ...actual, homedir: () => tempHome }
})
return import('./openai-api-key-store')
}
beforeEach(() => {
tempHome = mkdtempLike('orca-openai-key-store-')
safeStorageMock.decryptString.mockClear()
safeStorageMock.encryptString.mockClear()
safeStorageMock.isEncryptionAvailable.mockClear()
safeStorageMock.isEncryptionAvailable.mockReturnValue(true)
})
function mkdtempLike(prefix: string): string {
return mkdtempSync(join(tmpdir(), prefix))
}
function writeStoredOpenAiKey(value: string): void {
const orcaDir = join(tempHome, '.orca')
mkdirSync(orcaDir, { recursive: true })
writeFileSync(join(orcaDir, 'openai-speech-token.enc'), value)
}
describe('OpenAI speech API key store', () => {
it('checks configured status without decrypting or touching safeStorage', async () => {
writeStoredOpenAiKey('encrypted-key')
const store = await loadStoreModule()
expect(store.hasOpenAiSpeechApiKey()).toBe(true)
expect(safeStorageMock.isEncryptionAvailable).not.toHaveBeenCalled()
expect(safeStorageMock.decryptString).not.toHaveBeenCalled()
})
it('decrypts only when the key is read for an API request', async () => {
writeStoredOpenAiKey('encrypted-key')
const store = await loadStoreModule()
expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key')
expect(safeStorageMock.decryptString).toHaveBeenCalledOnce()
})
it('caches the decrypted key so repeated dictations do not repeatedly touch safeStorage', async () => {
writeStoredOpenAiKey('encrypted-key')
const store = await loadStoreModule()
expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key')
expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key')
expect(safeStorageMock.decryptString).toHaveBeenCalledOnce()
})
it('uses the in-memory key after save without decrypting from safeStorage', async () => {
const store = await loadStoreModule()
store.saveOpenAiSpeechApiKey('saved-key')
expect(store.readOpenAiSpeechApiKey()).toBe('saved-key')
expect(safeStorageMock.decryptString).not.toHaveBeenCalled()
})
it('reports missing status without creating storage files', async () => {
const store = await loadStoreModule()
expect(store.hasOpenAiSpeechApiKey()).toBe(false)
expect(existsSync(join(tempHome, '.orca'))).toBe(false)
expect(safeStorageMock.decryptString).not.toHaveBeenCalled()
})
})
+99
View File
@@ -0,0 +1,99 @@
import { safeStorage } from 'electron'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { homedir } from 'os'
import { join } from 'path'
type StoredOpenAiKey = {
encryptedKeyBase64: string
}
const OPENAI_SPEECH_TOKEN_FILE = 'openai-speech-token.enc'
let cachedOpenAiSpeechApiKey: string | null = null
function getOrcaDir(): string {
return join(homedir(), '.orca')
}
function ensureOrcaDir(): void {
const dir = getOrcaDir()
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true })
}
}
function getOpenAiKeyPath(): string {
return join(getOrcaDir(), OPENAI_SPEECH_TOKEN_FILE)
}
function readLegacyJsonStoredOpenAiKey(): StoredOpenAiKey | null {
const keyPath = getOpenAiKeyPath()
if (!existsSync(keyPath)) {
return null
}
try {
const parsed = JSON.parse(readFileSync(keyPath, 'utf8')) as Partial<StoredOpenAiKey>
if (typeof parsed.encryptedKeyBase64 !== 'string' || parsed.encryptedKeyBase64 === '') {
return null
}
return { encryptedKeyBase64: parsed.encryptedKeyBase64 }
} catch {
return null
}
}
export function hasOpenAiSpeechApiKey(): boolean {
// Why: Settings and model-state refresh call this on startup; checking file
// existence avoids decrypting safeStorage and triggering macOS keychain prompts.
return existsSync(getOpenAiKeyPath())
}
export function saveOpenAiSpeechApiKey(apiKey: string): void {
const trimmed = apiKey.trim()
if (!trimmed) {
throw new Error('OpenAI API key is required')
}
ensureOrcaDir()
if (safeStorage.isEncryptionAvailable()) {
writeFileSync(getOpenAiKeyPath(), safeStorage.encryptString(trimmed), { mode: 0o600 })
cachedOpenAiSpeechApiKey = trimmed
return
}
console.warn(
'[speech] safeStorage encryption unavailable — storing OpenAI speech key in plaintext'
)
writeFileSync(getOpenAiKeyPath(), trimmed, { encoding: 'utf8', mode: 0o600 })
cachedOpenAiSpeechApiKey = trimmed
}
export function readOpenAiSpeechApiKey(): string {
if (cachedOpenAiSpeechApiKey !== null) {
return cachedOpenAiSpeechApiKey
}
const keyPath = getOpenAiKeyPath()
if (!existsSync(keyPath)) {
throw new Error('OpenAI API key is not configured')
}
try {
const raw = readFileSync(keyPath)
const legacyJson = readLegacyJsonStoredOpenAiKey()
if (legacyJson) {
cachedOpenAiSpeechApiKey = safeStorage.decryptString(
Buffer.from(legacyJson.encryptedKeyBase64, 'base64')
)
return cachedOpenAiSpeechApiKey
}
cachedOpenAiSpeechApiKey = safeStorage.isEncryptionAvailable()
? safeStorage.decryptString(raw)
: raw.toString('utf8')
return cachedOpenAiSpeechApiKey
} catch {
throw new Error('OpenAI API key could not be decrypted')
}
}
export function clearOpenAiSpeechApiKey(): void {
cachedOpenAiSpeechApiKey = null
rmSync(getOpenAiKeyPath(), { force: true })
}
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'
import { sanitizeOpenAiTranscriptionErrorMessage } from './openai-transcription-client'
describe('sanitizeOpenAiTranscriptionErrorMessage', () => {
it('does not expose the invalid OpenAI API key echoed by the provider', () => {
expect(
sanitizeOpenAiTranscriptionErrorMessage(
'Incorrect API key provided: fsdfdsfsdf. You can find your API key at https://platform.openai.com/account/api-keys.'
)
).toBe('Incorrect OpenAI API key provided.')
})
it('redacts API keys and bearer tokens from other provider errors', () => {
expect(
sanitizeOpenAiTranscriptionErrorMessage(
'Request failed for sk-testSecret123 with Authorization: Bearer token-value_123'
)
).toBe('Request failed for [redacted] with Authorization: Bearer [redacted]')
})
})
@@ -0,0 +1,137 @@
import { resampleToRate } from './stt-audio-resample'
export const OPENAI_TRANSCRIPTION_MODEL_BY_ID: Record<string, string> = {
'openai-gpt-4o-mini-transcribe': 'gpt-4o-mini-transcribe',
'openai-gpt-4o-transcribe': 'gpt-4o-transcribe'
}
const OPENAI_TRANSCRIPTION_URL = 'https://api.openai.com/v1/audio/transcriptions'
const CLOUD_TRANSCRIPTION_SAMPLE_RATE = 16000
const MAX_CLOUD_AUDIO_SECONDS = 10 * 60
type OpenAiTranscriptionResponse = {
text?: unknown
error?: {
message?: unknown
}
}
export function sanitizeOpenAiTranscriptionErrorMessage(message: string): string {
if (/incorrect api key provided:/i.test(message)) {
return 'Incorrect OpenAI API key provided.'
}
const sanitized = message
.replace(/\bsk-[A-Za-z0-9_-]+/g, '[redacted]')
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]')
.trim()
return sanitized || 'OpenAI transcription request failed'
}
function encodePcm16Wav(samples: Float32Array, sampleRate: number): Buffer {
const dataBytes = samples.length * 2
const buffer = Buffer.alloc(44 + dataBytes)
buffer.write('RIFF', 0)
buffer.writeUInt32LE(36 + dataBytes, 4)
buffer.write('WAVE', 8)
buffer.write('fmt ', 12)
buffer.writeUInt32LE(16, 16)
buffer.writeUInt16LE(1, 20)
buffer.writeUInt16LE(1, 22)
buffer.writeUInt32LE(sampleRate, 24)
buffer.writeUInt32LE(sampleRate * 2, 28)
buffer.writeUInt16LE(2, 32)
buffer.writeUInt16LE(16, 34)
buffer.write('data', 36)
buffer.writeUInt32LE(dataBytes, 40)
for (let i = 0; i < samples.length; i += 1) {
const clamped = Math.max(-1, Math.min(1, samples[i]))
const value = clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff
buffer.writeInt16LE(Math.round(value), 44 + i * 2)
}
return buffer
}
function combineChunks(chunks: Float32Array[]): Float32Array {
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0)
const combined = new Float32Array(totalLength)
let offset = 0
for (const chunk of chunks) {
combined.set(chunk, offset)
offset += chunk.length
}
return combined
}
function parseOpenAiTranscriptionResponse(data: OpenAiTranscriptionResponse): string {
if (typeof data.text === 'string') {
return data.text.trim()
}
if (typeof data.error?.message === 'string') {
throw new Error(sanitizeOpenAiTranscriptionErrorMessage(data.error.message))
}
throw new Error('OpenAI transcription response did not include text')
}
export class OpenAiTranscriptionSession {
private chunks: Float32Array[] = []
private audioSeconds = 0
constructor(
private readonly modelId: string,
private readonly readApiKey: () => string
) {}
feedAudio(samples: Float32Array, sampleRate: number): void {
const normalized = resampleToRate(samples, sampleRate, CLOUD_TRANSCRIPTION_SAMPLE_RATE)
this.audioSeconds += normalized.length / CLOUD_TRANSCRIPTION_SAMPLE_RATE
if (this.audioSeconds > MAX_CLOUD_AUDIO_SECONDS) {
throw new Error('Cloud transcription is limited to 10 minutes per dictation')
}
this.chunks.push(new Float32Array(normalized))
}
async finish(): Promise<string> {
if (this.chunks.length === 0) {
return ''
}
const apiModel = OPENAI_TRANSCRIPTION_MODEL_BY_ID[this.modelId]
if (!apiModel) {
throw new Error(`Unknown OpenAI transcription model: ${this.modelId}`)
}
const audio = combineChunks(this.chunks)
this.chunks = []
const wav = encodePcm16Wav(audio, CLOUD_TRANSCRIPTION_SAMPLE_RATE)
const form = new FormData()
form.append('model', apiModel)
form.append('response_format', 'json')
// Why: OpenAI's transcription endpoint expects a multipart file object;
// a named WAV blob avoids filesystem temp files and works in packaged apps.
form.append('file', new Blob([new Uint8Array(wav)], { type: 'audio/wav' }), 'dictation.wav')
const response = await fetch(OPENAI_TRANSCRIPTION_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.readApiKey()}`
},
body: form
})
const data = (await response.json().catch(() => ({}))) as OpenAiTranscriptionResponse
if (!response.ok) {
const message =
typeof data.error?.message === 'string'
? sanitizeOpenAiTranscriptionErrorMessage(data.error.message)
: response.statusText
throw new Error(`OpenAI transcription failed: ${message}`)
}
return parseOpenAiTranscriptionResponse(data)
}
}
+101 -8
View File
@@ -1,6 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { MockWorker, getCreatedWorkerCount, getLastWorker, resetWorkers } = vi.hoisted(() => {
const {
MockOpenAiTranscriptionSession,
MockWorker,
getCloudSessions,
getCreatedWorkerCount,
getLastWorker,
readOpenAiSpeechApiKeyMock,
resetCloudSessions,
resetWorkers
} = vi.hoisted(() => {
class HoistedMockWorker extends EventTarget {
static created = 0
static instances: HoistedMockWorker[] = []
@@ -64,10 +73,36 @@ const { MockWorker, getCreatedWorkerCount, getLastWorker, resetWorkers } = vi.ho
}
}
class HoistedMockOpenAiTranscriptionSession {
static instances: HoistedMockOpenAiTranscriptionSession[] = []
feedCalls: { samples: Float32Array; sampleRate: number }[] = []
constructor(
readonly modelId: string,
readonly readApiKey: () => string
) {
HoistedMockOpenAiTranscriptionSession.instances.push(this)
}
feedAudio(samples: Float32Array, sampleRate: number): void {
this.feedCalls.push({ samples, sampleRate })
}
finish(): Promise<string> {
return Promise.resolve(`${this.modelId}:${this.readApiKey()}`)
}
}
return {
MockOpenAiTranscriptionSession: HoistedMockOpenAiTranscriptionSession,
MockWorker: HoistedMockWorker,
getCloudSessions: () => HoistedMockOpenAiTranscriptionSession.instances,
getCreatedWorkerCount: () => HoistedMockWorker.created,
getLastWorker: () => HoistedMockWorker.instances.at(-1),
readOpenAiSpeechApiKeyMock: vi.fn(() => 'test-openai-key'),
resetCloudSessions: () => {
HoistedMockOpenAiTranscriptionSession.instances = []
},
resetWorkers: () => {
HoistedMockWorker.created = 0
HoistedMockWorker.instances = []
@@ -89,20 +124,40 @@ vi.mock('worker_threads', () => ({
}))
vi.mock('./model-catalog', () => ({
getCatalogModel: () => ({
id: 'model-a',
type: 'transducer',
streaming: true,
sampleRate: 16000,
files: ['encoder.onnx', 'decoder.onnx', 'joiner.onnx', 'tokens.txt']
})
getCatalogModel: (id: string) =>
id === 'openai-model'
? {
id,
type: 'openai',
provider: 'openai',
streaming: false,
sampleRate: 16000
}
: {
id: 'model-a',
type: 'transducer',
provider: 'local',
streaming: true,
sampleRate: 16000,
files: ['encoder.onnx', 'decoder.onnx', 'joiner.onnx', 'tokens.txt']
}
}))
vi.mock('./openai-api-key-store', () => ({
readOpenAiSpeechApiKey: readOpenAiSpeechApiKeyMock
}))
vi.mock('./openai-transcription-client', () => ({
OpenAiTranscriptionSession: MockOpenAiTranscriptionSession
}))
import { IDLE_WORKER_TEARDOWN_MS, START_DICTATION_TIMEOUT_MS, SttService } from './stt-service'
describe('SttService', () => {
beforeEach(() => {
resetCloudSessions()
resetWorkers()
readOpenAiSpeechApiKeyMock.mockClear()
})
it('reuses an idle warm worker for a second dictation with the same owner', async () => {
@@ -184,6 +239,44 @@ describe('SttService', () => {
expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0)
})
it('uses the OpenAI transcription session without creating a worker', async () => {
const sink = vi.fn()
const service = new SttService({
getModelState: vi.fn().mockResolvedValue({ id: 'openai-model', status: 'ready' }),
getModelDir: vi.fn().mockReturnValue('/tmp/model-a')
} as never)
await service.startDictation('openai-model', sink, undefined, 'desktop')
service.feedAudio(new Float32Array([0.25, -0.25]), 48000, 'desktop')
await service.stopDictation('desktop')
expect(getCreatedWorkerCount()).toBe(0)
expect(getCloudSessions()).toHaveLength(1)
expect(getCloudSessions()[0].feedCalls).toHaveLength(1)
expect(sink).toHaveBeenCalledWith({ type: 'ready' })
expect(sink).toHaveBeenCalledWith({
type: 'final',
text: 'openai-model:test-openai-key'
})
expect(sink).toHaveBeenCalledWith({ type: 'stopped' })
})
it('reads the OpenAI key only when finishing cloud dictation', async () => {
const service = new SttService({
getModelState: vi.fn().mockResolvedValue({ id: 'openai-model', status: 'ready' }),
getModelDir: vi.fn().mockReturnValue('/tmp/model-a')
} as never)
await service.startDictation('openai-model', vi.fn(), undefined, 'desktop')
service.feedAudio(new Float32Array([0.25]), 16000, 'desktop')
expect(readOpenAiSpeechApiKeyMock).not.toHaveBeenCalled()
await service.stopDictation('desktop')
expect(readOpenAiSpeechApiKeyMock).toHaveBeenCalledOnce()
})
it('keeps startup cancellation tombstoned after the worker has been created', async () => {
const service = new SttService({
getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }),
+65 -9
View File
@@ -6,6 +6,8 @@ import { join } from 'path'
import { app } from 'electron'
import { getCatalogModel } from './model-catalog'
import type { ModelManager } from './model-manager'
import { OpenAiTranscriptionSession } from './openai-transcription-client'
import { readOpenAiSpeechApiKey } from './openai-api-key-store'
export const START_DICTATION_TIMEOUT_MS = 60_000
const STOP_DICTATION_TIMEOUT_MS = 60_000
@@ -22,6 +24,7 @@ export type SttEventSink = (event: SttEvent) => void
export class SttService {
private worker: Worker | null = null
private cloudSession: OpenAiTranscriptionSession | null = null
private modelManager: ModelManager
private activeModelId: string | null = null
private activeHotwordsFilePath: string | undefined
@@ -51,7 +54,7 @@ export class SttService {
}
return
}
if (this.worker && this.activeOwner && this.activeOwner !== owner) {
if ((this.worker || this.cloudSession) && this.activeOwner && this.activeOwner !== owner) {
throw new Error('dictation_already_active')
}
this.starting = true
@@ -78,6 +81,34 @@ export class SttService {
hotwordsFilePath?: string,
owner = 'desktop'
): Promise<void> {
const manifest = getCatalogModel(modelId)
if (!manifest) {
throw new Error(`Unknown model: ${modelId}`)
}
if (manifest.provider === 'openai') {
if (this.worker) {
await this.stopDictation(owner, { cancelStarting: false })
await this.teardownIdleWorker()
}
const modelState = await this.modelManager.getModelState(modelId)
if (modelState.status !== 'ready') {
throw new Error(`Model not ready: ${modelState.status}`)
}
this.cloudSession = new OpenAiTranscriptionSession(modelId, readOpenAiSpeechApiKey)
this.activeModelId = modelId
this.activeHotwordsFilePath = undefined
this.eventSink = sink
sink({ type: 'ready' })
return
}
if (this.cloudSession) {
await this.stopDictation(owner, { cancelStarting: false })
}
if (
this.worker &&
this.activeModelId === modelId &&
@@ -93,11 +124,6 @@ export class SttService {
await this.teardownIdleWorker()
}
const manifest = getCatalogModel(modelId)
if (!manifest) {
throw new Error(`Unknown model: ${modelId}`)
}
const modelState = await this.modelManager.getModelState(modelId)
if (modelState.status !== 'ready') {
throw new Error(`Model not ready: ${modelState.status}`)
@@ -207,7 +233,7 @@ export class SttService {
modelType: manifest.type,
streaming: manifest.streaming,
sampleRate: manifest.sampleRate,
files: manifest.files,
files: manifest.files ?? [],
hotwordsFilePath,
modelingUnit: manifest.modelingUnit
})
@@ -237,6 +263,10 @@ export class SttService {
if (currentOwner !== owner) {
throw new Error('dictation_owner_mismatch')
}
if (this.cloudSession) {
this.cloudSession.feedAudio(samples, sampleRate)
return
}
this.worker?.postMessage({ type: 'feed', samples, sampleRate }, [samples.buffer as ArrayBuffer])
}
@@ -247,7 +277,7 @@ export class SttService {
if (options.cancelStarting !== false && this.startingOwner === owner) {
this.canceledOwners.add(owner)
}
if (!this.worker) {
if (!this.worker && !this.cloudSession) {
return
}
const currentOwner = this.activeOwner ?? this.startingOwner
@@ -255,7 +285,33 @@ export class SttService {
throw new Error('dictation_owner_mismatch')
}
if (this.cloudSession) {
const session = this.cloudSession
this.cloudSession = null
try {
const text = await session.finish()
if (text) {
this.eventSink?.({ type: 'final', text })
}
} catch (error) {
this.eventSink?.({
type: 'error',
error: error instanceof Error ? error.message : String(error)
})
} finally {
this.eventSink?.({ type: 'stopped' })
this.activeModelId = null
this.activeHotwordsFilePath = undefined
this.activeOwner = null
this.eventSink = null
}
return
}
const worker = this.worker
if (!worker) {
return
}
worker.postMessage({ type: 'stop' })
let forcedTeardown = false
@@ -319,7 +375,7 @@ export class SttService {
}
isActive(): boolean {
return this.worker !== null
return this.worker !== null || this.cloudSession !== null
}
getActiveModelId(): string | null {