fix(speech): resume interrupted voice model downloads and surface real errors (#8775)

* fix(speech): resume interrupted voice model downloads and surface real errors

Voice model downloads that died late in the transfer (flaky networks,
scanning proxies) failed at the UI's 90% progress cap and restarted from
byte zero on every retry, so affected users could never complete any
model download (#8620 / STA-1775).

- Retry transient download failures (net::ERR_* transfer cuts, resets,
  timeouts, HTTP 5xx/429) with an HTTP Range resume from the bytes
  already on disk, restarting from the canonical URL each attempt since
  signed CDN redirect URLs expire; bounded backoff, gives up after
  repeated zero-progress attempts with a diagnosable error.
- Correct catalog sizeBytes to exact upstream asset sizes (parakeet
  v2/v3 are 482/487 MB, not 170/180; paraformer is 1,047 MB, not 115) —
  also the progress denominator when content-length is missing.
- Show the underlying failure cause in the download-error toast and log
  it in main; it was previously invisible everywhere.

All 7 pinned catalog SHA-256 hashes verified against current upstream
assets. Live-verified end to end: a transfer killed mid-body resumes
with a 206 and completes through checksum, extraction, and validation.

Fixes #8620

* fix(speech): harden resumed model downloads

* fix(speech): validate resumed download completion

* fix(speech): keep segmented download resumes progressing

* fix(speech): don't abandon a download that keeps making progress

The retry loop gave up after 8 total failures regardless of progress, so
a large model (e.g. the ~1GB Paraformer) over a network that resets every
few hundred MB was abandoned mid-download even though every attempt was
resuming and advancing — the exact 'stuck then fails' symptom, just later.

Replace the all-time failure budget and the separate advancing-segment
cap with a single rule: give up only on a genuine stall (repeated
attempts with no forward progress) or an absolute request ceiling that
bounds a pathological tiny-segment server. Any download that keeps
advancing now runs to completion.

Verified live under Electron 43: a transfer reset mid-stream on every
attempt but advancing each time previously gave up at 67% after 8
attempts; it now completes. All prior resume/cancel/timeout scenarios
still pass.
This commit is contained in:
Brennan Benson
2026-07-14 17:49:13 -07:00
committed by GitHub
parent d44696a74c
commit 33a8df93fc
4 changed files with 1020 additions and 32 deletions
+9 -7
View File
@@ -1,5 +1,7 @@
import type { SpeechModelManifest } from '../../shared/speech-types'
// Why: sizeBytes must be the exact upstream asset size — it is the UI size
// label and the download-progress denominator when content-length is missing.
export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
{
id: 'parakeet-tdt-0.6b-v3-int8',
@@ -9,7 +11,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'transducer',
provider: 'local',
language: 'multilingual',
sizeBytes: 180_000_000,
sizeBytes: 487_170_055,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2',
archiveSha256: '5793d0fd397c5778d2cf2126994d58e9d56b1be7c04d13c7a15bb1b4eafb16bf',
@@ -28,7 +30,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'transducer',
provider: 'local',
language: 'en',
sizeBytes: 170_000_000,
sizeBytes: 482_468_385,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8.tar.bz2',
archiveSha256: '157c157bc51155e03e37d2466522a3a737dd9c72bb25f36eb18912964161e1ad',
@@ -45,7 +47,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'transducer',
provider: 'local',
language: 'zh-en',
sizeBytes: 130_000_000,
sizeBytes: 511_274_346,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-streaming-zipformer-bilingual-zh-en-2023-02-20.tar.bz2',
archiveSha256: '27ffbd9ee24ad186d99acc2f6354d7992b27bcab490812510665fa8f9389c5f8',
@@ -68,7 +70,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'paraformer',
provider: 'local',
language: 'zh-en',
sizeBytes: 115_000_000,
sizeBytes: 1_047_319_737,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-streaming-paraformer-bilingual-zh-en.tar.bz2',
archiveSha256: '5462a1fce42693deae572af1e8c4687124b12aa85fe61ff4d3168bb5280e205f',
@@ -84,7 +86,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'transducer',
provider: 'local',
language: 'en',
sizeBytes: 128_000_000,
sizeBytes: 127_887_156,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-streaming-zipformer-en-20M-2023-02-17.tar.bz2',
archiveSha256: '9c559283e8498d3fe95913c79ca1cb454bb26281ac2b102b41306c7d752765d9',
@@ -106,7 +108,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'transducer',
provider: 'local',
language: 'zh',
sizeBytes: 74_000_000,
sizeBytes: 74_004_050,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-streaming-zipformer-zh-14M-2023-02-23.tar.bz2',
archiveSha256: '2cbd71b640d9c37d3784f29367333a4577b0398b62e9deeed418170b081cba8b',
@@ -128,7 +130,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [
type: 'whisper',
provider: 'local',
language: 'multilingual',
sizeBytes: 116_000_000,
sizeBytes: 116_204_861,
downloadUrl:
'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-whisper-tiny.tar.bz2',
archiveSha256: 'c46116994e539aa165266d96b325252728429c12535eb9d8b6a2b10f129e66b1',
@@ -0,0 +1,671 @@
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ModelManager } from './model-manager'
const { netRequestMock } = vi.hoisted(() => ({
netRequestMock: vi.fn()
}))
vi.mock('electron', () => ({
app: {
getPath: () => '/tmp/orca-speech-models-test'
},
net: {
request: netRequestMock
}
}))
type ModelManagerInternals = {
downloadArchiveWithRetry: (
url: string,
archivePath: string,
expectedSize: number,
modelId: string,
isAborted: () => boolean,
signal: AbortSignal
) => Promise<void>
downloadFile: (
url: string,
archivePath: string,
expectedSize: number,
modelId: string,
isAborted: () => boolean,
signal?: AbortSignal,
redirectCount?: number,
resumeOffset?: number
) => Promise<void>
}
type ScriptedResponse = {
statusCode: number
headers?: Record<string, string>
chunks?: Buffer[]
failWith?: string
}
type ScriptedResponseFactory = (sentHeaders: Record<string, string>) => ScriptedResponse
// Emulates Electron's ClientRequest/IncomingMessage closely enough for the
// download pipeline: a real Readable body so stream.pipeline semantics
// (including mid-body destroy) match production behavior.
function scriptRequest(factory: ScriptedResponseFactory): {
sentHeaders: Record<string, string>
abortMock: ReturnType<typeof vi.fn>
} {
const sentHeaders: Record<string, string> = {}
const listeners = new Map<string, Set<(...args: unknown[]) => void>>()
const addListener = (event: string, cb: (...args: unknown[]) => void): void => {
const set = listeners.get(event) ?? new Set()
set.add(cb)
listeners.set(event, set)
}
const abortMock = vi.fn(() => request)
const request = {
setHeader: vi.fn((name: string, value: string) => {
sentHeaders[name.toLowerCase()] = value
}),
on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
addListener(event, cb)
return request
}),
off: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
listeners.get(event)?.delete(cb)
return request
}),
abort: abortMock,
end: vi.fn(() => {
queueMicrotask(() => {
const spec = factory(sentHeaders)
const response = Object.assign(new Readable({ read() {} }), {
statusCode: spec.statusCode,
headers: spec.headers ?? {}
})
for (const cb of listeners.get('response') ?? []) {
cb(response)
}
setTimeout(() => {
for (const chunk of spec.chunks ?? []) {
response.push(chunk)
}
// Why: fail on a later tick so pushed chunks flush to the file
// stream first, mirroring a transfer that dies mid-body.
setTimeout(() => {
if (spec.failWith) {
response.destroy(new Error(spec.failWith))
} else {
response.push(null)
}
}, 20)
}, 20)
})
return request
})
}
netRequestMock.mockImplementationOnce(() => request)
return { sentHeaders, abortMock }
}
const PAYLOAD = Buffer.from('0123456789abcdefghij')
describe('ModelManager download resume', () => {
beforeEach(() => {
netRequestMock.mockReset()
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('resumes an interrupted download with a Range request and assembles the full file', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest(() => ({
statusCode: 200,
headers: { 'content-length': String(PAYLOAD.length) },
chunks: [PAYLOAD.subarray(0, 10)],
failWith: 'net::ERR_CONTENT_LENGTH_MISMATCH'
}))
const second = scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=10-')
return {
statusCode: 206,
headers: {
'content-length': String(PAYLOAD.length - 10),
'content-range': `bytes 10-${PAYLOAD.length - 1}/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(10)]
}
})
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(2)
expect(second.sentHeaders.range).toBe('bytes=10-')
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('uses a complete archive after a late transport failure without requesting past EOF', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest(() => ({
statusCode: 200,
headers: { 'content-length': String(PAYLOAD.length) },
chunks: [PAYLOAD],
failWith: 'net::ERR_CONNECTION_RESET'
}))
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(1)
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('requests the remaining bytes when a clean range response ends before the archive total', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const first = scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=10-')
return {
statusCode: 206,
headers: {
'content-length': '5',
'content-range': `bytes 10-14/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(10, 15)]
}
})
const second = scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=15-')
return {
statusCode: 206,
headers: {
'content-length': '5',
'content-range': `bytes 15-19/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(15)]
}
})
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
writeFileSync(archivePath, PAYLOAD.subarray(0, 10))
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(2)
expect(first.sentHeaders.range).toBe('bytes=10-')
expect(second.sentHeaders.range).toBe('bytes=15-')
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('continues through more than eight advancing range segments', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
for (let offset = 1; offset <= 9; offset += 1) {
scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe(`bytes=${offset}-`)
return {
statusCode: 206,
headers: {
'content-length': '1',
'content-range': `bytes ${offset}-${offset}/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(offset, offset + 1)]
}
})
}
scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=10-')
return {
statusCode: 206,
headers: {
'content-length': '10',
'content-range': `bytes 10-19/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(10)]
}
})
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
writeFileSync(archivePath, PAYLOAD.subarray(0, 1))
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(10)
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('bounds a server that advances by pathologically tiny segments forever', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
let bytesWritten = 0
// Advances one byte per request against a total larger than the request
// ceiling, so it makes forward progress forever without ever completing.
const downloadFileMock = vi.spyOn(manager, 'downloadFile').mockImplementation(() => {
bytesWritten += 1
writeFileSync(archivePath, Buffer.alloc(bytesWritten))
return Promise.resolve()
})
await expect(
manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
1_000_000,
'm',
() => false,
new AbortController().signal
)
).rejects.toThrow(/too many download requests/)
// The absolute request ceiling (MAX_TOTAL_DOWNLOAD_REQUESTS) bounds it.
expect(downloadFileMock).toHaveBeenCalledTimes(4_096)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('keeps resuming a download that advances across many mid-stream drops', async () => {
vi.useFakeTimers()
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
// Every attempt delivers a small slice then drops mid-stream — the
// classic "dies partway, resumes" pattern. Because each attempt makes
// forward progress, the download must complete no matter how many drops
// it takes (regression guard: a fixed failure budget used to abandon a
// still-advancing large download around attempt 8).
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
const SLICE = 2
let delivered = 0
const downloadFileMock = vi.spyOn(manager, 'downloadFile').mockImplementation(() => {
delivered = Math.min(delivered + SLICE, PAYLOAD.length)
writeFileSync(archivePath, PAYLOAD.subarray(0, delivered))
return Promise.reject(new Error('net::ERR_CONNECTION_RESET'))
})
const download = manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
const outcome = download.then(
() => 'resolved',
(error: unknown) => (error instanceof Error ? error.message : String(error))
)
// Drive the per-attempt backoff (1s each, since progress resets the
// stall counter) well past the ten attempts this needs.
await vi.advanceTimersByTimeAsync(30_000)
await expect(outcome).resolves.toBe('resolved')
expect(downloadFileMock).toHaveBeenCalledTimes(PAYLOAD.length / SLICE)
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
vi.useRealTimers()
rmSync(dir, { recursive: true, force: true })
}
})
it('keeps the known archive total when Content-Range omits it', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=10-')
return {
statusCode: 206,
headers: {
'content-length': '5',
'content-range': 'bytes 10-14/*'
},
chunks: [PAYLOAD.subarray(10, 15)]
}
})
scriptRequest((sentHeaders) => {
expect(sentHeaders.range).toBe('bytes=15-')
return {
statusCode: 206,
headers: {
'content-length': '5',
'content-range': 'bytes 15-19/*'
},
chunks: [PAYLOAD.subarray(15)]
}
})
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
writeFileSync(archivePath, PAYLOAD.subarray(0, 10))
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(2)
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('rejects and discards a partial when Content-Range does not match the offset', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const mismatched = scriptRequest(() => ({
statusCode: 206,
headers: {
'content-length': '10',
'content-range': `bytes 0-9/${PAYLOAD.length}`
},
chunks: [PAYLOAD.subarray(0, 10)]
}))
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
writeFileSync(archivePath, PAYLOAD.subarray(0, 10))
const error = await manager
.downloadFile(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal,
0,
10
)
.catch((cause: unknown) => cause)
expect(error).toMatchObject({
message: 'Invalid Content-Range for resume at byte 10',
retryable: true
})
expect(existsSync(archivePath)).toBe(false)
expect(mismatched.abortMock).toHaveBeenCalledTimes(1)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('restarts from scratch when the server ignores the Range request', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest(() => ({
statusCode: 200,
headers: { 'content-length': String(PAYLOAD.length) },
chunks: [PAYLOAD.subarray(0, 10)],
failWith: 'net::ERR_CONNECTION_RESET'
}))
scriptRequest(() => ({
statusCode: 200,
headers: { 'content-length': String(PAYLOAD.length) },
chunks: [PAYLOAD]
}))
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
await manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
expect(netRequestMock).toHaveBeenCalledTimes(2)
expect(readFileSync(archivePath)).toEqual(PAYLOAD)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('does not retry non-transient failures', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest(() => ({ statusCode: 404 }))
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
await expect(
manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
join(dir, 'model.tar.bz2'),
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
).rejects.toThrow('HTTP 404')
expect(netRequestMock).toHaveBeenCalledTimes(1)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('aborts an HTTP error response instead of draining it after rejection', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const scripted = scriptRequest(() => ({
statusCode: 429,
headers: { 'retry-after': '3' }
}))
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const error = await manager
.downloadFile(
'https://example.com/model.tar.bz2',
join(dir, 'model.tar.bz2'),
PAYLOAD.length,
'm',
() => false
)
.catch((cause: unknown) => cause)
expect(error).toMatchObject({ message: 'HTTP 429', httpStatusCode: 429, retryAfterMs: 3_000 })
expect(scripted.abortMock).toHaveBeenCalledTimes(1)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('honors Retry-After before issuing another request', async () => {
vi.useFakeTimers()
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const archivePath = join(dir, 'model.tar.bz2')
const rateLimitError = Object.assign(new Error('HTTP 429'), {
httpStatusCode: 429,
retryAfterMs: 3_000
})
const downloadFileMock = vi
.spyOn(manager, 'downloadFile')
.mockRejectedValueOnce(rateLimitError)
.mockImplementationOnce(() => {
writeFileSync(archivePath, PAYLOAD)
return Promise.resolve()
})
const download = manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
archivePath,
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
await vi.advanceTimersByTimeAsync(2_999)
expect(downloadFileMock).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
await expect(download).resolves.toBeUndefined()
expect(downloadFileMock).toHaveBeenCalledTimes(2)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('does not retry before an excessively long Retry-After window', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const rateLimitError = Object.assign(new Error('HTTP 429'), {
httpStatusCode: 429,
retryAfterMs: 300_000
})
const downloadFileMock = vi.spyOn(manager, 'downloadFile').mockRejectedValue(rateLimitError)
await expect(
manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
join(dir, 'model.tar.bz2'),
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
).rejects.toThrow('server requested retry after 300 seconds')
expect(downloadFileMock).toHaveBeenCalledTimes(1)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('gives up after repeated zero-progress failures with a diagnosable error', async () => {
vi.useFakeTimers()
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const downloadFileMock = vi
.spyOn(manager, 'downloadFile')
.mockRejectedValue(new Error('net::ERR_CONNECTION_RESET'))
const download = manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
join(dir, 'model.tar.bz2'),
PAYLOAD.length,
'm',
() => false,
new AbortController().signal
)
const outcome = download.then(
() => 'resolved',
(error: unknown) => (error instanceof Error ? error.message : String(error))
)
// Let the first rejection schedule its backoff before advancing timers;
// this avoids racing fake time against stream/file I/O under full-suite load.
await vi.advanceTimersByTimeAsync(0)
expect(downloadFileMock).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(999)
expect(downloadFileMock).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(downloadFileMock).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(1_999)
expect(downloadFileMock).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(1)
expect(downloadFileMock).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(3_999)
expect(downloadFileMock).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1)
await expect(outcome).resolves.toMatch(
/Model download interrupted at 0% \(0 of 20 bytes\) after 4 attempts: .*net::ERR_CONNECTION_RESET/
)
expect(downloadFileMock).toHaveBeenCalledTimes(4)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('stops retrying once the download is aborted', async () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-model-resume-'))
try {
scriptRequest(() => ({
statusCode: 200,
headers: { 'content-length': String(PAYLOAD.length) },
failWith: 'net::ERR_CONNECTION_RESET'
}))
const controller = new AbortController()
const manager = new ModelManager(dir) as unknown as ModelManagerInternals
const download = manager.downloadArchiveWithRetry(
'https://example.com/model.tar.bz2',
join(dir, 'model.tar.bz2'),
PAYLOAD.length,
'm',
() => false,
controller.signal
)
const outcome = download.then(
() => 'resolved',
(error: unknown) => (error instanceof Error ? error.message : String(error))
)
// Abort after the transfer failure enters backoff; the next attempt must
// settle as Aborted without issuing another request.
setTimeout(() => controller.abort(), 100)
const message = await outcome
expect(message).toBe('Aborted')
expect(netRequestMock).toHaveBeenCalledTimes(1)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})
+323 -16
View File
@@ -1,7 +1,14 @@
/* eslint-disable max-lines -- Why: model download, checksum, extraction, and cleanup share one state machine so progress/error transitions stay coupled. */
import { app, net } from 'electron'
import { join, resolve, relative } from 'node:path'
import { existsSync, mkdirSync, createWriteStream, createReadStream, rmSync } from 'node:fs'
import {
existsSync,
mkdirSync,
createWriteStream,
createReadStream,
rmSync,
statSync
} from 'node:fs'
import { readdir, rm } from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { pipeline } from 'node:stream/promises'
@@ -28,11 +35,129 @@ type ProgressCallback = (modelId: string, progress: number) => void
type DownloadIncomingMessage = Electron.IncomingMessage &
NodeJS.ReadableStream & {
headers: Record<string, string | string[] | undefined>
resume: () => void
destroy?: () => void
}
type HttpStatusError = Error & {
httpStatusCode?: number
retryAfterMs?: number
retryable?: boolean
}
type DownloadTotals = { totalBytes: number }
type ContentRange = { start: number; end: number; totalBytes?: number }
const DOWNLOAD_IDLE_TIMEOUT_MS = 120_000
// Why: flaky networks and scanning proxies commonly kill long CDN transfers
// near the end (reported as "stuck at 90%, then fails"); resuming with a Range
// request lets those connections finish instead of failing the same way on
// every full restart.
const DOWNLOAD_RETRY_DELAYS_MS = [1_000, 2_000, 4_000]
// Why: abandon a download only after this many CONSECUTIVE attempts make no
// forward progress. A resume that keeps advancing (even across many mid-stream
// drops) is never given up on — that is the whole point of resumable downloads
// for large models over flaky networks, and a fixed all-time failure budget
// would wrongly kill a steadily-progressing large download.
const MAX_NO_PROGRESS_ATTEMPTS = DOWNLOAD_RETRY_DELAYS_MS.length + 1
// Why: an absolute backstop so a server handing back pathologically tiny (or
// zero-net) segments cannot loop forever; sized to cover the largest (~1GB)
// model even if a proxy caps each range response near ~256KB, far below any
// real CDN chunk.
const MAX_TOTAL_DOWNLOAD_REQUESTS = 4_096
// Why: a longer server window should be surfaced for a later manual retry,
// rather than leaving the settings download looking stuck for minutes.
const MAX_RETRY_AFTER_MS = 120_000
const RETRYABLE_NET_ERROR =
/net::ERR_(CONTENT_LENGTH_MISMATCH|INCOMPLETE_CHUNKED_ENCODING|CONNECTION_(RESET|CLOSED|ABORTED|REFUSED|TIMED_OUT)|EMPTY_RESPONSE|NETWORK_CHANGED|TIMED_OUT|INTERNET_DISCONNECTED|ADDRESS_UNREACHABLE|NAME_NOT_RESOLVED|SOCKET_NOT_CONNECTED|HTTP2_PROTOCOL_ERROR|QUIC_PROTOCOL_ERROR)\b/
const RETRYABLE_HTTP_STATUSES = new Set([408, 416, 425, 429, 500, 502, 503, 504])
function isRetryableDownloadError(error: unknown): boolean {
if (!(error instanceof Error)) {
return false
}
const downloadError = error as HttpStatusError
if (downloadError.retryable === true) {
return true
}
const statusCode = downloadError.httpStatusCode
if (statusCode !== undefined) {
return RETRYABLE_HTTP_STATUSES.has(statusCode)
}
return (
RETRYABLE_NET_ERROR.test(error.message) || error.message.includes('without network activity')
)
}
function getHeaderValue(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value
}
function parseContentRange(value: string | string[] | undefined): ContentRange | null {
const match = getHeaderValue(value)
?.trim()
.match(/^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i)
if (!match) {
return null
}
const start = Number.parseInt(match[1], 10)
const end = Number.parseInt(match[2], 10)
const totalBytes = match[3] === '*' ? undefined : Number.parseInt(match[3], 10)
if (
!Number.isSafeInteger(start) ||
!Number.isSafeInteger(end) ||
end < start ||
(totalBytes !== undefined && (!Number.isSafeInteger(totalBytes) || totalBytes <= end))
) {
return null
}
return { start, end, totalBytes }
}
function parseRetryAfterMs(value: string | string[] | undefined): number | undefined {
const header = getHeaderValue(value)?.trim()
if (!header) {
return undefined
}
if (/^\d+$/.test(header)) {
const seconds = Number.parseInt(header, 10)
const delayMs = seconds * 1_000
return Number.isSafeInteger(delayMs) ? delayMs : undefined
}
const retryAt = Date.parse(header)
return Number.isNaN(retryAt) ? undefined : Math.max(0, retryAt - Date.now())
}
function describeInterruptedDownload(
cause: unknown,
receivedBytes: number,
totalBytes: number,
attempts: number
): Error {
const causeMessage = cause instanceof Error ? cause.message : String(cause)
const received =
totalBytes > 0
? `${Math.min(99, Math.floor((receivedBytes / totalBytes) * 100))}% (${receivedBytes} of ${totalBytes} bytes)`
: `${receivedBytes} bytes`
return new Error(
`Model download interrupted at ${received} after ${attempts} attempts: ${causeMessage}`
)
}
function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (signal.aborted) {
resolve()
return
}
const onAbort = (): void => {
clearTimeout(timer)
resolve()
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort)
resolve()
}, ms)
signal.addEventListener('abort', onAbort, { once: true })
})
}
export class ModelManager {
private modelsDir: string
@@ -177,6 +302,15 @@ export class ModelManager {
this.updateState(modelId, 'downloading', 0)
const archivePath = join(this.modelsDir, `${modelId}.tar.bz2`)
// Why: resume appends to the partial archive from this download run only;
// a leftover file from a crashed run would corrupt the resumed archive.
try {
if (existsSync(archivePath)) {
rmSync(archivePath)
}
} catch {
// best-effort; the first (non-resumed) attempt truncates on write
}
let aborted = false
const abortController = new AbortController()
@@ -191,7 +325,7 @@ export class ModelManager {
this.activeDownloads.set(modelId, handle)
try {
await this.downloadFile(
await this.downloadArchiveWithRetry(
manifest.downloadUrl,
archivePath,
manifest.sizeBytes,
@@ -239,6 +373,7 @@ export class ModelManager {
this.updateState(modelId, 'ready')
} catch (err) {
if (!aborted) {
console.error('[speech] Model download failed:', modelId, err)
this.updateState(modelId, 'error', undefined, String(err))
}
this.cleanup(modelId, archivePath)
@@ -309,6 +444,120 @@ export class ModelManager {
}
}
private getPartialArchiveBytes(archivePath: string): number {
try {
return statSync(archivePath).size
} catch {
return 0
}
}
private async downloadArchiveWithRetry(
url: string,
archivePath: string,
expectedSize: number,
modelId: string,
isAborted: () => boolean,
signal: AbortSignal
): Promise<void> {
let requestCount = 0
let noProgressStreak = 0
const totals: DownloadTotals = { totalBytes: expectedSize }
for (;;) {
requestCount += 1
const offset = this.getPartialArchiveBytes(archivePath)
// Why: the transport can fail after the final byte reached disk; the
// caller's SHA-256 check is the authoritative completion test.
if (offset === totals.totalBytes) {
return
}
// Why: absolute backstop against a server that never lets the download
// finish; the stall and abort paths handle the common cases first.
if (requestCount > MAX_TOTAL_DOWNLOAD_REQUESTS) {
throw describeInterruptedDownload(
new Error('too many download requests'),
offset,
totals.totalBytes,
requestCount - 1
)
}
try {
// Why: each attempt restarts from the canonical URL rather than the
// last redirect target, because CDN redirect URLs are signed and expire.
await this.downloadFile(
url,
archivePath,
expectedSize,
modelId,
isAborted,
signal,
0,
offset,
totals
)
const receivedBytes = this.getPartialArchiveBytes(archivePath)
if (receivedBytes === totals.totalBytes) {
return
}
if (receivedBytes > totals.totalBytes) {
throw new Error(
`Model download exceeded its expected size (${receivedBytes} of ${totals.totalBytes} bytes)`
)
}
const incompleteResponse = new Error(
`Model download response ended at ${receivedBytes} of ${totals.totalBytes} bytes`
)
if (receivedBytes > offset) {
// Why: some proxies return a valid but bounded range segment; request
// the next segment immediately instead of failing checksum or waiting.
// Forward progress resets the stall counter; the total-request ceiling
// at the loop top bounds a pathological tiny-segment server.
noProgressStreak = 0
continue
}
const retryableIncompleteResponse = incompleteResponse as HttpStatusError
retryableIncompleteResponse.retryable = true
throw retryableIncompleteResponse
} catch (err) {
if (isAborted() || signal.aborted) {
throw err
}
const receivedBytes = this.getPartialArchiveBytes(archivePath)
if (receivedBytes === totals.totalBytes) {
return
}
noProgressStreak = receivedBytes > offset ? 0 : noProgressStreak + 1
if (!isRetryableDownloadError(err)) {
throw err
}
// Why: give up only on a genuine stall (repeated no forward progress);
// a download that keeps advancing across drops is allowed to continue.
if (noProgressStreak >= MAX_NO_PROGRESS_ATTEMPTS) {
throw describeInterruptedDownload(err, receivedBytes, totals.totalBytes, requestCount)
}
const retryAfterMs = (err as HttpStatusError).retryAfterMs
if (retryAfterMs !== undefined && retryAfterMs > MAX_RETRY_AFTER_MS) {
const statusCode = (err as HttpStatusError).httpStatusCode
throw new Error(
`HTTP ${statusCode}; server requested retry after ${Math.ceil(retryAfterMs / 1_000)} seconds`
)
}
console.warn(
`[speech] Model download attempt ${requestCount} failed, retrying:`,
modelId,
err
)
await sleepUnlessAborted(
retryAfterMs ??
DOWNLOAD_RETRY_DELAYS_MS[
Math.min(Math.max(0, noProgressStreak - 1), DOWNLOAD_RETRY_DELAYS_MS.length - 1)
],
signal
)
}
}
}
private downloadFile(
url: string,
dest: string,
@@ -316,7 +565,9 @@ export class ModelManager {
modelId: string,
isAborted: () => boolean,
signal?: AbortSignal,
redirectCount = 0
redirectCount = 0,
resumeOffset = 0,
totals?: DownloadTotals
): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
@@ -425,28 +676,81 @@ export class ModelManager {
modelId,
isAborted,
signal,
redirectCount + 1
redirectCount + 1,
resumeOffset,
totals
)
.then(resolveOnce)
.catch(rejectOnce)
}
const onResponse = (incoming: Electron.IncomingMessage): void => {
const response = incoming as DownloadIncomingMessage
if (response.statusCode !== 200) {
response.resume()
rejectOnce(new Error(`HTTP ${response.statusCode}`))
const contentLength = response.headers['content-length']
const headerLength = Number.parseInt(getHeaderValue(contentLength) || '0', 10)
const parsedLength =
Number.isSafeInteger(headerLength) && headerLength > 0 ? headerLength : 0
const contentRange = parseContentRange(response.headers['content-range'])
const resumed =
resumeOffset > 0 &&
response.statusCode === 206 &&
contentRange?.start === resumeOffset &&
(parsedLength <= 0 || parsedLength === contentRange.end - contentRange.start + 1)
if (resumeOffset > 0 && response.statusCode === 206 && !resumed) {
// Why: appending an unverified range can silently corrupt the archive;
// discard it so the canonical URL is retried from byte zero.
try {
rmSync(dest)
} catch {
// best-effort
}
const activeRequest = request
const rangeError: HttpStatusError = new Error(
`Invalid Content-Range for resume at byte ${resumeOffset}`
)
rangeError.retryable = true
rejectOnce(rangeError)
activeRequest?.abort()
return
}
const contentLength = response.headers['content-length']
const totalSize =
Number.parseInt(
Array.isArray(contentLength) ? contentLength[0] : contentLength || '0',
10
) || expectedSize
if (response.statusCode !== 200 && !resumed) {
if (response.statusCode === 416) {
// Why: the server rejected our resume offset; drop the partial so
// the retry loop can restart this download from scratch.
try {
rmSync(dest)
} catch {
// best-effort
}
}
const activeRequest = request
const statusError: HttpStatusError = new Error(`HTTP ${response.statusCode}`)
statusError.httpStatusCode = response.statusCode
statusError.retryAfterMs = parseRetryAfterMs(response.headers['retry-after'])
rejectOnce(statusError)
// Why: retrying must not leave a prior error body draining without
// cancellation or idle-timeout ownership.
activeRequest?.abort()
return
}
// Why: a 200 despite our Range request means the server restarted the
// transfer from byte zero, so the partial file must be overwritten.
const progressBase = resumed ? resumeOffset : 0
// Why: Content-Length on a 206 describes only this segment; when
// Content-Range uses '*', retain the known complete archive size.
const totalSize = resumed
? (contentRange?.totalBytes ?? totals?.totalBytes ?? expectedSize)
: parsedLength > 0
? parsedLength
: expectedSize
if (totals) {
totals.totalBytes = totalSize
}
let downloaded = 0
const fileStream = createWriteStream(dest)
const fileStream = createWriteStream(dest, { flags: resumed ? 'a' : 'w' })
const cleanupResponseProgressListener = (): void => {
response.off('data', onResponseData)
@@ -460,7 +764,7 @@ export class ModelManager {
return
}
downloaded += chunk.length
const progress = Math.min(0.9, downloaded / totalSize)
const progress = Math.min(0.9, (progressBase + downloaded) / totalSize)
this.updateState(modelId, 'downloading', progress)
}
@@ -481,6 +785,9 @@ export class ModelManager {
}
request = net.request({ method: 'GET', url: parsedUrl.toString() })
if (resumeOffset > 0) {
request.setHeader('Range', `bytes=${resumeOffset}-`)
}
// Why: Electron's net stack honors app proxy settings, unlike Node's
// https client, but it does not expose request.setTimeout().
@@ -13,6 +13,13 @@ import {
import { Cloud, Download, Trash2, Loader2, ChevronDown, Check } from 'lucide-react'
import { translate } from '@/i18n/i18n'
function describeSpeechModelDownloadError(error: unknown): string {
const message = error instanceof Error ? error.message : String(error)
// Why: ipcRenderer.invoke wraps main-process rejections; strip the transport
// prefix so the toast shows only the underlying download failure.
return message.replace(/^Error invoking remote method '[^']+': (?:Error: )?/, '')
}
type VoiceSpeechModelSectionProps = {
voiceSettings: VoiceSettings
catalog: SpeechModelManifest[]
@@ -90,16 +97,17 @@ export function VoiceSpeechModelSection({
} else if (!isDownloading) {
// Why: download progress appears in this menu, so starting one should not dismiss it.
event.preventDefault()
void window.api.speech
.downloadModel(manifest.id)
.catch(() =>
toast.error(
translate(
'auto.components.settings.VoicePane.cfde55c7b0',
'Failed to download model.'
)
)
void window.api.speech.downloadModel(manifest.id).catch((error: unknown) =>
toast.error(
translate(
'auto.components.settings.VoicePane.cfde55c7b0',
'Failed to download model.'
),
// Why: the raw cause (e.g. net::ERR_CONTENT_LENGTH_MISMATCH)
// is the only diagnosable signal users can report back.
{ description: describeSpeechModelDownloadError(error) }
)
)
}
}}
className={`group flex items-center gap-2.5 py-2.5 ${