Allow deleting downloaded speech models on desktop and mobile (#5794)

* Allow deleting downloaded speech models on desktop and mobile

Implement safe deletion of local speech models across desktop and
mobile platforms.

- Add a shared helper to coordinate STT service teardown, file deletion,
  and voice settings cleanup.
- Prevent deleting speech models that are currently in use or starting.
- Update desktop and mobile settings UIs to expose the delete action.

* Track multiple pending model deletions and update action disabling

- Replace the single pending delete ID string state with a Set of IDs on desktop settings to track multiple concurrently deleting models.
- Switch the desktop delete action to use the standard themed Button component.
- Disable all row interactions on the mobile voice model list when any model action is busy.
- Add unit test coverage verifying that individual row delete button disabled states behave correctly.
This commit is contained in:
Jinjing
2026-06-19 12:31:11 -07:00
committed by GitHub
parent 5dbff5d8ea
commit bc2f5145da
22 changed files with 836 additions and 77 deletions
+31 -2
View File
@@ -1,7 +1,7 @@
import { createHash } from 'crypto'
import { mkdtempSync, rmSync, writeFileSync } from 'fs'
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { dirname, join } from 'path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SPEECH_MODEL_CATALOG } from './model-catalog'
import { ModelManager } from './model-manager'
@@ -122,6 +122,35 @@ describe('ModelManager', () => {
}
})
it('deletes a ready local model and reports it as not downloaded', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-'))
try {
const manifest = SPEECH_MODEL_CATALOG.find((model) => model.provider === 'local')
expect(manifest?.files).toBeDefined()
const manager = new ModelManager(dir)
const modelDir = manager.getModelDir(manifest!.id)
for (const file of manifest!.files ?? []) {
const path = join(modelDir, file)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, 'model file')
}
await expect(manager.getModelState(manifest!.id)).resolves.toEqual({
id: manifest!.id,
status: 'ready'
})
await manager.deleteModel(manifest!.id)
expect(existsSync(modelDir)).toBe(false)
await expect(manager.getModelState(manifest!.id)).resolves.toEqual({
id: manifest!.id,
status: 'not-downloaded'
})
} 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 {
@@ -0,0 +1,134 @@
import { describe, expect, it, vi } from 'vitest'
import { getDefaultVoiceSettings } from '../../shared/constants'
import type { VoiceSettings } from '../../shared/speech-types'
import type { GlobalSettings } from '../../shared/types'
import { SPEECH_MODEL_CATALOG } from './model-catalog'
import { deleteLocalSpeechModel } from './speech-model-deletion'
const localModel = SPEECH_MODEL_CATALOG.find((model) => model.provider === 'local')
const cloudModel = SPEECH_MODEL_CATALOG.find((model) => model.provider === 'openai')
function makeStore(initialVoice: VoiceSettings) {
let voice = initialVoice
const updateSettings = vi.fn((updates: Partial<GlobalSettings>) => {
if (updates.voice) {
voice = updates.voice
}
return { voice } as GlobalSettings
})
return {
getSettings: vi.fn(() => ({ voice }) as GlobalSettings),
updateSettings
}
}
describe('deleteLocalSpeechModel', () => {
it('clears the selected local model after deletion succeeds', async () => {
expect(localModel).toBeDefined()
const calls: string[] = []
const voice = { ...getDefaultVoiceSettings(), enabled: true, sttModel: localModel!.id }
const store = makeStore(voice)
const modelManager = {
deleteModel: vi.fn(async () => {
calls.push('delete')
})
}
const sttService = {
prepareModelForDeletion: vi.fn(async () => {
calls.push('prepare')
})
}
await deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId: localModel!.id
})
expect(calls).toEqual(['prepare', 'delete'])
expect(store.updateSettings).toHaveBeenCalledWith(
{
voice: {
...voice,
sttModel: ''
}
},
{ notifyListeners: true }
)
})
it('does not clear selection when another client selected a newer model', async () => {
expect(localModel).toBeDefined()
const voice = { ...getDefaultVoiceSettings(), enabled: true, sttModel: localModel!.id }
const store = makeStore(voice)
const modelManager = {
deleteModel: vi.fn(async () => {
store.updateSettings({ voice: { ...voice, sttModel: 'newer-model' } })
})
}
const sttService = { prepareModelForDeletion: vi.fn(async () => {}) }
await deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId: localModel!.id
})
expect(store.updateSettings).toHaveBeenCalledTimes(1)
expect(store.updateSettings).toHaveBeenCalledWith({
voice: { ...voice, sttModel: 'newer-model' }
})
})
it('leaves settings untouched when deletion fails', async () => {
expect(localModel).toBeDefined()
const store = makeStore({ ...getDefaultVoiceSettings(), sttModel: localModel!.id })
const modelManager = {
deleteModel: vi.fn(async () => {
throw new Error('permission denied')
})
}
const sttService = { prepareModelForDeletion: vi.fn(async () => {}) }
await expect(
deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId: localModel!.id
})
).rejects.toThrow('permission denied')
expect(store.updateSettings).not.toHaveBeenCalled()
})
it('rejects unknown and cloud models before preparing storage deletion', async () => {
expect(cloudModel).toBeDefined()
const store = makeStore(getDefaultVoiceSettings())
const modelManager = { deleteModel: vi.fn(async () => {}) }
const sttService = { prepareModelForDeletion: vi.fn(async () => {}) }
await expect(
deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId: 'missing-model'
})
).rejects.toThrow('voice_model_unknown')
await expect(
deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId: cloudModel!.id
})
).rejects.toThrow('voice_model_not_deletable')
expect(sttService.prepareModelForDeletion).not.toHaveBeenCalled()
expect(modelManager.deleteModel).not.toHaveBeenCalled()
expect(store.updateSettings).not.toHaveBeenCalled()
})
})
+79
View File
@@ -0,0 +1,79 @@
import { getDefaultVoiceSettings } from '../../shared/constants'
import type { VoiceSettings } from '../../shared/speech-types'
import { getCatalogModel, isLocalSpeechModel } from './model-catalog'
import type { ModelManager } from './model-manager'
import type { SttService } from './stt-service'
export type SpeechModelDeletionErrorCode =
| 'voice_model_unknown'
| 'voice_model_not_deletable'
| 'voice_model_in_use'
export class SpeechModelDeletionError extends Error {
constructor(readonly code: SpeechModelDeletionErrorCode) {
super(code)
this.name = 'SpeechModelDeletionError'
}
}
type SpeechModelDeletionStore = {
getSettings: () => {
voice?: VoiceSettings
}
updateSettings: (
updates: {
voice: VoiceSettings
},
options?: { notifyListeners?: boolean; originWebContentsId?: number }
) => unknown
}
type DeleteLocalSpeechModelArgs = {
store: SpeechModelDeletionStore
modelManager: Pick<ModelManager, 'deleteModel'>
sttService: Pick<SttService, 'prepareModelForDeletion'>
modelId: string
}
export function getSpeechModelDeletionErrorCode(
error: unknown
): SpeechModelDeletionErrorCode | null {
if (error instanceof SpeechModelDeletionError) {
return error.code
}
if (error instanceof Error && error.message === 'voice_model_in_use') {
return 'voice_model_in_use'
}
return null
}
export async function deleteLocalSpeechModel({
store,
modelManager,
sttService,
modelId
}: DeleteLocalSpeechModelArgs): Promise<void> {
const manifest = getCatalogModel(modelId)
if (!manifest) {
throw new SpeechModelDeletionError('voice_model_unknown')
}
if (!isLocalSpeechModel(manifest)) {
throw new SpeechModelDeletionError('voice_model_not_deletable')
}
await sttService.prepareModelForDeletion(modelId)
await modelManager.deleteModel(modelId)
const currentVoice = store.getSettings().voice ?? getDefaultVoiceSettings()
if (currentVoice.sttModel === modelId) {
store.updateSettings(
{
voice: {
...currentVoice,
sttModel: ''
}
},
{ notifyListeners: true }
)
}
}
+64
View File
@@ -239,6 +239,70 @@ describe('SttService', () => {
expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0)
})
it('rejects deletion prep while the target model is starting', async () => {
let resolveModelState: (state: { id: string; status: string }) => void = () => {}
const modelStatePromise = new Promise<{ id: string; status: string }>((resolve) => {
resolveModelState = resolve
})
const service = new SttService({
getModelState: vi.fn(() => modelStatePromise),
getModelDir: vi.fn().mockReturnValue('/tmp/model-a')
} as never)
const startPromise = service.startDictation('model-a', vi.fn(), undefined, 'desktop')
await Promise.resolve()
await expect(service.prepareModelForDeletion('model-a')).rejects.toThrow('voice_model_in_use')
resolveModelState({ id: 'model-a', status: 'ready' })
await startPromise
await service.stopDictation('desktop')
})
it('tears down an idle warm worker before deleting the target model', async () => {
const service = new SttService({
getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }),
getModelDir: vi.fn().mockReturnValue('/tmp/model-a')
} as never)
await service.startDictation('model-a', vi.fn(), undefined, 'desktop')
const worker = getLastWorker()
expect(worker).toBeDefined()
await service.stopDictation('desktop')
await service.prepareModelForDeletion('model-a')
expect(worker!.messages.some((message) => message.type === 'teardown')).toBe(true)
expect(worker!.terminated).toBe(true)
expect(service.isActive()).toBe(false)
})
it('rejects deletion prep when a target warm worker cannot be torn down during another start', async () => {
let resolveModelState: (state: { id: string; status: string }) => void = () => {}
const secondModelState = new Promise<{ id: string; status: string }>((resolve) => {
resolveModelState = resolve
})
const getModelState = vi
.fn()
.mockResolvedValueOnce({ id: 'model-a', status: 'ready' })
.mockReturnValue(secondModelState)
const service = new SttService({
getModelState,
getModelDir: vi.fn().mockReturnValue('/tmp/model-a')
} as never)
await service.startDictation('model-a', vi.fn(), undefined, 'desktop')
await service.stopDictation('desktop')
const startOtherModel = service.startDictation('model-b', vi.fn(), undefined, 'desktop')
await Promise.resolve()
await expect(service.prepareModelForDeletion('model-a')).rejects.toThrow('voice_model_in_use')
resolveModelState({ id: 'model-b', status: 'ready' })
await startOtherModel
await service.stopDictation('desktop')
})
it('uses the OpenAI transcription session without creating a worker', async () => {
const sink = vi.fn()
const service = new SttService({
+25 -2
View File
@@ -30,6 +30,7 @@ export class SttService {
private activeHotwordsFilePath: string | undefined
private activeOwner: string | null = null
private startingOwner: string | null = null
private startingModelId: string | null = null
private starting = false
private canceledOwners = new Set<string>()
private eventSink: SttEventSink | null = null
@@ -59,6 +60,7 @@ export class SttService {
}
this.starting = true
this.startingOwner = owner
this.startingModelId = modelId
this.clearIdleTeardownTimer()
try {
@@ -71,6 +73,7 @@ export class SttService {
} finally {
this.starting = false
this.startingOwner = null
this.startingModelId = null
this.canceledOwners.delete(owner)
}
}
@@ -382,6 +385,18 @@ export class SttService {
return this.activeModelId
}
async prepareModelForDeletion(modelId: string): Promise<void> {
if (this.startingModelId === modelId || (this.activeOwner && this.activeModelId === modelId)) {
throw new Error('voice_model_in_use')
}
if (this.worker && this.activeModelId === modelId) {
await this.teardownIdleWorker({ ignoreTerminateErrors: false })
if (this.worker && this.activeModelId === modelId) {
throw new Error('voice_model_in_use')
}
}
}
private getWorkerPath(): string {
if (app.isPackaged) {
return join(process.resourcesPath, 'app.asar', 'out', 'main', 'stt-worker.js')
@@ -407,16 +422,24 @@ export class SttService {
this.idleTeardownTimer.unref?.()
}
private async teardownIdleWorker(): Promise<void> {
private async teardownIdleWorker(
options: { ignoreTerminateErrors?: boolean } = { ignoreTerminateErrors: true }
): Promise<void> {
this.clearIdleTeardownTimer()
if (!this.worker || this.activeOwner || this.startingOwner) {
return
}
const worker = this.worker
worker.postMessage({ type: 'teardown' })
try {
await worker.terminate()
} catch (error) {
if (!options.ignoreTerminateErrors) {
throw error
}
}
this.cleanupActiveWorkerLifecycleListeners()
worker.removeAllListeners()
await worker.terminate().catch(() => undefined)
if (this.worker === worker) {
this.worker = null
this.activeModelId = null