fix: startup hint, sidecar heartbeat, VC++ runtime guidance, tail fade and actionable failure reports (#4243)

Fixes #4228, #4229, #4230.
This commit is contained in:
Palash Debnath authored and GitHub committed 2026-11-18 05:01:26 +05:30
1 parent 73d6139597
commit eee6850070
59 files changed
+592 -65

No files matched your search

+12 -3
View File
@@ -313,18 +313,27 @@ def _check_deep_synthesis() -> dict:
import concurrent.futures
import time as _time
from services.inference_cancellation import InferenceCancellation
# A killable sidecar watches this scope: at the deadline below it is
# stopped instead of holding the engine lock and a GPU worker for as long
# as its heartbeats keep arriving (#4228).
cancellation = InferenceCancellation()
def _synth():
import services.model_manager as mm
from services.tts_backend import get_active_tts_backend, active_backend_id
backend = get_active_tts_backend(model=mm.model)
wav = backend.generate("Diagnostics check, one two three.", num_step=4)
return active_backend_id(), int(wav.shape[-1]) / max(1, backend.sample_rate)
with cancellation.activate():
backend = get_active_tts_backend(model=mm.model)
wav = backend.generate("Diagnostics check, one two three.", num_step=4)
return active_backend_id(), int(wav.shape[-1]) / max(1, backend.sample_rate)
t0 = _time.perf_counter()
ex = concurrent.futures.ThreadPoolExecutor(max_workers=1)
try:
engine_id, audio_s = ex.submit(_synth).result(timeout=_DEEP_TIMEOUT_S)
except concurrent.futures.TimeoutError:
cancellation.cancel()
return _check(
"deep_synth", "Deep synthesis", FAIL,
f"timed out after {_DEEP_TIMEOUT_S}s - engine load or synthesis hung",
+4 -1
View File
@@ -232,6 +232,7 @@ def validate_record(value, epoch, schema=None):
_causal_counter = itertools.count(1)
_NETWORK_ERRNOS = frozenset(getattr(errno, name) for name in ('ENETDOWN','ENETUNREACH','ENETRESET','EHOSTUNREACH','EHOSTDOWN','ENOTCONN','ETIMEDOUT') if hasattr(errno, name))
def _exception_fields(error, schema):
@@ -254,13 +255,15 @@ def _exception_fields(error, schema):
if MemoryError in kinds:
result['error_code'] = 'HOST_MEMORY_EXHAUSTED'
elif any(cls is compute_timeout for cls in kinds):
result['error_code'] = 'UNKNOWN'
result['error_code'] = 'GPU_JOB_TIMEOUT'
elif TimeoutError in kinds or ConnectionError in kinds:
result['error_code'] = 'NETWORK_ERROR'
elif OSError in kinds:
number = BaseException.__getattribute__(error,'errno')
if number in (errno.ENOSPC,errno.EDQUOT):
result['error_code'] = 'DISK_FULL'
elif number in _NETWORK_ERRNOS:
result['error_code'] = 'NETWORK_ERROR'
lines = []
total = 0
tb = BaseException.__getattribute__(error,'__traceback__')
+56 -36
View File
@@ -62,6 +62,34 @@ _SEND_LOCK = threading.Lock()
_LOAD_HEARTBEAT_S = 5.0
@contextlib.contextmanager
def _heartbeating(stdout, stage: str, progress: dict | None = None):
"""Send {"op":"progress"} every few seconds while the body runs.
The parent re-arms its recv watchdog on every frame, so slow-but-alive work
(imports on a cold disk, reference transcription, a long synthesis) is not
killed as a silent wedge (#4228). Stage "loading_model" also counts as
cold-load evidence for the parent's GPU-pool clock; "generating" does not.
"""
stop = threading.Event()
def beat() -> None:
while not stop.wait(_LOAD_HEARTBEAT_S):
_send(stdout, {
"op": "progress",
"stage": stage,
"percent": (progress or {}).get("percent", 0),
})
thread = threading.Thread(target=beat, name=f"omnivoice-{stage}-heartbeat", daemon=True)
thread.start()
try:
yield
finally:
stop.set()
thread.join()
# ── wire protocol ─────────────────────────────────────────────────────────
@@ -180,10 +208,18 @@ def _skip_unused_heavy_imports():
def _load_model(stdout):
"""Cold-construct the OmniVoice model, reusing the parent's load path."""
global _model
if _model is not None:
return _model
progress = {"percent": 0}
# Heartbeat across the WHOLE cold load, imports and weight prefetch
# included: those used to be silent, and on a slow Windows disk they alone
# could outlast the parent's recv deadline (#4228).
with _heartbeating(stdout, "loading_model", progress):
return _construct_model(stdout, progress)
def _construct_model(stdout, progress: dict):
global _model
_send(stdout, {"op": "progress", "stage": "loading_model", "percent": 0})
_ensure_backend_on_path()
@@ -202,8 +238,6 @@ def _load_model(stdout):
# Forward real HF download/weight progress so the parent's recv loop keeps
# its watchdog alive across a slow cold load (the parent consumes these
# {"op": "progress"} frames and re-arms its deadline on each one).
progress = {"percent": 0}
def _on_progress(ev):
pct = ev.get("pct", 0.0)
if pct:
@@ -211,19 +245,6 @@ def _load_model(stdout):
_send(stdout, {"op": "progress", "stage": "loading_model",
"percent": progress["percent"]})
# Cached checkpoints produce no download callbacks. Loading and moving a
# model onto MPS can still exceed the normal generation budget, so keep
# both bounded parent watchdogs informed that the child remains alive.
stop_heartbeat = threading.Event()
def _heartbeat():
while not stop_heartbeat.wait(_LOAD_HEARTBEAT_S):
_send(stdout, {
"op": "progress",
"stage": "loading_model",
"percent": progress["percent"],
})
checkpoint = resolve_omnivoice_checkpoint()
stop_prefetch = threading.Event()
threading.Thread(
@@ -242,20 +263,12 @@ def _load_model(stdout):
stop_prefetch.set()
lid = register_listener(_on_progress)
heartbeat = threading.Thread(
target=_heartbeat,
name="omnivoice-load-heartbeat",
daemon=True,
)
heartbeat.start()
try:
_model = OmniVoice.from_pretrained(
checkpoint, device_map=device,
dtype=getattr(torch, tts_dtype_name(device)), load_asr=preload_asr,
)
finally:
stop_heartbeat.set()
heartbeat.join()
unregister_listener(lid)
_send(stdout, {"op": "progress", "stage": "loading_model", "percent": 100})
return _model
@@ -310,7 +323,11 @@ def _handle_synthesize(msg: dict, stdout) -> None:
ref_text = None
try:
ref_text = transcribe_reference(ref_audio, release_after=True)
# Loads a Whisper model: silent for minutes on a cold disk. Not
# a "loading_model" stage: the parent credits that as cold-load
# progress, and a stalled transcription must not earn it.
with _heartbeating(stdout, "reference_asr"):
ref_text = transcribe_reference(ref_audio, release_after=True)
reference_asr = None if ref_text else "empty"
except Exception: # noqa: BLE001 — preserve installed-only model fallback
reference_asr = "failed"
@@ -332,18 +349,21 @@ def _handle_synthesize(msg: dict, stdout) -> None:
# length: when resolution found no words, plain generate() would load the
# model's own ASR and (now) release it again on every line.
untranscribed = isinstance(ref_audio, str) and not (ref_text or "").strip()
if untranscribed:
_ensure_backend_on_path()
from services.tts_backend import generate_with_cached_ref # noqa: PLC0415
# The first synthesis also pays one-time kernel compilation / warm-up; keep
# proving liveness so a slow render is not mistaken for a hang (#4228).
with _heartbeating(stdout, "generating"):
if untranscribed:
_ensure_backend_on_path()
from services.tts_backend import generate_with_cached_ref # noqa: PLC0415
audios = generate_with_cached_ref(
model, text=text, ref_audio=ref_audio, ref_text=None,
release_reference_asr=True, reference_asr=reference_asr, **gen_kw,
)
else:
audios = model.generate(
text=text, ref_audio=ref_audio, ref_text=ref_text, **gen_kw
)
audios = generate_with_cached_ref(
model, text=text, ref_audio=ref_audio, ref_text=None,
release_reference_asr=True, reference_asr=reference_asr, **gen_kw,
)
else:
audios = model.generate(
text=text, ref_audio=ref_audio, ref_text=ref_text, **gen_kw
)
audio = audios[0] if isinstance(audios, (list, tuple)) else audios
sample_rate = int(getattr(model, "sampling_rate", OMNIVOICE_SAMPLE_RATE))
+21 -1
View File
@@ -14,6 +14,7 @@ returned unmodified). The leveler and the peak limiter are pure numpy (#3412), s
they always run.
"""
import logging
import math
import subprocess
import sys
import threading
@@ -248,7 +249,26 @@ def trim_speech_padding(audio_tensor: torch.Tensor, sample_rate: int) -> torch.T
margin = int(sample_rate * 0.05)
start = max(0, int(voiced[0].item()) - margin)
end = min(audio_tensor.shape[-1], int(voiced[-1].item()) + 1 + margin)
return audio_tensor[..., start:end]
return _fade_out_tail(audio_tensor[..., start:end], sample_rate)
def _fade_out_tail(audio_tensor: torch.Tensor, sample_rate: int, fade_ms: float = 25.0) -> torch.Tensor:
"""Ease the last ``fade_ms`` to zero so a trimmed take never ends on a click (#4229).
Edge trimming leaves the final sample wherever the decay happened to be,
and some engines stop mid-tail; the step to silence reads as a sharp
cut-off. The length is unchanged. A tail already below -60 dBFS is left
as is. Never touches the head.
"""
n = min(int(sample_rate * fade_ms / 1000), audio_tensor.shape[-1])
if n < 2:
return audio_tensor
if float(audio_tensor[..., -1].abs().max()) <= 10 ** (-60 / 20):
return audio_tensor
ramp = 0.5 * (1 + torch.cos(torch.linspace(0, math.pi, n, device=audio_tensor.device, dtype=audio_tensor.dtype)))
out = audio_tensor.clone()
out[..., -n:] = out[..., -n:] * ramp
return out
#: Samples per block for the numpy stages. Long takes are processed in blocks
#: so temporary memory stays bounded (a 30-minute take at 24 kHz is 43 M
+7 -1
View File
@@ -283,6 +283,12 @@ def _ensure_reaper_running() -> None:
_RESOLVE_HEARTBEAT_S = 5.0
#: Progress stages that only re-arm the recv watchdog. They prove the child is
#: alive, not that a cold load advanced, so they never extend the pool job's
#: execution budget (#2435, #4228).
_UNCREDITED_PROGRESS_STAGES = frozenset({"generating", "reference_asr"})
@contextlib.contextmanager
def _heartbeat_while_resolving(engine_id: str):
"""Report progress while a slow engine-venv resolution runs (#1414).
@@ -978,7 +984,7 @@ class SubprocessBackend(TTSBackend):
# timer thread proves nothing about synthesis progress:
# crediting it would let a stalled native generate hold
# its GPU worker past the execution budget (#2435).
if running_on_gpu_pool() and reply.get("stage") != "generating":
if running_on_gpu_pool() and reply.get("stage") not in _UNCREDITED_PROGRESS_STAGES:
report_model_load_activity()
except Exception:
pass # the heartbeat is best-effort; never fail a synth over it
+1
View File
@@ -0,0 +1 @@
The startup screen only says "first run can take several minutes" while the Python environment is actually being installed, and the OmniVoice engine now reports progress during cold imports, reference transcription and synthesis so slow starts are no longer killed as "sent nothing for 300s" (#4228)
+1
View File
@@ -0,0 +1 @@
Trimmed speech now ends with a short fade-out instead of a sharp cut-off (#4229)
+1
View File
@@ -0,0 +1 @@
Windows setup now explains a torch c10.dll "WinError 1114" load failure as an outdated Visual C++ runtime and tells you to install the latest one (#4230)
+1
View File
@@ -0,0 +1 @@
Opt-in automatic failure reports now name which part of the app failed (main process, GPU or helper process, GPU job timeout or network) instead of reporting an unknown error (#4243)
+6
View File
@@ -54,12 +54,16 @@
"FFMPEG_MISSING",
"GATEKEEPER_QUARANTINE",
"GPU_ARCH_UNSUPPORTED",
"GPU_JOB_TIMEOUT",
"GPU_OOM",
"GPU_PROCESS_GONE",
"HF_AUTH_FAILED",
"HF_MIRROR_GATED",
"HOST_MEMORY_EXHAUSTED",
"INPUT_TOO_SHORT",
"INVALID_MEDIA_FILE",
"MAIN_UNCAUGHT_EXCEPTION",
"MAIN_UNHANDLED_REJECTION",
"MEDIA_TOOL_MISSING",
"MODEL_CACHE_CORRUPT",
"MODEL_DOWNLOAD_INTERRUPTED",
@@ -70,6 +74,7 @@
"NETWORK_ERROR",
"NO_AUDIO_TRACK",
"OS_INVALID_ARGUMENT",
"OTHER_CHILD_PROCESS_GONE",
"PKG_RESOURCES_MISSING",
"POCKETTTS_GATED_WEIGHTS",
"PORT_IN_USE",
@@ -93,6 +98,7 @@
"UNKNOWN",
"UNSUPPORTED_PLATFORM",
"UNSUPPORTED_VIDEO_URL",
"UTILITY_PROCESS_GONE",
"VIDEO_DOWNLOAD_BOT_CHECK",
"VIDEO_DOWNLOAD_NETWORK",
"VIDEO_DOWNLOAD_OS_ERROR",
+4
View File
@@ -72,6 +72,10 @@ Without valid app credentials, the existing public events request
(`/api/public/v1/events`, event `diagnostic_report`) and site remain unchanged.
Usage analytics keeps its existing destination and request format.
`config/diagnostics.json` is the shared closed metadata policy.
Desktop process crashes carry a closed code that names the path, never a message:
main-process uncaught exception or unhandled rejection, GPU process gone, utility
process gone, or another Electron child process gone (the child's free-text service
name is not read). A generation deadline reports `GPU_JOB_TIMEOUT`.
Reports contain technical categories/codes, app/build/platform labels,
known first-party source locations, bounded counters and a separately generated
random installation ID. They never contain audio, text/transcripts, user names,
+2
View File
@@ -119,6 +119,8 @@ The runtime is inside OneDrive, Dropbox, iCloud Drive, Google Drive or Nextcloud
A system library the engine needs is missing or too old. The setup screen names it; see the [Linux guide](linux.md).
On Windows the usual one is the Microsoft Visual C++ Redistributable. `OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed ... torch\lib\c10.dll` while importing `faster_whisper`, `ctranslate2` or `torch` means the installed copy is too old or damaged (VoiceStudio reports its `msvcp140.dll` version when it can read it). Reinstalling the Python packages cannot fix it. Install the latest [Microsoft Visual C++ Redistributable (x64)](https://aka.ms/vs/17/release/vc_redist.x64.exe), restart Windows, then press Retry.
### `UNSUPPORTED_PLATFORM`
This computer cannot run the local engine, or this is the wrong download for it. See the [macOS guide](macos.md), or connect to an engine on another computer.
+6
View File
@@ -90,6 +90,7 @@ vi.mock('./runtime-project', async (importOriginal) => ({
...(await importOriginal<typeof import('./runtime-project')>()),
MISSING_SYSTEM_LIBRARY_CODE: 'MISSING_SYSTEM_LIBRARY',
OUTDATED_SYSTEM_LIBRARY_CODE: 'OUTDATED_SYSTEM_LIBRARY',
TORCH_DLL_INIT_FAILED_CODE: 'TORCH_DLL_INIT_FAILED',
RUNTIME_FILES_LOCKED_CODE: 'RUNTIME_FILES_LOCKED',
runtimeDependenciesReady: mocks.dependencies,
runtimeReady: mocks.ready,
@@ -613,6 +614,11 @@ it('exposes actionable storage failures without requiring log parsing', async ()
);
await supervisor.setupRuntime();
expect(supervisor.status.setupIssue).toBe('outdated_system_library');
mocks.install.mockRejectedValue(
Object.assign(new Error('unknown cause'), { code: 'TORCH_DLL_INIT_FAILED' }),
);
await supervisor.setupRuntime();
expect(supervisor.status.setupIssue).toBe('torch_dll_init_failed');
await supervisor.shutdown();
});
@@ -32,6 +32,7 @@ vi.mock('./runtime-project', async (importOriginal) => ({
runtimePython: (root: string) => root + '/.venv/bin/python',
MISSING_SYSTEM_LIBRARY_CODE: 'MISSING_SYSTEM_LIBRARY',
OUTDATED_SYSTEM_LIBRARY_CODE: 'OUTDATED_SYSTEM_LIBRARY',
TORCH_DLL_INIT_FAILED_CODE: 'TORCH_DLL_INIT_FAILED',
RUNTIME_FILES_LOCKED_CODE: 'RUNTIME_FILES_LOCKED',
}));
+4 -1
View File
@@ -18,6 +18,7 @@ import {
installRuntime,
MISSING_SYSTEM_LIBRARY_CODE,
OUTDATED_SYSTEM_LIBRARY_CODE,
TORCH_DLL_INIT_FAILED_CODE,
RUNTIME_FILES_LOCKED_CODE,
promoteLegacyRuntimeCaches,
runtimeDependenciesReady,
@@ -1961,7 +1962,9 @@ export class BackendSupervisor extends EventEmitter<{
? 'missing_system_library'
: code === OUTDATED_SYSTEM_LIBRARY_CODE
? 'outdated_system_library'
: code === RUNTIME_FILES_LOCKED_CODE
: code === TORCH_DLL_INIT_FAILED_CODE
? 'torch_dll_init_failed'
: code === RUNTIME_FILES_LOCKED_CODE
? 'files_locked'
: ['EACCES', 'EPERM', 'EROFS'].includes(code || '')
? 'access'
+18 -4
View File
@@ -119,7 +119,12 @@ export function installDiagnosticProcessCapture(
source: MainProcessErrorSource = process,
): () => void {
const stopTracking = trackDiagnosticOperations();
const capture = (error: unknown, reason: string, expectedEpoch?: string) => {
const capture = (
error: unknown,
reason: string,
error_code: string,
expectedEpoch?: string,
) => {
try {
if (!reports.enabled) return;
if (
@@ -128,7 +133,7 @@ export function installDiagnosticProcessCapture(
)
return;
reports.capture(
{ category: 'app_crash', stage: 'other', reason, ...projectException(error) },
{ category: 'app_crash', stage: 'other', reason, error_code, ...projectException(error) },
expectedEpoch,
);
} catch {
@@ -141,11 +146,11 @@ export function installDiagnosticProcessCapture(
if (origin === 'unhandledRejection') return;
const owner = diagnosticOperationOwner(reports, error);
if (!owner || owner.epoch === null) return;
capture(error, 'unhandled_exception', owner.epoch);
capture(error, 'unhandled_exception', 'MAIN_UNCAUGHT_EXCEPTION', owner.epoch);
};
const rejected = (error: unknown, promise?: Promise<unknown>) => {
const epoch = diagnosticRejectionEpoch(promise, reports, error);
if (epoch !== null) capture(error, 'unhandled_rejection', epoch);
if (epoch !== null) capture(error, 'unhandled_rejection', 'MAIN_UNHANDLED_REJECTION', epoch);
};
source.on('uncaughtExceptionMonitor', fatal);
source.on('unhandledRejection', rejected);
@@ -156,6 +161,13 @@ export function installDiagnosticProcessCapture(
};
}
/** Electron's fixed child-process type enum; the free-text service name is never read. */
function childProcessCode(type: string | undefined): string {
if (type === 'GPU') return 'GPU_PROCESS_GONE';
if (type === 'Utility') return 'UTILITY_PROCESS_GONE';
return 'OTHER_CHILD_PROCESS_GONE';
}
/** Electron provides these reasons; normal/expected exits and arbitrary strings are ignored. */
export function captureProcessGone(
reports: Pick<DiagnosticReports, 'capture'>,
@@ -163,6 +175,7 @@ export function captureProcessGone(
reason: string,
exitCode: number,
expected = false,
processType?: string,
): void {
if (
expected ||
@@ -182,6 +195,7 @@ export function captureProcessGone(
'integrity-failure': 'integrity_failure',
} as Record<string, string>
)[reason] ?? reason,
...(renderer ? {} : { error_code: childProcessCode(processType) }),
exit_code: exitCode,
});
}
+17 -2
View File
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { types } from 'node:util';
import rawSchema from '../../../config/diagnostics.json';
import type { DiagnosticCategory, DiagnosticStage } from '../preload/diagnostics';
@@ -255,11 +256,25 @@ export function sanitizeRecord(
: null;
}
/** Subclasses (`class FetchError extends TypeError`) report their nearest known built-in base. */
function knownErrorType(error: { name: string }): string {
const named = enums.get('error_type')?.has(error.name) ? error.name : undefined;
if (named && named !== 'Error') return named;
let proto: unknown = Object.getPrototypeOf(error);
for (let depth = 0; proto && depth < 16; depth++) {
const ctor = (proto as { constructor?: { name?: unknown } }).constructor;
const name = ctor && typeof ctor.name === 'string' ? ctor.name : '';
if (name !== 'Error' && enums.get('error_type')?.has(name) && name !== 'OtherError') return name;
proto = Object.getPrototypeOf(proto);
}
return named ?? 'OtherError';
}
/** Error messages and the first stack line are intentionally never inspected. */
export function projectException(error: unknown): Pick<DiagnosticEvent, 'error_type' | 'frames'> {
try {
if (!(error instanceof Error)) return { error_type: 'OtherError' };
const error_type = enumValue('error_type', error.name) ?? 'OtherError';
if (!(error instanceof Error) && !types.isNativeError(error)) return { error_type: 'OtherError' };
const error_type = knownErrorType(error);
const frames: string[] = [];
for (const line of String(error.stack ?? '')
.slice(0, 32_768)
+33 -1
View File
@@ -11,7 +11,7 @@ import {
installDiagnosticProcessCapture,
captureProcessGone,
} from './diagnostics-capture';
import { sanitizeProperties, sanitizeFrames, validUiInput } from './diagnostics-schema';
import { projectException, sanitizeProperties, sanitizeFrames, validUiInput } from './diagnostics-schema';
import { runDiagnosticOperation } from './diagnostic-operation';
import { MainErrorJournal, installMainProcessErrorHandlers } from './main-error-journal';
import type { BackendStatus } from '../preload/index.d';
@@ -698,9 +698,41 @@ describe('strict data projection and durable recovery', () => {
stop();
await reports.flush();
expect(send).toHaveBeenCalledTimes(2);
const sent = send.mock.calls.map((call) => JSON.parse(String(call[1]?.body)).props.error_code);
expect(sent).toContain('MAIN_UNCAUGHT_EXCEPTION');
expect(JSON.stringify(send.mock.calls)).not.toMatch(/PRIVATE_PROMPT|PRIVATE_CANCEL/);
});
it('gives every stage-other app_crash path a distinct closed error_code', async () => {
const capture = vi.fn();
const reports = { capture } as never;
captureProcessGone(reports, false, 'crashed', 1, false, 'GPU');
captureProcessGone(reports, false, 'crashed', 1, false, 'Utility');
captureProcessGone(reports, false, 'killed', 9, false, 'Zygote');
captureProcessGone(reports, false, 'killed', 9);
const codes = capture.mock.calls.map(([event]) => event.error_code);
expect(codes).toEqual([
'GPU_PROCESS_GONE',
'UTILITY_PROCESS_GONE',
'OTHER_CHILD_PROCESS_GONE',
'OTHER_CHILD_PROCESS_GONE',
]);
captureProcessGone(reports, true, 'crashed', 1, false, 'Tab');
expect(capture.mock.calls.at(-1)?.[0].error_code).toBeUndefined();
});
it('projects subclasses of built-in errors to their built-in base type', () => {
class FetchError extends TypeError {
name = 'FetchError';
}
expect(projectException(new FetchError('PRIVATE')).error_type).toBe('TypeError');
expect(projectException(new RangeError('x')).error_type).toBe('RangeError');
expect(projectException(Object.assign(new Error('x'), { name: 'Custom' })).error_type).toBe(
'OtherError',
);
expect(projectException('string').error_type).toBe('OtherError');
});
it('does not call a slow or canceled install stalled without actual no-progress evidence', async () => {
const send = success();
const reports = reporter({ send });
+1
View File
@@ -535,6 +535,7 @@ if (singleInstance && !app.requestSingleInstanceLock()) {
details.reason,
details.exitCode,
quitting || Boolean(quitPreparation),
details.type,
);
});
let initialized: Promise<void> = Promise.resolve();
+5 -1
View File
@@ -103,7 +103,11 @@ export async function localDataIdentity(directory: string): Promise<string | und
if (matches(previous)) return (await sameRoot()) ? previous!.id : undefined;
// One creator/rotation at a time. Other instances may read the completed
// atomic publication; a stale or inaccessible lock simply leaves it unknown.
for (let attempt = 0; attempt < 50; attempt++) {
// A time budget, not an attempt count: a loaded machine (or CI runner) can
// hold the lock longer than a fixed number of 10 ms waits.
// Monotonic: a wall-clock jump must not stretch or cut the wait.
const deadline = performance.now() + 5_000;
while (performance.now() < deadline) {
try {
lock = await open(lockPath, 'wx', 0o600);
break;
+57
View File
@@ -1963,6 +1963,63 @@ describe('outdated Visual C++ runtime behind a native import crash (#3293)', ()
expect(await runtimeReady(bundle, project)).toBe(false);
});
it('names an outdated runtime behind torch WinError 1114 on c10.dll (#4230)', async () => {
const { bundle, project } = await fixture();
const failure = installRuntime(
bundle,
project,
'uv',
runner('14.23.27820.0', () =>
Object.assign(new Error('Runtime setup exited with code 1'), {
code: 1,
stdout: 'VOICESTUDIO_IMPORT=fastapi\nVOICESTUDIO_IMPORT=faster_whisper\n',
stderr:
'OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading "C:\\x\\torch\\lib\\c10.dll" or one of its dependencies.',
}),
),
new AbortController().signal,
);
await expect(failure).rejects.toMatchObject({ code: OUTDATED_SYSTEM_LIBRARY_CODE });
await expect(failure).rejects.toThrow(/"faster_whisper".*14\.23\.27820\.0.*Visual C\+\+/s);
});
const dllInit = (dir = 'C:\\x') => () =>
Object.assign(new Error('Runtime setup exited with code 1'), {
code: 1,
stdout: 'VOICESTUDIO_IMPORT=fastapi\nVOICESTUDIO_IMPORT=faster_whisper\n',
stderr: `OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading "${dir}\\torch\\lib\\c10.dll" or one of its dependencies.`,
});
it('matches WinError 1114 even when the runtime path is very long (#4230)', async () => {
const { bundle, project } = await fixture();
await expect(
installRuntime(
bundle,
project,
'uv',
runner('14.23.27820.0', dllInit(`D:\\${'a'.repeat(400)}`)),
new AbortController().signal,
),
).rejects.toMatchObject({ code: OUTDATED_SYSTEM_LIBRARY_CODE });
});
it.each([
['a current runtime', '14.44.35211.0', /\(14\.44\.35211\.0\) looks current/],
['an unreadable runtime version', '', /version could not be read/],
])('does not blame the runtime for WinError 1114 with %s (#4230)', async (_n, version, text) => {
const { bundle, project } = await fixture();
const failure = installRuntime(
bundle,
project,
'uv',
runner(version, dllInit()),
new AbortController().signal,
);
await expect(failure).rejects.toMatchObject({ code: 'TORCH_DLL_INIT_FAILED' });
await expect(failure).rejects.toThrow(text);
await expect(failure).rejects.toThrow(/not established/);
});
it('keeps the plain import failure when the runtime is current or the error is not a crash', async () => {
const current = await fixture();
await expect(
+44 -2
View File
@@ -187,6 +187,18 @@ export const OUTDATED_SYSTEM_LIBRARY_CODE = 'OUTDATED_SYSTEM_LIBRARY';
export const MIN_MSVCP140_VERSION = [14, 40] as const;
/** Windows exit status for an access violation, unsigned and signed. */
const ACCESS_VIOLATION_EXIT_CODES = new Set<unknown>([3221225477, -1073741819]);
/**
* Python's `OSError: [WinError 1114]` from torch's own DLL loader (#4230).
*
* `torch/__init__.py` re-raises it as "Error loading ...\\torch\\lib\\c10.dll or one of
* its dependencies". A DLL initialization routine fails in `c10.dll` when the
* Visual C++ runtime it initialises against is too old or damaged; reinstalling
* the wheels cannot change a system library.
*/
/** Error code for a torch DLL that would not initialise when the cause is not established. */
export const TORCH_DLL_INIT_FAILED_CODE = 'TORCH_DLL_INIT_FAILED';
// One line, no distance limit: a long custom runtime path must still match (#4230).
const TORCH_DLL_INIT_FAILED = /WinError 1114[^\r\n]*\btorch[\\/]+lib[\\/]+\w+\.dll/i;
function importFailure(error: unknown): Error {
const failure = error as { code?: unknown; message?: unknown; stdout?: unknown } | null;
const module = lastImportAttempted(failure?.stdout);
@@ -785,10 +797,40 @@ export function outdatedSystemLibraryError(
diagnosis: NativeRuntimeDiagnosis,
): Error | null {
const code = (failure as { code?: unknown } | null)?.code;
if (!ACCESS_VIOLATION_EXIT_CODES.has(code)) return null;
const msvcp = diagnosis.msvcp140;
const output = failure as { stdout?: unknown; stderr?: unknown; message?: unknown } | null;
const text = `${output?.stderr ?? ''}\n${output?.stdout ?? ''}\n${output?.message ?? ''}`;
const module = lastImportAttempted(output?.stdout);
// torch's DLL loader names the failure itself, so it needs no crash status. The
// system runtime is the cause whether or not the probe could read its version.
if (TORCH_DLL_INIT_FAILED.test(text)) {
const subject = module ? `Importing "${module}" failed` : 'Loading PyTorch failed';
if (msvcp && msvcp140Outdated(msvcp.version)) {
return Object.assign(
new Error(
`${subject} because Windows could not initialise PyTorch's c10.dll (WinError 1114) and this ` +
`system's Visual C++ runtime is outdated (${scrubText(msvcp.path)} is version ${msvcp.version}; ` +
`${MIN_MSVCP140_VERSION.join('.')} or newer is needed). Install the latest Microsoft Visual C++ ` +
'Redistributable (x64) from Microsoft, restart Windows and press Retry; reinstalling the ' +
'Python packages cannot update a system library.',
),
{ code: OUTDATED_SYSTEM_LIBRARY_CODE, stdout: output?.stdout },
);
}
// The runtime is current or could not be read: the cause is not established.
return Object.assign(
new Error(
`${subject} because Windows could not initialise PyTorch's c10.dll (WinError 1114). The cause ` +
'is not established: this Windows system\'s Visual C++ runtime ' +
`${msvcp?.version ? `(${msvcp.version}) looks current` : 'version could not be read'}. Installing the latest ` +
'Microsoft Visual C++ Redistributable (x64) and restarting Windows may help; so may updating the ' +
'graphics driver or pressing Clean & Retry under More fixes. Send the in-app report if it persists.',
),
{ code: TORCH_DLL_INIT_FAILED_CODE, stdout: output?.stdout },
);
}
if (!ACCESS_VIOLATION_EXIT_CODES.has(code)) return null;
if (!msvcp || !msvcp140Outdated(msvcp.version)) return null;
const module = lastImportAttempted((failure as { stdout?: unknown }).stdout);
return Object.assign(
new Error(
`${module ? `Importing "${module}" crashed` : 'A native import crashed'} because this Windows ` +
+1
View File
@@ -66,6 +66,7 @@ export interface BackendStatus {
| 'wrong_architecture'
| 'missing_system_library'
| 'outdated_system_library'
| 'torch_dll_init_failed'
| 'files_locked'
| 'install_stuck';
/** Free disk (GiB) the failed install needed; the CPU-only install needs less than the CUDA one. */
@@ -169,6 +169,20 @@ it('lists install steps with the active package on the current step and the log
expect(restart).toHaveBeenCalledTimes(1);
});
it.each(['starting', 'attaching'] as const)(
'does not claim a first run on an ordinary %s launch (#4228)',
(stage) => {
backendStatus.stage = stage;
render(
<BackendGate>
<div>workspace</div>
</BackendGate>,
);
expect(screen.queryByText(i18n.t('backend.first_run_hint'))).not.toBeInTheDocument();
expect(screen.getByText(i18n.t(`backend.${stage}`))).toBeInTheDocument();
},
);
it('keeps the download bar live when a new download follows a prepared batch', () => {
backendStatus.stage = 'installing';
backendStatus.setupPhase = 'installing_deps';
@@ -644,6 +658,16 @@ it('warns about Smart App Control before the download without blocking install',
delete backendStatus.smartAppControlWarning;
});
it('shows localized guidance for a torch DLL failure with no established cause (#4230)', () => {
backendStatus.message = 'Importing "faster_whisper" failed (WinError 1114)';
backendStatus.setupIssue = 'torch_dll_init_failed';
renderGate('setup_required');
expect(screen.getByText(i18n.t('backend.setup_torch_dll_init_failed'))).toBeVisible();
delete backendStatus.setupIssue;
});
it('shows download guidance on a failed setup', () => {
backendStatus.message = 'Runtime setup exited with code 1';
backendStatus.failure = { code: 'RUNTIME_DOWNLOAD_INTERRUPTED', stage: 'setup_required' };
@@ -407,7 +407,10 @@ export function BackendGate({ children, repairDock }: BackendGateProps) {
{t('backend.setup_unsupported_platform')}
</p>
) : null}
{running ? (
{/* Only while the Python environment is actually being prepared (first
run or repair). Ordinary launches also pass through `starting` and
`attaching`; the long-wait wording is false there (#4228). */}
{installing ? (
<p className="text-sm text-foreground/65">{t('backend.first_run_hint')}</p>
) : null}
{cause ? (
@@ -2077,6 +2077,7 @@
"setup_wrong_architecture": "أغلق VoiceStudio واستبدله بملف DMG لإصدار Apple Silicon ‏(arm64)، ثم افتحه مجددًا. الإصدار الحالي مخصص لـ Intel ويعمل عبر Rosetta؛ تبديله يتيح الذكاء الاصطناعي المحلي مع إبقاء الأصوات والمشاريع.",
"setup_missing_system_library": "ينقص هذا النظام من Windows حزمة Microsoft Visual C++ 2015-2022 Redistributable (x64) التي يحتاجها امتداد الصوت في PyTorch. ثبّتها من Microsoft ثم اضغط «إعادة المحاولة».",
"setup_outdated_system_library": "حزمة Microsoft Visual C++ Redistributable (x64) على نظام Windows هذا قديمة جدًا، لذا تتعطل مكتبة كلام عند تحميلها. ثبّت أحدث إصدار من Microsoft ثم اضغط «إعادة المحاولة».",
"setup_torch_dll_init_failed": "تعذّر تحميل PyTorch ولم يتم تحديد السبب. ثبّت أحدث إصدار من Microsoft Visual C++ Redistributable (x64)، ثم حدّث تعريف بطاقة الرسومات، ثم اضغط إعادة المحاولة. إذا استمر الفشل، فاستخدم \"تنظيف وإعادة المحاولة\" ضمن \"حلول أخرى\".",
"setup_files_locked": "يستخدم برنامج آخر ملفات VoiceStudio (OneDrive أو تطبيق مزامنة آخر، أو برنامج مكافحة الفيروسات، أو خادم VoiceStudio لا يزال يعمل). أغلقه أو أوقف المزامنة مؤقتًا ثم اضغط «إعادة المحاولة».",
"download_apple_silicon": "تنزيل نسخة Apple Silicon",
"ready": "المحرك جاهز",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "Beende VoiceStudio, ersetze es durch das Apple-Silicon-DMG (arm64) und starte es neu. Derzeit läuft die Intel-Ausgabe über Rosetta; der Wechsel aktiviert lokale KI und lässt Stimmen sowie Projekte unangetastet.",
"setup_missing_system_library": "Auf diesem Windows-System fehlt das Microsoft Visual C++ 2015-2022 Redistributable (x64), das die PyTorch-Audioerweiterung benötigt. Installiere es von Microsoft und drücke dann auf „Erneut versuchen“.",
"setup_outdated_system_library": "Das Microsoft Visual C++ Redistributable (x64) auf diesem Windows-System ist zu alt, deshalb stürzt eine Sprachbibliothek beim Laden ab. Installiere die neueste Version von Microsoft und drücke dann auf „Erneut versuchen“.",
"setup_torch_dll_init_failed": "PyTorch konnte nicht geladen werden, die Ursache ist nicht geklärt. Installiere das neueste Microsoft Visual C++ Redistributable (x64), aktualisiere dann den Grafiktreiber und drücke auf „Erneut versuchen“. Hilft das nicht, nutze „Bereinigen & Wiederholen“ unter „Weitere Lösungen“.",
"setup_files_locked": "Ein anderes Programm verwendet die Dateien von VoiceStudio (OneDrive oder eine andere Sync-App, ein Virenscanner oder ein noch laufendes VoiceStudio-Backend). Schließe es oder pausiere die Synchronisierung und drücke dann auf „Erneut versuchen“.",
"download_apple_silicon": "Apple-Silicon-Version herunterladen",
"ready": "Engine bereit",
@@ -383,7 +383,8 @@
"setup_unsupported_platform": "Connect this app to a remote backend below. PyTorch is not released for Intel macOS, so this Mac needs no local backend installation.",
"setup_wrong_architecture": "Quit VoiceStudio, replace it with the Apple Silicon (arm64) DMG, then open it again. You are running the Intel build through Rosetta; switching builds enables local AI without removing voices or projects.",
"setup_missing_system_library": "This Windows system is missing the Microsoft Visual C++ 2015-2022 Redistributable (x64), which the PyTorch audio extension needs. Install it from Microsoft, then press Retry.",
"setup_outdated_system_library": "This Windows system's Microsoft Visual C++ Redistributable (x64) is too old, so a speech library crashes when it loads. Install the latest version from Microsoft, then press Retry.",
"setup_outdated_system_library": "This Windows system's Microsoft Visual C++ Redistributable (x64) is too old or damaged, so PyTorch or a speech library fails to load. Install the latest version from Microsoft, then press Retry.",
"setup_torch_dll_init_failed": "PyTorch could not load, and the cause is not established. Try installing the latest Microsoft Visual C++ Redistributable (x64), then updating your graphics driver, then press Retry. If it still fails, use \"Clean & Retry\" under \"More fixes\".",
"setup_files_locked": "Another program is using VoiceStudio's files (OneDrive or another sync app, antivirus, or a VoiceStudio backend that is still running). Close it or pause syncing, then press Retry.",
"download_apple_silicon": "Download the Apple Silicon build",
"proxy_bypass_help": "Fully quit VoiceStudio, set HTTP_PROXY/HTTPS_PROXY to your proxy URL and NO_PROXY to excluded hosts in a terminal, then launch VoiceStudio from that terminal. Retrying in the current app cannot load new environment variables.",
@@ -2031,6 +2031,7 @@
"setup_wrong_architecture": "Cierra VoiceStudio, sustitúyelo por el DMG de Apple Silicon (arm64) y ábrelo de nuevo. Ahora se está usando la edición Intel mediante Rosetta; el cambio habilita la IA local sin borrar voces ni proyectos.",
"setup_missing_system_library": "A este sistema Windows le falta el Microsoft Visual C++ 2015-2022 Redistributable (x64), que necesita la extensión de audio de PyTorch. Instálalo desde Microsoft y pulsa Reintentar.",
"setup_outdated_system_library": "El Microsoft Visual C++ Redistributable (x64) de este sistema Windows es demasiado antiguo, por lo que una biblioteca de voz falla al cargarse. Instala la versión más reciente desde Microsoft y pulsa Reintentar.",
"setup_torch_dll_init_failed": "PyTorch no se pudo cargar y la causa no está establecida. Instala el último Microsoft Visual C++ Redistributable (x64), después actualiza el controlador de la tarjeta gráfica y pulsa Reintentar. Si sigue fallando, usa «Limpiar y reintentar» en «Más soluciones».",
"setup_files_locked": "Otro programa está usando los archivos de VoiceStudio (OneDrive u otra app de sincronización, el antivirus o un backend de VoiceStudio que sigue en ejecución). Ciérralo o pausa la sincronización y pulsa Reintentar.",
"download_apple_silicon": "Descargar la versión para Apple Silicon",
"ready": "Motor listo",
@@ -2031,6 +2031,7 @@
"setup_wrong_architecture": "Fermez VoiceStudio, remplacez-le par le DMG Apple Silicon (arm64), puis relancez-le. L’édition Intel fonctionne actuellement sous Rosetta ; changer d’édition active l’IA locale sans toucher aux voix ni aux projets.",
"setup_missing_system_library": "Ce système Windows ne dispose pas du Microsoft Visual C++ 2015-2022 Redistributable (x64), dont l’extension audio PyTorch a besoin. Installez-le depuis Microsoft, puis cliquez sur Réessayer.",
"setup_outdated_system_library": "Le Microsoft Visual C++ Redistributable (x64) de ce système Windows est trop ancien : une bibliothèque vocale plante à son chargement. Installez la dernière version depuis Microsoft, puis cliquez sur Réessayer.",
"setup_torch_dll_init_failed": "PyTorch n'a pas pu se charger et la cause n'est pas établie. Installez le dernier Microsoft Visual C++ Redistributable (x64), puis mettez à jour votre pilote graphique, puis appuyez sur Réessayer. Si cela échoue encore, utilisez « Nettoyer et réessayer » dans « Autres solutions ».",
"setup_files_locked": "Un autre programme utilise les fichiers de VoiceStudio (OneDrive ou une autre application de synchronisation, l’antivirus, ou un backend VoiceStudio encore en cours d’exécution). Fermez-le ou suspendez la synchronisation, puis cliquez sur Réessayer.",
"download_apple_silicon": "Télécharger la version Apple Silicon",
"ready": "Moteur prêt",
@@ -384,6 +384,7 @@
"setup_wrong_architecture": "Sae de VoiceStudio, substitúeo polo Apple Silicon (arm64) DMG e, a continuación, ábreo de novo. Estás executando a compilación de Intel a través de Rosetta; o cambio de compilación permite a IA local sen eliminar voces ou proxectos.",
"setup_missing_system_library": "Este sistema Windows carece do Microsoft Visual C++ 2015-2022 Redistributable (x64), que necesita a extensión de audio PyTorch. Instálao desde Microsoft e, a continuación, prema Reintentar.",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) deste sistema Windows é demasiado antigo, polo que unha biblioteca de voz falla cando se carga. Instala a versión máis recente de Microsoft e, a continuación, preme Retry.",
"setup_torch_dll_init_failed": "Non se puido cargar PyTorch e a causa non está establecida. Instala o último Microsoft Visual C++ Redistributable (x64), despois actualiza o controlador gráfico e preme Tentar de novo. Se aínda falla, usa «Limpar e tentar de novo» en «Máis solucións».",
"setup_files_locked": "Outro programa está a usar os ficheiros de VoiceStudio (OneDrive ou outra aplicación de sincronización, antivirus ou un backend de VoiceStudio que aínda está en execución). Péchao ou fai unha pausa na sincronización e, a continuación, preme Reintentar.",
"download_apple_silicon": "Descarga a versión de Apple Silicon",
"proxy_bypass_help": "Sae totalmente de VoiceStudio, configure HTTP_PROXY/HTTPS_PROXY no URL do seu proxy e NO_PROXY para os hosts excluídos nun terminal e, a continuación, inicie VoiceStudio desde ese terminal. Volver tentar na aplicación actual non se poden cargar novas variables de ambiente.",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "यह VoiceStudio का Intel (x64) बिल्ड है जो Apple Silicon Mac पर Rosetta के ज़रिए चल रहा है, इसलिए लोकल AI बैकएंड इंस्टॉल नहीं हो सकता। ऐप बंद करें, इसके ऊपर Apple Silicon (arm64) DMG इंस्टॉल करें और फिर से खोलें — आपकी आवाज़ें और प्रोजेक्ट सुरक्षित रहेंगे।",
"setup_missing_system_library": "इस Windows सिस्टम पर Microsoft Visual C++ 2015-2022 Redistributable (x64) नहीं है, जिसकी PyTorch ऑडियो एक्सटेंशन को ज़रूरत है। इसे Microsoft से इंस्टॉल करें, फिर «पुनः प्रयास करें» दबाएँ।",
"setup_outdated_system_library": "इस Windows सिस्टम पर Microsoft Visual C++ Redistributable (x64) बहुत पुराना है, इसलिए एक स्पीच लाइब्रेरी लोड होते समय क्रैश हो जाती है। Microsoft से नवीनतम संस्करण इंस्टॉल करें, फिर «पुनः प्रयास करें» दबाएँ।",
"setup_torch_dll_init_failed": "PyTorch लोड नहीं हो सका और कारण स्पष्ट नहीं है। नवीनतम Microsoft Visual C++ Redistributable (x64) इंस्टॉल करें, फिर ग्राफ़िक्स ड्राइवर अपडेट करें और पुनः प्रयास दबाएँ। फिर भी विफल हो तो \"अन्य समाधान\" में \"साफ़ करें और पुनः प्रयास करें\" का उपयोग करें।",
"setup_files_locked": "कोई दूसरा प्रोग्राम VoiceStudio की फ़ाइलों का उपयोग कर रहा है (OneDrive या कोई अन्य सिंक ऐप, एंटीवायरस, या अभी भी चल रहा VoiceStudio बैकएंड)। उसे बंद करें या सिंक रोकें, फिर «पुनः प्रयास करें» दबाएँ।",
"download_apple_silicon": "Apple Silicon बिल्ड डाउनलोड करें",
"ready": "इंजन तैयार है",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "Tutup VoiceStudio, ganti dengan DMG Apple Silicon (arm64), lalu buka lagi. Saat ini edisi Intel berjalan melalui Rosetta; penggantian edisi mengaktifkan AI lokal tanpa menghapus suara atau proyek.",
"setup_missing_system_library": "Sistem Windows ini tidak memiliki Microsoft Visual C++ 2015-2022 Redistributable (x64), yang dibutuhkan ekstensi audio PyTorch. Pasang dari Microsoft, lalu tekan Coba Lagi.",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) di sistem Windows ini terlalu lama, sehingga sebuah pustaka suara mogok saat dimuat. Pasang versi terbaru dari Microsoft, lalu tekan Coba Lagi.",
"setup_torch_dll_init_failed": "PyTorch tidak dapat dimuat dan penyebabnya belum dipastikan. Pasang Microsoft Visual C++ Redistributable (x64) terbaru, lalu perbarui driver grafis, kemudian tekan Coba lagi. Jika masih gagal, gunakan \"Bersihkan & Coba Lagi\" di \"Solusi lain\".",
"setup_files_locked": "Program lain sedang menggunakan file VoiceStudio (OneDrive atau aplikasi sinkronisasi lain, antivirus, atau backend VoiceStudio yang masih berjalan). Tutup program itu atau jeda sinkronisasi, lalu tekan Coba Lagi.",
"download_apple_silicon": "Unduh build Apple Silicon",
"ready": "Mesin siap",
@@ -2031,6 +2031,7 @@
"setup_wrong_architecture": "Chiudi VoiceStudio, sostituiscilo con il DMG Apple Silicon (arm64), quindi riaprilo. Al momento è in uso l’edizione Intel tramite Rosetta; il cambio abilita l’IA locale senza cancellare voci o progetti.",
"setup_missing_system_library": "Questo sistema Windows non ha il Microsoft Visual C++ 2015-2022 Redistributable (x64), necessario all’estensione audio di PyTorch. Installalo da Microsoft, poi premi Riprova.",
"setup_outdated_system_library": "Il Microsoft Visual C++ Redistributable (x64) di questo sistema Windows è troppo vecchio, quindi una libreria vocale si arresta al caricamento. Installa la versione più recente da Microsoft, poi premi Riprova.",
"setup_torch_dll_init_failed": "Impossibile caricare PyTorch e la causa non è stata stabilita. Installa l'ultimo Microsoft Visual C++ Redistributable (x64), poi aggiorna il driver della scheda video e premi Riprova. Se continua a fallire, usa «Pulisci e riprova» in «Altre soluzioni».",
"setup_files_locked": "Un altro programma sta usando i file di VoiceStudio (OneDrive o un’altra app di sincronizzazione, l’antivirus o un backend VoiceStudio ancora in esecuzione). Chiudilo o metti in pausa la sincronizzazione, poi premi Riprova.",
"download_apple_silicon": "Scarica la versione Apple Silicon",
"retry": "Riprova",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "VoiceStudio を終了し、Apple Silicon(arm64)版 DMG に置き換えてから再起動してください。現在は Intel 版が Rosetta 経由で動作しています。版を切り替えてもボイスやプロジェクトは消えず、ローカル AI が利用可能になります。",
"setup_missing_system_library": "この Windows システムには、PyTorch の音声拡張に必要な Microsoft Visual C++ 2015-2022 再頒布可能パッケージ (x64) が入っていません。Microsoft からインストールしてから、再試行を押してください。",
"setup_outdated_system_library": "この Windows システムの Microsoft Visual C++ 再頒布可能パッケージ (x64) が古いため、音声ライブラリの読み込み時にクラッシュします。Microsoft から最新版をインストールしてから、再試行を押してください。",
"setup_torch_dll_init_failed": "PyTorch を読み込めませんでした。原因は特定できていません。最新の Microsoft Visual C++ 再頒布可能パッケージ (x64) をインストールし、次にグラフィックドライバーを更新してから、再試行を押してください。それでも失敗する場合は、「その他の解決策」の「クリーンアップして再試行」を使ってください。",
"setup_files_locked": "別のプログラムが VoiceStudio のファイルを使用しています(OneDrive などの同期アプリ、ウイルス対策ソフト、または実行中のままの VoiceStudio バックエンド)。そのプログラムを閉じるか同期を一時停止してから、再試行を押してください。",
"download_apple_silicon": "Apple Silicon 版をダウンロード",
"ready": "エンジン準備完了",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "VoiceStudio를 종료하고 Apple Silicon(arm64) DMG로 교체한 다음 다시 실행하세요. 현재 Intel판이 Rosetta를 통해 동작 중입니다. 버전을 바꾸면 음성과 프로젝트를 지우지 않고 로컬 AI를 사용할 수 있습니다.",
"setup_missing_system_library": "이 Windows 시스템에 PyTorch 오디오 확장이 필요로 하는 Microsoft Visual C++ 2015-2022 재 배포 가능한 패키지(x64)가 없습니다. Microsoft에서 설치한 뒤 다시 시도하세요.",
"setup_outdated_system_library": "이 Windows 시스템의 Microsoft Visual C++ 재배포 가능 패키지(x64)가 너무 오래되어 음성 라이브러리가 로드될 때 충돌합니다. Microsoft에서 최신 버전을 설치한 뒤 다시 시도하세요.",
"setup_torch_dll_init_failed": "PyTorch를 불러오지 못했고 원인은 확인되지 않았습니다. 최신 Microsoft Visual C++ 재배포 가능 패키지(x64)를 설치하고, 그래픽 드라이버를 업데이트한 뒤 다시 시도를 누르세요. 계속 실패하면 \"다른 해결 방법\"의 \"정리 후 재시도\"를 사용하세요.",
"setup_files_locked": "다른 프로그램이 VoiceStudio 파일을 사용하고 있습니다(OneDrive 또는 다른 동기화 앱, 백신 프로그램, 아직 실행 중인 VoiceStudio 백엔드). 해당 프로그램을 닫거나 동기화를 일시 중지한 뒤 다시 시도하세요.",
"download_apple_silicon": "Apple Silicon 빌드 다운로드",
"ready": "엔진 준비 완료",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "Sluit VoiceStudio, vervang het door de Apple Silicon-DMG (arm64) en start opnieuw. Nu draait de Intel-editie via Rosetta; na de wissel werkt lokale AI en blijven stemmen en projecten behouden.",
"setup_missing_system_library": "Op dit Windows-systeem ontbreekt het Microsoft Visual C++ 2015-2022 Redistributable (x64) dat de PyTorch-audio-extensie nodig heeft. Installeer het via Microsoft en druk daarna op Opnieuw proberen.",
"setup_outdated_system_library": "Het Microsoft Visual C++ Redistributable (x64) op dit Windows-systeem is te oud, waardoor een spraakbibliotheek crasht bij het laden. Installeer de nieuwste versie via Microsoft en druk daarna op Opnieuw proberen.",
"setup_torch_dll_init_failed": "PyTorch kon niet worden geladen en de oorzaak is niet vastgesteld. Installeer de nieuwste Microsoft Visual C++ Redistributable (x64), werk daarna je grafische driver bij en kies Opnieuw proberen. Mislukt het nog steeds, gebruik dan \"Wissen & Opnieuw proberen\" onder \"Meer oplossingen\".",
"setup_files_locked": "Een ander programma gebruikt de bestanden van VoiceStudio (OneDrive of een andere sync-app, antivirus, of een VoiceStudio-backend die nog draait). Sluit het of pauzeer de synchronisatie en druk daarna op Opnieuw proberen.",
"download_apple_silicon": "Apple Silicon-versie downloaden",
"ready": "Engine gereed",
@@ -2053,6 +2053,7 @@
"setup_wrong_architecture": "Zamknij VoiceStudio, zastąp go obrazem DMG dla Apple Silicon (arm64) i uruchom ponownie. Obecnie edycja Intel działa przez Rosetta; zmiana włączy lokalną AI bez usuwania głosów ani projektów.",
"setup_missing_system_library": "W tym systemie Windows brakuje pakietu Microsoft Visual C++ 2015-2022 Redistributable (x64), którego potrzebuje rozszerzenie audio PyTorch. Zainstaluj go ze strony Microsoft, a następnie naciśnij Ponów.",
"setup_outdated_system_library": "Pakiet Microsoft Visual C++ Redistributable (x64) w tym systemie Windows jest zbyt stary, więc biblioteka mowy ulega awarii podczas ładowania. Zainstaluj najnowszą wersję ze strony Microsoft, a następnie naciśnij Ponów.",
"setup_torch_dll_init_failed": "Nie udało się załadować PyTorch, a przyczyna nie jest ustalona. Zainstaluj najnowszy Microsoft Visual C++ Redistributable (x64), następnie zaktualizuj sterownik karty graficznej i naciśnij Ponów. Jeśli nadal się nie udaje, użyj „Wyczyść i ponów” w „Inne rozwiązania”.",
"setup_files_locked": "Inny program używa plików VoiceStudio (OneDrive lub inna aplikacja synchronizująca, antywirus albo wciąż działający backend VoiceStudio). Zamknij go lub wstrzymaj synchronizację, a następnie naciśnij Ponów.",
"download_apple_silicon": "Pobierz wersję dla Apple Silicon",
"ready": "Silnik gotowy",
@@ -2031,6 +2031,7 @@
"setup_wrong_architecture": "Esta é a versão Intel (x64) do VoiceStudio executada pelo Rosetta num Mac com Apple Silicon, por isso o backend de IA local não pode ser instalado. Feche o app, instale por cima o DMG para Apple Silicon (arm64) e abra-o novamente — suas vozes e projetos são mantidos.",
"setup_missing_system_library": "Este sistema Windows não tem o Microsoft Visual C++ 2015-2022 Redistributable (x64), de que a extensão de áudio do PyTorch precisa. Instale-o a partir da Microsoft e prima Tentar novamente.",
"setup_outdated_system_library": "O Microsoft Visual C++ Redistributable (x64) deste sistema Windows é demasiado antigo, por isso uma biblioteca de voz falha ao carregar. Instale a versão mais recente a partir da Microsoft e prima Tentar novamente.",
"setup_torch_dll_init_failed": "Não foi possível carregar o PyTorch e a causa não foi determinada. Instale o Microsoft Visual C++ Redistributable (x64) mais recente, depois atualize o driver da placa de vídeo e toque em Tentar novamente. Se ainda falhar, use \"Limpar e Repetir\" em \"Mais soluções\".",
"setup_files_locked": "Outro programa está a usar os ficheiros do VoiceStudio (OneDrive ou outra app de sincronização, antivírus, ou um backend do VoiceStudio ainda em execução). Feche-o ou pause a sincronização e prima Tentar novamente.",
"download_apple_silicon": "Baixar a versão para Apple Silicon",
"ready": "Motor pronto",
@@ -2053,6 +2053,7 @@
"setup_wrong_architecture": "Закройте VoiceStudio, замените его версией DMG для Apple Silicon (arm64) и запустите снова. Сейчас Intel-версия работает через Rosetta; после замены локальный ИИ станет доступен, а голоса и проекты сохранятся.",
"setup_missing_system_library": "В этой системе Windows отсутствует Microsoft Visual C++ 2015-2022 Redistributable (x64), который нужен аудиорасширению PyTorch. Установите его с сайта Microsoft и нажмите «Повторить».",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) в этой системе Windows слишком старый, поэтому речевая библиотека аварийно завершается при загрузке. Установите последнюю версию с сайта Microsoft и нажмите «Повторить».",
"setup_torch_dll_init_failed": "Не удалось загрузить PyTorch, причина не установлена. Установите последнюю версию Microsoft Visual C++ Redistributable (x64), затем обновите драйвер видеокарты и нажмите «Повторить». Если ошибка остаётся, используйте «Очистить и повторить» в разделе «Другие решения».",
"setup_files_locked": "Другая программа использует файлы VoiceStudio (OneDrive или другое приложение синхронизации, антивирус или всё ещё работающий бэкенд VoiceStudio). Закройте её или приостановите синхронизацию и нажмите «Повторить».",
"download_apple_silicon": "Скачать версию для Apple Silicon",
"ready": "Движок готов",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "Det här är Intel-versionen (x64) av VoiceStudio som körs via Rosetta på en Mac med Apple Silicon, så den lokala AI-backenden kan inte installeras. Avsluta appen, installera Apple Silicon-DMG:n (arm64) ovanpå och öppna den igen – dina röster och projekt finns kvar.",
"setup_missing_system_library": "Det här Windows-systemet saknar Microsoft Visual C++ 2015-2022 Redistributable (x64), som PyTorch ljudextensionen behöver. Installera det från Microsoft och tryck sedan på Försök igen.",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) på det här Windows-systemet är för gammalt, så ett talbibliotek kraschar när det läses in. Installera den senaste versionen från Microsoft och tryck sedan på Försök igen.",
"setup_torch_dll_init_failed": "PyTorch kunde inte läsas in och orsaken är inte fastställd. Installera den senaste Microsoft Visual C++ Redistributable (x64), uppdatera sedan grafikdrivrutinen och tryck på Försök igen. Om det fortfarande misslyckas, använd \"Rensa & Försök igen\" under \"Fler lösningar\".",
"setup_files_locked": "Ett annat program använder VoiceStudios filer (OneDrive eller en annan synkapp, antivirus eller en VoiceStudio-backend som fortfarande körs). Stäng det eller pausa synkroniseringen och tryck sedan på Försök igen.",
"download_apple_silicon": "Ladda ned Apple Silicon-versionen",
"retry": "Försök igen",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "ปิด VoiceStudio เปลี่ยนเป็น DMG รุ่น Apple Silicon (arm64) แล้วเปิดใหม่ ขณะนี้รุ่น Intel ทำงานผ่าน Rosetta; การเปลี่ยนรุ่นจะเปิดใช้ AI ในเครื่องโดยไม่ลบเสียงหรือโปรเจกต์",
"setup_missing_system_library": "ระบบ Windows นี้ไม่มี Microsoft Visual C++ 2015-2022 Redistributable (x64) ซึ่งส่วนขยายเสียงของ PyTorch ต้องใช้ ติดตั้งจาก Microsoft แล้วกดลองใหม่",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) บนระบบ Windows นี้เก่าเกินไป ไลบรารีเสียงจึงขัดข้องขณะโหลด ติดตั้งเวอร์ชันล่าสุดจาก Microsoft แล้วกดลองใหม่",
"setup_torch_dll_init_failed": "โหลด PyTorch ไม่ได้และยังไม่ทราบสาเหตุ ติดตั้ง Microsoft Visual C++ Redistributable (x64) เวอร์ชันล่าสุด จากนั้นอัปเดตไดรเวอร์การ์ดจอ แล้วกดลองอีกครั้ง หากยังล้มเหลว ให้ใช้ \"ล้างข้อมูลและลองใหม่\" ใน \"วิธีแก้ไขอื่น\"",
"setup_files_locked": "มีโปรแกรมอื่นกำลังใช้ไฟล์ของ VoiceStudio (OneDrive หรือแอปซิงค์อื่น โปรแกรมป้องกันไวรัส หรือแบ็กเอนด์ VoiceStudio ที่ยังทำงานอยู่) ปิดโปรแกรมนั้นหรือหยุดการซิงค์ชั่วคราว แล้วกดลองใหม่",
"download_apple_silicon": "ดาวน์โหลดรุ่น Apple Silicon",
"ready": "เอนจินพร้อม",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "VoiceStudio'yu kapatın, Apple Silicon (arm64) DMG'siyle değiştirin ve yeniden açın. Şu anda Intel sürümü Rosetta üzerinden çalışıyor; sürümü değiştirmek sesleri ve projeleri silmeden yerel yapay zekâyı etkinleştirir.",
"setup_missing_system_library": "Bu Windows sisteminde, PyTorch ses eklentisinin ihtiyaç duyduğu Microsoft Visual C++ 2015-2022 Redistributable (x64) eksik. Microsoft’tan yükleyip Yeniden Dene’ye basın.",
"setup_outdated_system_library": "Bu Windows sistemindeki Microsoft Visual C++ Redistributable (x64) çok eski olduğu için bir konuşma kitaplığı yüklenirken çöküyor. En son sürümü Microsoft’tan yükleyin, ardından Yeniden Dene’ye basın.",
"setup_torch_dll_init_failed": "PyTorch yüklenemedi ve neden belirlenemedi. En son Microsoft Visual C++ Redistributable (x64) sürümünü yükleyin, ardından grafik sürücünüzü güncelleyin ve Yeniden dene'ye basın. Yine de başarısız olursa \"Diğer çözümler\" altındaki \"Temizle ve Yeniden Dene\" seçeneğini kullanın.",
"setup_files_locked": "Başka bir program VoiceStudio dosyalarını kullanıyor (OneDrive veya başka bir eşitleme uygulaması, antivirüs ya da hâlâ çalışan bir VoiceStudio arka ucu). Onu kapatın veya eşitlemeyi duraklatın, ardından Yeniden Dene’ye basın.",
"download_apple_silicon": "Apple Silicon sürümünü indir",
"ready": "Motor hazır",
@@ -2053,6 +2053,7 @@
"setup_wrong_architecture": "Закрийте VoiceStudio, замініть його DMG-версією для Apple Silicon (arm64) і запустіть знову. Зараз Intel-версія працює через Rosetta; після заміни локальний ШІ стане доступним, а голоси й проєкти залишаться.",
"setup_missing_system_library": "У цій системі Windows відсутній Microsoft Visual C++ 2015-2022 Redistributable (x64), потрібний аудіорозширенню PyTorch. Установіть його з Microsoft, а потім натисніть «Повторити».",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) у цій системі Windows застарий, тому мовна бібліотека аварійно завершується під час завантаження. Установіть найновішу версію з сайту Microsoft і натисніть «Повторити».",
"setup_torch_dll_init_failed": "Не вдалося завантажити PyTorch, причину не встановлено. Установіть найновішу версію Microsoft Visual C++ Redistributable (x64), потім оновіть драйвер відеокарти та натисніть «Повторити». Якщо помилка лишається, скористайтеся «Очистити і повторити» у розділі «Інші рішення».",
"setup_files_locked": "Інша програма використовує файли VoiceStudio (OneDrive чи інший застосунок синхронізації, антивірус або бекенд VoiceStudio, що досі працює). Закрийте її або призупиніть синхронізацію й натисніть «Повторити».",
"download_apple_silicon": "Завантажити версію для Apple Silicon",
"ready": "Рушій готовий",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "Hãy đóng VoiceStudio, thay bằng DMG Apple Silicon (arm64), rồi mở lại. Hiện bản Intel đang chạy qua Rosetta; đổi bản sẽ bật AI cục bộ mà không xóa giọng nói hay dự án.",
"setup_missing_system_library": "Hệ thống Windows này thiếu Microsoft Visual C++ 2015-2022 Redistributable (x64), thành phần mà tiện ích âm thanh của PyTorch cần đến. Hãy cài từ Microsoft rồi nhấn Thử lại.",
"setup_outdated_system_library": "Microsoft Visual C++ Redistributable (x64) trên hệ thống Windows này quá cũ nên một thư viện giọng nói bị lỗi khi tải. Hãy cài phiên bản mới nhất từ Microsoft rồi nhấn Thử lại.",
"setup_torch_dll_init_failed": "Không thể tải PyTorch và chưa xác định được nguyên nhân. Hãy cài Microsoft Visual C++ Redistributable (x64) mới nhất, sau đó cập nhật trình điều khiển đồ họa rồi nhấn Thử lại. Nếu vẫn lỗi, hãy dùng \"Dọn dẹp & Thử lại\" trong \"Cách khắc phục khác\".",
"setup_files_locked": "Một chương trình khác đang dùng tệp của VoiceStudio (OneDrive hoặc ứng dụng đồng bộ khác, phần mềm diệt virus, hoặc backend VoiceStudio vẫn đang chạy). Hãy đóng chương trình đó hoặc tạm dừng đồng bộ rồi nhấn Thử lại.",
"download_apple_silicon": "Tải bản Apple Silicon",
"retry": "Thử lại",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "这是通过 Rosetta 在 Apple Silicon Mac 上运行的 VoiceStudio Intel (x64) 版本,因此无法安装本地 AI 后端。请退出应用,覆盖安装 Apple Silicon (arm64) 版 DMG 后重新打开——你的声音和项目都会保留。",
"setup_missing_system_library": "此 Windows 系统缺少 PyTorch 音频扩展所需的 Microsoft Visual C++ 2015-2022 可再分发组件 (x64)。请从 Microsoft 安装后点击重试。",
"setup_outdated_system_library": "此 Windows 系统上的 Microsoft Visual C++ 可再发行组件 (x64) 版本过旧,导致语音库在加载时崩溃。请从 Microsoft 安装最新版本,然后点击重试。",
"setup_torch_dll_init_failed": "PyTorch 无法加载,原因尚未确定。请安装最新的 Microsoft Visual C++ 可再发行组件 (x64),然后更新显卡驱动,再点击重试。如果仍然失败,请使用“更多修复方法”中的“清理并重试”。",
"setup_files_locked": "另一个程序正在使用 VoiceStudio 的文件(OneDrive 或其他同步应用、杀毒软件,或仍在运行的 VoiceStudio 后端)。请关闭该程序或暂停同步,然后点击重试。",
"download_apple_silicon": "下载 Apple Silicon 版本",
"retry": "重试",
@@ -2029,6 +2029,7 @@
"setup_wrong_architecture": "這是透過 Rosetta 在 Apple Silicon Mac 上執行的 VoiceStudio Intel (x64) 版本,因此無法安裝本機 AI 後端。請結束應用程式,覆蓋安裝 Apple Silicon (arm64) 版 DMG 後重新開啟——你的聲音與專案都會保留。",
"setup_missing_system_library": "此 Windows 系統缺少 PyTorch 音訊擴充功能所需的 Microsoft Visual C++ 2015-2022 可再散布元件 (x64)。請從 Microsoft 安裝後按一下重試。",
"setup_outdated_system_library": "此 Windows 系統上的 Microsoft Visual C++ 可轉散發套件 (x64) 版本過舊,導致語音程式庫在載入時當機。請從 Microsoft 安裝最新版本,然後按下重試。",
"setup_torch_dll_init_failed": "PyTorch 無法載入,原因尚未確定。請安裝最新的 Microsoft Visual C++ 可轉散發套件 (x64),接著更新顯示卡驅動程式,再按重試。若仍然失敗,請使用「更多修復方法」中的「清理並重試」。",
"setup_files_locked": "另一個程式正在使用 VoiceStudio 的檔案(OneDrive 或其他同步應用程式、防毒軟體,或仍在執行的 VoiceStudio 後端)。請關閉該程式或暫停同步,然後按下重試。",
"download_apple_silicon": "下載 Apple Silicon 版本",
"ready": "引擎已就緒",
@@ -251,6 +251,24 @@ export function diagnosticFrames(error: unknown): string {
}
}
/** Subclasses report their nearest known built-in base; anything else stays OtherError. */
function knownErrorType(error: unknown, errorName: unknown): string {
if (!(error instanceof Error)) return 'OtherError';
const named =
typeof errorName === 'string' && errorName.length <= 64 && errorTypes.has(errorName)
? errorName
: undefined;
if (named && named !== 'Error') return named;
let proto: unknown = Object.getPrototypeOf(error);
for (let depth = 0; proto && depth < 16; depth++) {
const ctor = (proto as { constructor?: { name?: unknown } }).constructor;
const base = ctor && typeof ctor.name === 'string' ? ctor.name : '';
if (base !== 'Error' && base !== 'OtherError' && errorTypes.has(base)) return base;
proto = Object.getPrototypeOf(proto);
}
return named ?? 'OtherError';
}
/** Typed technical fields only; failure reporting never affects the original operation. */
export function prepareDiagnosticException(
error: unknown,
@@ -288,11 +306,7 @@ export function prepareDiagnosticException(
if (seenErrors.has(error)) return null;
seenErrors.add(error);
}
const observedName = error instanceof Error ? errorName : 'OtherError';
const name =
typeof observedName === 'string' && observedName.length <= 64 && errorTypes.has(observedName)
? observedName
: 'OtherError';
const name = knownErrorType(error, errorName);
const frames = diagnosticFrames(error);
const input: DiagnosticInput = {
category,
@@ -3,6 +3,28 @@ import { classifyInstallFailure, type FailureEvidence, type InstallFailureCode }
// Text from real reports. When an issue reveals a new class, add it here.
const CORPUS: [string, FailureEvidence, InstallFailureCode][] = [
[
'#4230 torch c10.dll failure under a very long runtime path',
{
stage: 'setup_required',
message: 'Runtime setup exited with code 1',
logLines: [
`OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading "D:\\${'a'.repeat(400)}\\torch\\lib\\c10.dll" or one of its dependencies.`,
],
},
'SYSTEM_LIBRARY_PROBLEM',
],
[
'#4230 torch c10.dll initialisation failed (outdated Visual C++ runtime)',
{
stage: 'setup_required',
message: 'Runtime setup exited with code 1; the import check stopped while importing "faster_whisper"',
logLines: [
'OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed. Error loading "~\\AppData\\Roaming\\VoiceStudio\\runtime\\project\\.venv\\Lib\\site-packages\\torch\\lib\\c10.dll" or one of its dependencies.',
],
},
'SYSTEM_LIBRARY_PROBLEM',
],
[
'#3635 Smart App Control confirmed by the reporter',
{ stage: 'failed', message: 'spawn UNKNOWN', smartAppControl: 'on' },
@@ -129,6 +129,7 @@ const SETUP_ISSUE_CODES: Record<string, InstallFailureCode> = {
files_locked: 'RUNTIME_FILES_LOCKED',
missing_system_library: 'SYSTEM_LIBRARY_PROBLEM',
outdated_system_library: 'SYSTEM_LIBRARY_PROBLEM',
torch_dll_init_failed: 'SYSTEM_LIBRARY_PROBLEM',
unsupported_platform: 'UNSUPPORTED_PLATFORM',
wrong_architecture: 'UNSUPPORTED_PLATFORM',
};
@@ -136,6 +137,8 @@ const SETUP_ISSUE_CODES: Record<string, InstallFailureCode> = {
const DOWNLOAD_INTERRUPTED =
/peer closed connection|close_notify|error decoding response body|error sending request|failed to download|failed to fetch|connection (?:reset|closed|refused|timed out)|operation timed out|network (?:is )?unreachable|dns error/i;
const TORCH_DLL_INIT = /WinError 1114[^\r\n]*\btorch[\\/]+lib[\\/]+\w+\.dll/i;
const ILLEGAL_INSTRUCTION = 0xc000001d;
const ACCESS_VIOLATION = 0xc0000005;
const IN_PAGE_ERROR = 0xc0000006;
@@ -185,6 +188,14 @@ export function classifyInstallFailure(evidence: FailureEvidence): InstallFailur
const native = nativeCode(evidence, message);
if (native) return native;
// torch could not initialise c10.dll: the Visual C++ runtime, not the wheels (#4230).
if (
TORCH_DLL_INIT.test(message) ||
lines.some((line) => TORCH_DLL_INIT.test(line)) ||
/Windows could not initialise PyTorch's c10\.dll/.test(message)
)
return 'SYSTEM_LIBRARY_PROBLEM';
if (/Python environment\b.*\b(is missing|is incomplete|missing or incomplete)\b/is.test(message))
return /setup:api/.test(message) ? 'SOURCE_ENV_INCOMPLETE' : 'BROKEN_VENV';
if (/\bENOSPC\b|no space left on device/i.test(message)) return 'DISK_FULL';
+33
View File
@@ -128,6 +128,39 @@ def test_deep_check_success(monkeypatch):
assert "1.0s of audio" in check["detail"]
def test_deep_check_timeout_cancels_the_worker(monkeypatch):
"""#4228: a hung deep synthesis must not keep a sidecar (and the engine
lock and GPU worker it holds) alive once the verdict has shipped."""
import threading
from services.inference_cancellation import current_cancellation
entered = threading.Event()
seen = []
release = threading.Event()
class HungBackend:
sample_rate = 24000
def generate(self, text, **kw):
seen.append(current_cancellation())
entered.set()
release.wait(10)
raise RuntimeError("cancelled")
import services.tts_backend as tb
monkeypatch.setattr(tb, "get_active_tts_backend", lambda model=None: HungBackend())
monkeypatch.setattr(tb, "active_backend_id", lambda: "fake")
monkeypatch.setattr(diagnose, "_DEEP_TIMEOUT_S", 0.5)
try:
check = diagnose._check_deep_synthesis()
assert entered.wait(5)
assert check["status"] == FAIL
assert seen[0] is not None and seen[0].cancelled.is_set()
finally:
release.set()
def test_deep_check_engine_failure(monkeypatch):
import services.tts_backend as tb
def _boom(model=None):
+36
View File
@@ -0,0 +1,36 @@
"""Expected OS/network conditions get a specific closed code, not UNKNOWN."""
import errno
import importlib
import json
from pathlib import Path
import pytest
SCHEMA = json.loads(
(Path(__file__).resolve().parents[1] / "config" / "diagnostics.json").read_text(encoding="utf-8")
)
@pytest.fixture
def reports():
# Resolved per test: another test may replace the sys.modules entry.
return importlib.import_module("core.diagnostic_reports")
@pytest.mark.parametrize("number", [errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN])
def test_unreachable_network_oserror_is_network_error(reports, number):
fields = reports._exception_fields(OSError(number, "private"), reports._schema())
assert fields["error_type"] == "OSError"
assert fields["error_code"] == "NETWORK_ERROR"
def test_disk_full_still_disk_full_and_plain_oserror_stays_unclassified(reports):
schema = reports._schema()
assert reports._exception_fields(OSError(errno.ENOSPC, "x"), schema)["error_code"] == "DISK_FULL"
assert "error_code" not in reports._exception_fields(OSError(errno.EACCES, "x"), schema)
def test_new_codes_are_in_the_closed_policy():
for code in ("GPU_JOB_TIMEOUT", "MAIN_UNCAUGHT_EXCEPTION", "MAIN_UNHANDLED_REJECTION",
"GPU_PROCESS_GONE", "UTILITY_PROCESS_GONE", "OTHER_CHILD_PROCESS_GONE"):
assert code in SCHEMA["error_codes"]
@@ -159,7 +159,7 @@ def test_gpu_deadline_is_compute_failure_and_transport_errors_keep_their_classif
assert saved == []
else:
assert len(saved) == 1
assert saved[0]["props"]["error_code"] == ("UNKNOWN" if failure == "compute" else "NETWORK_ERROR")
assert saved[0]["props"]["error_code"] == ("GPU_JOB_TIMEOUT" if failure == "compute" else "NETWORK_ERROR")
assert saved[0]["props"]["category"] == ("model_load_failed" if entry == "prewarm" else "engine_failed")
assert "private operation detail" not in str(saved)
@@ -273,4 +273,4 @@ def test_local_compute_timeout_classification_is_central(
saved = records(reporter)
assert len(saved) == 1
assert saved[0]["props"]["error_type"] == ("ConnectionError" if kind == "connection" else "TimeoutError")
assert saved[0]["props"]["error_code"] == ("UNKNOWN" if kind in {"compute", "subclass"} else "NETWORK_ERROR")
assert saved[0]["props"]["error_code"] == ("GPU_JOB_TIMEOUT" if kind in {"compute", "subclass"} else "NETWORK_ERROR")
+1 -1
View File
@@ -51,7 +51,7 @@ def test_actual_dub_terminal_error_keeps_one_causal_report(reporter, dub_job_env
rows = reporter._files()
assert len(rows) == 1
assert rows[0]['props']['error_type'] == ('MemoryError' if kind == 'memory' else 'TimeoutError')
assert rows[0]['props']['error_code'] == ('HOST_MEMORY_EXHAUSTED' if kind == 'memory' else 'UNKNOWN')
assert rows[0]['props']['error_code'] == ('HOST_MEMORY_EXHAUSTED' if kind == 'memory' else 'GPU_JOB_TIMEOUT')
assert rows[0]['props']['occurrences'] == 1
assert any('"type": "error"' in event for event in published)
assert all('diagnostic' not in event and 'private' not in event for event in published)
+2 -1
View File
@@ -118,7 +118,8 @@ def test_strict_slot_keeps_full_cache_and_fits_the_tail(render_dub, monkeypatch,
monkeypatch.setattr(dg, "apply_rvc", lambda _: None)
calls=[]
async def stretch(wav, target, sr):
calls.append((wav.shape[-1], target, float(wav[0,-1])))
# Probe just before the 25 ms tail fade (#4229): the loud tail must arrive uncut.
calls.append((wav.shape[-1], target, float(wav[0,-2000])))
return torch.nn.functional.interpolate(wav.unsqueeze(0),size=target,mode='linear').squeeze(0)
monkeypatch.setattr(dg, '_pitch_preserving_stretch', stretch)
events=render_dub.run(timing_strategy='strict_slot')
+16
View File
@@ -88,3 +88,19 @@ def test_openai_speech_trims_edges(openai_tts):
def test_openai_speech_keeps_explicit_duration(openai_tts):
assert openai_tts({"duration": 2.0}).shape[-1] == 2000
def test_trimmed_tail_fades_out_instead_of_cutting(): # #4229
"""A tail that stops while still audible must end near zero, not on a step."""
audio = torch.cat([torch.full((1, 1000), 0.5), torch.full((1, 200), 0.3)], dim=-1)
out = dsp.trim_speech_padding(audio, SR * 24)
assert abs(float(out[0, -1])) < 0.01
assert float(out[0, 0]) == 0.5
assert out.shape[-1] == audio.shape[-1]
def test_fade_leaves_quiet_tail_and_length_alone():
audio = torch.cat([torch.zeros(1, 100), torch.full((1, 500), 0.5), torch.zeros(1, 400)], dim=-1)
out = dsp.trim_speech_padding(audio, SR)
assert out.shape[-1] == 500 + 2 * MARGIN
assert float(out[0, -1]) == 0.0
@@ -461,6 +461,7 @@ def test_generating_heartbeats_are_not_credited_as_model_load_progress(mm, monke
{"op": "progress", "stage": "loading_model", "percent": 1},
{"op": "progress", "stage": "generating", "percent": 2},
{"op": "progress", "stage": "generating", "percent": 3},
{"op": "progress", "stage": "reference_asr", "percent": 0},
{"op": "audio", "audio_pcm_b64": "", "sample_rate": 24000, "n_samples": 0},
]
monkeypatch.setattr(b, "_spawn", lambda: None)
@@ -112,3 +112,97 @@ def test_prefetch_stops_when_the_real_load_starts(tmp_path):
def test_prefetch_never_raises_for_a_missing_checkpoint(tmp_path):
sidecar._prefetch_weights(str(tmp_path / "does-not-exist"), threading.Event())
sidecar._prefetch_weights("not-an-installed/repo-id", threading.Event())
def _recording_send(monkeypatch, frames, beats=2):
"""Record frames; `reached` is set once `beats` progress frames arrived."""
reached = threading.Event()
monkeypatch.setattr(sidecar, "_LOAD_HEARTBEAT_S", 0.01)
def send(_stream, obj):
frames.append(obj)
if sum(1 for f in frames if f["op"] == "progress") >= beats:
reached.set()
monkeypatch.setattr(sidecar, "_send", send)
return reached
def test_heartbeating_emits_progress_while_the_body_is_silent(monkeypatch):
# #4228: any silent phase past the parent's 300s recv deadline kills the sidecar.
sent = []
reached = _recording_send(monkeypatch, sent)
with sidecar._heartbeating(None, "generating"):
assert reached.wait(5), "no heartbeat while the body was silent"
assert all(f["op"] == "progress" and f["stage"] == "generating" for f in sent)
# The beater is joined on exit: nothing is sent afterwards.
count = len(sent)
assert not [t for t in threading.enumerate() if t.name == "omnivoice-generating-heartbeat"]
assert len(sent) == count
def test_synthesis_heartbeats_while_model_generate_runs(monkeypatch):
frames = []
reached = _recording_send(monkeypatch, frames)
class Model:
sampling_rate = 24000
def generate(self, **_kw):
assert reached.wait(5), "no heartbeat during generate"
return [object()]
monkeypatch.setattr(sidecar, "_tensor_to_pcm_b64", lambda *_a, **_k: ("", 24000, 0))
monkeypatch.setattr(sidecar, "_load_model", lambda _s: Model())
sidecar._handle_synthesize({"text": "hello"}, None)
assert frames[-1]["op"] == "audio"
assert any(f["op"] == "progress" and f["stage"] == "generating" for f in frames)
def test_cold_load_heartbeats_through_the_imports_before_from_pretrained(monkeypatch):
# The imports and checkpoint resolution ahead of from_pretrained were silent.
frames = []
reached = _recording_send(monkeypatch, frames)
monkeypatch.setattr(sidecar, "_model", None)
def slow_construct(_stdout, progress):
assert reached.wait(5), "no heartbeat during the cold load"
return "model"
monkeypatch.setattr(sidecar, "_construct_model", slow_construct)
assert sidecar._load_model(None) == "model"
assert any(f["stage"] == "loading_model" for f in frames)
def test_reference_transcription_heartbeats_with_an_uncredited_stage(monkeypatch):
# The parent credits "loading_model" as cold-load time, so a stalled
# transcription must use a stage it does not credit (#4228).
from services import subprocess_backend as sb
frames = []
reached = _recording_send(monkeypatch, frames)
monkeypatch.setattr(sidecar, "_ensure_backend_on_path", lambda: None)
import services.asr_backend as asr
import services.tts_backend as tts
def transcribe(_ref, release_after=True):
assert reached.wait(5), "no heartbeat during reference transcription"
return "words"
monkeypatch.setattr(asr, "transcribe_reference", transcribe)
monkeypatch.setattr(tts, "reference_duration_s", lambda _r: 1.0)
monkeypatch.setattr(tts, "has_unresolved_clone_prompt", lambda *_a: False)
monkeypatch.setattr(sidecar, "_tensor_to_pcm_b64", lambda *_a, **_k: ("", 24000, 0))
class Model:
sampling_rate = 24000
def generate(self, **_kw):
return [object()]
monkeypatch.setattr(sidecar, "_load_model", lambda _s: Model())
sidecar._handle_synthesize({"text": "hi", "ref_audio": "ref.wav"}, None)
stages = {f["stage"] for f in frames if f["op"] == "progress"}
assert "reference_asr" in stages
assert "reference_asr" in sb._UNCREDITED_PROGRESS_STAGES
assert "loading_model" not in sb._UNCREDITED_PROGRESS_STAGES
+1 -1
View File
@@ -159,7 +159,7 @@ def test_get_best_device_installs_it_on_an_xpu_host(monkeypatch):
@pytest.mark.parametrize("rel,loader", [
("backend/services/model_manager.py", "def _load_model_sync("),
("backend/engines/omnivoice_subprocess/main.py", "def _load_model("),
("backend/engines/omnivoice_subprocess/main.py", "def _construct_model("),
])
def test_omnivoice_loaders_pick_the_device_before_loading(rel, loader):
"""get_best_device() installs the fallback, so it has to run before