mirror of
https://github.com/debpalash/VoiceStudio.git
synced 2026-12-04 01:18:16 +00:00
Restart a crashed engine, ask before quitting running work, keep the batch queue across restarts (#4623)
* feat(desktop): restart a crashed engine, ask before quitting running work, keep the batch queue across restarts - A local engine that crashed after it had started restarts on its own (1, 3, 6, 12, 30 s); a sixth crash in ten minutes, or a crash before it ever started, stays on the recovery screen. - A quit the user starts asks first while the engine reports running work; confirmed update installs, OS shutdown and relaunches do not ask. - Unfinished batch jobs keep a record beside their upload and are queued again, in order, on the next backend start. - Interrupted audiobook/story renders are announced once after launch with a Resume action. * changelog: add fragment for #4623 * test(dub): wait for the voice search to take focus * fix(desktop): close the gaps review found in job resume and the quit prompt - Quitting during a generation, clone, design or transcription now asks first: the engine reports open requests that do work, not just jobs. - Restart on CPU withdraws a pending automatic restart before it saves the device choice, so the engine cannot start on the old device. - Batch queue records hold only the upload's name, so they carry no home path and still restore after the data folder moves. - A save racing a cancel, a job skipped as cancelled, or a record that cannot be deleted no longer brings finished or cancelled work back. - One malformed record is dropped on its own instead of stopping every saved job from restoring. - A queued or restored job whose speech model was removed fails with the enqueue message instead of downloading it. - The interrupted-render notice retries a failed check a few times.
This commit is contained in:
1 parent
5f73c1c625
commit
d6bd82844c
50 files changed
+1255
-25
No files matched your search
@@ -4,11 +4,16 @@ This is a lightweight batch orchestrator. Each job is a dub project that
|
||||
runs through the same ingest→transcribe→translate→generate pipeline as
|
||||
a manual dub, but driven by the queue instead of the UI.
|
||||
|
||||
The queue is in-memory (lives for the process lifetime). Jobs persist to
|
||||
the SQLite `jobs` table for history, but the queue itself restarts empty
|
||||
on backend restart — intentional, since GPU jobs can't be safely resumed.
|
||||
The queue runs in memory. Each job that has not finished also keeps a small
|
||||
record beside its upload (``<job_id>.queued.json``), so a quit, crash or update
|
||||
restart does not drop the rest of a long batch: the next backend start queues
|
||||
those jobs again, in their original order, from their saved upload and
|
||||
settings. A job that was mid-pipeline starts over (its partial outputs are
|
||||
reset), since GPU work cannot be resumed mid-stage. Finishing, failing,
|
||||
cancelling or deleting a job removes its record.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import shutil
|
||||
import uuid
|
||||
@@ -28,6 +33,7 @@ from core import failure, voice_leases
|
||||
from core.logging_utils import log_safe
|
||||
from core.media_types import media_upload_suffix
|
||||
from core.path_security import contained_join, portable_filename
|
||||
from core.durable_io import flush_dir, flush_fd
|
||||
from core.file_cleanup import FileCleanupError, unlink_if_present
|
||||
from services.dub_batching import (
|
||||
BATCH_WIDTH_ENV,
|
||||
@@ -69,6 +75,173 @@ _job_reservations: set[str] = set()
|
||||
_reservation_lock = threading.Lock()
|
||||
_jobs: dict = {} # job_id → status dict
|
||||
|
||||
# ── Durable queue records ───────────────────────────────────────────────
|
||||
|
||||
_RECORD_SUFFIX = ".queued.json"
|
||||
# Settings needed to run a job again; progress and results are rebuilt.
|
||||
_RECORD_FIELDS = (
|
||||
"id", "filename", "video_path", "langs", "voice_id", "preserve_bg",
|
||||
"translation_provider", "created_at", "attempts",
|
||||
)
|
||||
# Server-generated ids (uuid4 prefix). Anything else in the folder is not ours.
|
||||
_JOB_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
||||
_TERMINAL = frozenset({"done", "failed", "cancelled"})
|
||||
|
||||
|
||||
def _batch_root() -> str:
|
||||
return os.path.realpath(os.path.join(DATA_DIR, "batch"))
|
||||
|
||||
|
||||
def _record_path(job_id: str) -> Optional[str]:
|
||||
if not _JOB_ID_RE.match(job_id or ""):
|
||||
return None
|
||||
return os.path.join(_batch_root(), os.path.basename(f"{job_id}{_RECORD_SUFFIX}"))
|
||||
|
||||
|
||||
def _write_record(path: str, record: dict) -> None:
|
||||
tmp = f"{path}.tmp"
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0), 0o600)
|
||||
try:
|
||||
os.write(fd, json.dumps(record).encode("utf-8"))
|
||||
flush_fd(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
os.replace(tmp, path)
|
||||
flush_dir(os.path.dirname(path))
|
||||
except OSError:
|
||||
logger.warning("Could not save the batch queue record for %s", log_safe(record.get("id")), exc_info=True)
|
||||
|
||||
|
||||
def _save_record(job: dict) -> None:
|
||||
"""Write the job's queue record atomically. Best-effort: never fails a job."""
|
||||
path = _record_path(job.get("id", ""))
|
||||
if path is None:
|
||||
return
|
||||
record = {key: job.get(key) for key in _RECORD_FIELDS}
|
||||
# Only the upload's name: the record never holds a home path, and a data
|
||||
# folder moved elsewhere still finds its uploads.
|
||||
record["video_path"] = os.path.basename(job.get("video_path") or "")
|
||||
_write_record(path, record)
|
||||
# A cancel that ran during the write already removed the record; the write
|
||||
# must not bring back work the user cancelled.
|
||||
if job.get("status") in _TERMINAL:
|
||||
_discard_record(job["id"])
|
||||
|
||||
|
||||
def _discard_record(job_id: str) -> None:
|
||||
path = _record_path(job_id)
|
||||
if path is None:
|
||||
return
|
||||
try:
|
||||
unlink_if_present(path)
|
||||
except FileCleanupError:
|
||||
logger.warning("Could not remove the batch queue record for %s", log_safe(job_id), exc_info=True)
|
||||
# A record left behind would run the job again (and clear its results)
|
||||
# on the next start; mark it finished so restoring skips it.
|
||||
_write_record(path, {"id": job_id, "finished": True})
|
||||
|
||||
|
||||
def _load_records() -> list[dict]:
|
||||
"""Saved jobs whose upload still exists, oldest first. Unusable records are removed."""
|
||||
root = _batch_root()
|
||||
try:
|
||||
names = os.listdir(root)
|
||||
except OSError:
|
||||
return []
|
||||
records = []
|
||||
for name in names:
|
||||
if not name.endswith(_RECORD_SUFFIX):
|
||||
continue
|
||||
job_id = name[: -len(_RECORD_SUFFIX)]
|
||||
if not _JOB_ID_RE.match(job_id):
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(root, name), encoding="utf-8") as handle:
|
||||
record = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
record = None
|
||||
record = _usable_record(record, job_id, root)
|
||||
if record is None:
|
||||
_discard_record(job_id)
|
||||
continue
|
||||
records.append(record)
|
||||
records.sort(key=lambda r: r["created_at"])
|
||||
return records
|
||||
|
||||
|
||||
def _is_number(value) -> bool:
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def _usable_record(record, job_id: str, root: str) -> Optional[dict]:
|
||||
"""The record with checked, normalised fields, or None to drop only it."""
|
||||
if not isinstance(record, dict) or record.get("id") != job_id or record.get("finished"):
|
||||
return None
|
||||
langs = record.get("langs")
|
||||
if not isinstance(langs, list) or not langs or not all(isinstance(x, str) and x for x in langs):
|
||||
return None
|
||||
name = record.get("video_path")
|
||||
if not isinstance(name, str) or not name:
|
||||
return None
|
||||
# The upload is found by name in the current batch folder (older records
|
||||
# held a full path), confined there and owned by this job.
|
||||
video = os.path.realpath(os.path.join(root, os.path.basename(name)))
|
||||
if (
|
||||
os.path.dirname(video) != root
|
||||
or not os.path.basename(video).startswith(job_id)
|
||||
or not os.path.isfile(video)
|
||||
):
|
||||
return None
|
||||
created_at = record.get("created_at")
|
||||
attempts = record.get("attempts", 1)
|
||||
if not _is_number(created_at) or not isinstance(attempts, int) or isinstance(attempts, bool) or attempts < 1:
|
||||
return None
|
||||
for key in ("filename", "voice_id", "translation_provider"):
|
||||
if record.get(key) is not None and not isinstance(record[key], str):
|
||||
return None
|
||||
return {**record, "video_path": video, "created_at": float(created_at)}
|
||||
|
||||
|
||||
async def restore_interrupted_jobs() -> int:
|
||||
"""Queue again every job the previous backend did not finish. Returns the count."""
|
||||
records = await asyncio.to_thread(_load_records)
|
||||
restored = 0
|
||||
for record in records:
|
||||
job_id = record["id"]
|
||||
if job_id in _jobs:
|
||||
continue
|
||||
output_dir = os.path.join(_batch_root(), job_id)
|
||||
try:
|
||||
if os.path.isdir(output_dir):
|
||||
await asyncio.to_thread(shutil.rmtree, output_dir)
|
||||
except OSError:
|
||||
logger.warning("Could not reset batch outputs for %s; it will overwrite them", log_safe(job_id))
|
||||
_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"status": "queued",
|
||||
"filename": record.get("filename") or os.path.basename(record["video_path"]),
|
||||
"video_path": record["video_path"],
|
||||
"langs": [str(lang) for lang in record["langs"]],
|
||||
"voice_id": record.get("voice_id"),
|
||||
"preserve_bg": bool(record.get("preserve_bg", True)),
|
||||
"translation_provider": record.get("translation_provider") or "argos",
|
||||
"created_at": record["created_at"],
|
||||
"attempts": record.get("attempts", 1),
|
||||
"started_at": None,
|
||||
"finished_at": None,
|
||||
"error": None,
|
||||
"progress": None,
|
||||
"restored": True,
|
||||
}
|
||||
_ensure_queue()
|
||||
await _queue.put(job_id)
|
||||
restored += 1
|
||||
if restored:
|
||||
logger.info("Batch: queued %d job(s) the previous run did not finish.", restored)
|
||||
return restored
|
||||
|
||||
from core import activity as _activity # noqa: E402
|
||||
|
||||
_activity.register_probe("batch", lambda: any(
|
||||
@@ -92,6 +265,8 @@ class BatchJobStatus(BaseModel):
|
||||
attempts: int = 1
|
||||
retry_ready: bool = True
|
||||
setup_required: Optional[dict] = None
|
||||
#: Queued again after the backend restarted before the job finished.
|
||||
restored: bool = False
|
||||
|
||||
|
||||
def _ensure_queue():
|
||||
@@ -108,6 +283,8 @@ async def _worker():
|
||||
job_id = await _queue.get()
|
||||
job = _jobs.get(job_id)
|
||||
if not job or job["status"] == "cancelled":
|
||||
# A record a racing save left behind must not run it next start.
|
||||
_discard_record(job_id)
|
||||
_queue.task_done()
|
||||
continue
|
||||
|
||||
@@ -117,6 +294,7 @@ async def _worker():
|
||||
logger.info("Batch job %s starting: %s", job_id, job["filename"])
|
||||
from core import diagnostic_reports
|
||||
diagnostic_epoch = diagnostic_reports.observe_grant()
|
||||
shutting_down = False
|
||||
|
||||
# Each new job owns its grant independently of the request that
|
||||
# created this long-lived worker. Delayed failures keep that owner.
|
||||
@@ -142,6 +320,9 @@ async def _worker():
|
||||
# the in-flight job, then let the cancellation propagate.
|
||||
job["status"] = "cancelled"
|
||||
job["finished_at"] = time.time()
|
||||
# The backend is stopping, not the user: keep the queue record
|
||||
# so the next start runs this job again.
|
||||
shutting_down = True
|
||||
raise
|
||||
except Exception as e:
|
||||
if job["status"] == "cancelled":
|
||||
@@ -165,6 +346,8 @@ async def _worker():
|
||||
_processing_job_ids.discard(job_id)
|
||||
if job["status"] == "cancelled":
|
||||
job["retry_ready"] = True
|
||||
if not shutting_down and job["status"] in ("done", "failed", "cancelled"):
|
||||
_discard_record(job_id)
|
||||
_queue.task_done()
|
||||
|
||||
|
||||
@@ -356,6 +539,14 @@ async def _run_batch_pipeline_leased(job_id: str, job: dict, lease: voice_leases
|
||||
segment_transcript, assign_speakers_heuristic,
|
||||
)
|
||||
|
||||
# A job queued earlier, or restored after a restart, may find the speech
|
||||
# model removed since it was accepted: fail it with the message enqueue
|
||||
# gives, instead of letting the transcriber download the weights unasked.
|
||||
from services.asr_backend import asr_model_missing_detail, asr_model_missing_error
|
||||
missing = await asyncio.to_thread(asr_model_missing_error)
|
||||
if missing is not None:
|
||||
raise RuntimeError(asr_model_missing_detail(missing))
|
||||
|
||||
def _transcribe():
|
||||
# `load_*`, not `get_*`: the plain selector returns engines whose
|
||||
# shallow probe passed but whose deep import chain is broken, failing
|
||||
@@ -918,6 +1109,7 @@ async def enqueue_batch_job(
|
||||
"progress": None,
|
||||
}
|
||||
_jobs[job_id] = job
|
||||
await asyncio.to_thread(_save_record, job)
|
||||
await _queue.put(job_id)
|
||||
|
||||
logger.info(
|
||||
@@ -964,6 +1156,7 @@ def cancel_batch_job(job_id: str):
|
||||
job["status"] = "cancelled"
|
||||
job["retry_ready"] = not was_running
|
||||
job["finished_at"] = time.time()
|
||||
_discard_record(job_id)
|
||||
return {"cancelled": True}
|
||||
|
||||
|
||||
@@ -1058,6 +1251,7 @@ async def _admit_retry(job_id: str, job: dict):
|
||||
"progress": None,
|
||||
"attempts": int(job.get("attempts", 1)) + 1,
|
||||
})
|
||||
await asyncio.to_thread(_save_record, job)
|
||||
_ensure_queue()
|
||||
await _queue.put(job_id)
|
||||
return {"job_id": job_id, "status": "queued", "queue_position": _queue.qsize()}
|
||||
@@ -1111,6 +1305,7 @@ def _delete_job_files(job_id: str, job: dict):
|
||||
status_code=500,
|
||||
detail="Could not delete the batch output files. Close any app using them and retry.",
|
||||
) from exc
|
||||
_discard_record(job_id)
|
||||
_jobs.pop(job_id, None)
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ _PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity",
|
||||
|
||||
_lock = threading.Lock()
|
||||
_inflight = 0
|
||||
# Open HTTP requests that change something (a generation, a transcription, a
|
||||
# render stream): unlike reads and WebSocket sessions, quitting would cut them.
|
||||
_work_requests = 0
|
||||
# Reads change nothing, so quitting mid-read loses nothing.
|
||||
_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
_last_activity = time.monotonic()
|
||||
_probes: dict[str, Callable[[], bool]] = {}
|
||||
|
||||
@@ -38,23 +43,26 @@ def touch() -> None:
|
||||
_last_activity = time.monotonic()
|
||||
|
||||
|
||||
def _enter() -> None:
|
||||
global _inflight, _last_activity
|
||||
def _enter(work: bool = False) -> None:
|
||||
global _inflight, _work_requests, _last_activity
|
||||
with _lock:
|
||||
_inflight += 1
|
||||
_work_requests += work
|
||||
_last_activity = time.monotonic()
|
||||
|
||||
|
||||
def _leave() -> None:
|
||||
global _inflight, _last_activity
|
||||
def _leave(work: bool = False) -> None:
|
||||
global _inflight, _work_requests, _last_activity
|
||||
with _lock:
|
||||
_inflight -= 1
|
||||
_work_requests -= work
|
||||
_last_activity = time.monotonic()
|
||||
|
||||
|
||||
def snapshot() -> dict:
|
||||
with _lock:
|
||||
inflight = _inflight
|
||||
work_requests = _work_requests
|
||||
idle = time.monotonic() - _last_activity
|
||||
probes = list(_probes.items())
|
||||
busy = []
|
||||
@@ -68,7 +76,12 @@ def snapshot() -> dict:
|
||||
busy.append(name)
|
||||
if inflight or busy:
|
||||
idle = 0.0
|
||||
return {"inflight": inflight, "busy": sorted(busy), "idle_seconds": round(idle, 1)}
|
||||
return {
|
||||
"inflight": inflight,
|
||||
"work_requests": work_requests,
|
||||
"busy": sorted(busy),
|
||||
"idle_seconds": round(idle, 1),
|
||||
}
|
||||
|
||||
|
||||
class ActivityMiddleware:
|
||||
@@ -81,8 +94,9 @@ class ActivityMiddleware:
|
||||
if scope["type"] not in {"http", "websocket"} or scope.get("path") in _PASSIVE_PATHS:
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
_enter()
|
||||
work = scope["type"] == "http" and scope.get("method", "GET") not in _READ_METHODS
|
||||
_enter(work)
|
||||
try:
|
||||
await self.app(scope, receive, send)
|
||||
finally:
|
||||
_leave()
|
||||
_leave(work)
|
||||
@@ -1185,6 +1185,13 @@ async def _phase_b(app: FastAPI) -> None:
|
||||
await _await_profile_reconcile(app)
|
||||
app.state.idle_task = asyncio.create_task(idle_worker())
|
||||
app.state.worker_task = asyncio.create_task(task_manager.worker())
|
||||
# Batches a quit, crash or update restart cut short continue where they were.
|
||||
try:
|
||||
from api.routers import batch as batch_router
|
||||
|
||||
await batch_router.restore_interrupted_jobs()
|
||||
except Exception:
|
||||
logger.exception("Restoring the batch queue failed (non-fatal).")
|
||||
# Warm the TTS model in the background so first /generate is instant.
|
||||
_start_tts_preload(app)
|
||||
# Dictation v2: capture ASR warms in the background BY DEFAULT (~30s
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
A crashed local engine restarts on its own, quitting asks first while work is running, and unfinished batch jobs continue after a restart (#4623)
|
||||
@@ -13,9 +13,12 @@ Add to Queue stays at the bottom of the pane while the file list scrolls.
|
||||
Active, Completed and Failed views poll backend jobs. Progress shows backend stages
|
||||
and percentages. Active jobs can be cancelled; finished records require an inline
|
||||
confirmation before deletion. Completed language outputs use the native save dialog.
|
||||
Reloading the renderer reads existing jobs and never re-enqueues them. Backend
|
||||
process restart recovery is not established by this behavior: the batch queue is
|
||||
in memory. Native watch folders detect settled files through a capability-scoped
|
||||
Reloading the renderer reads existing jobs and never re-enqueues them. Jobs that
|
||||
have not finished survive a quit, crash or update restart: each keeps a small
|
||||
record beside its upload, and the next backend start queues them again in their
|
||||
original order. A job that was mid-pipeline starts over, with its partial outputs
|
||||
reset. Finishing, failing, cancelling or deleting a job removes its record.
|
||||
Quitting while a batch or another task runs asks first (see `electron-runtime.md`). Native watch folders detect settled files through a capability-scoped
|
||||
directory handle and stream multipart uploads directly to the selected local or
|
||||
HTTPS remote backend. Remote uploads receive the scoped session from Electron main;
|
||||
the renderer never handles it.
|
||||
|
||||
@@ -78,6 +78,11 @@ of the journal. Opening the details marks that crash seen and clears its repair-
|
||||
while retaining the evidence for bug reports; a later crash starts unacknowledged. `node electron/tests/native-crash-journal-smoke.mjs` exercises that complete native
|
||||
process/relaunch path with an isolated profile.
|
||||
|
||||
An engine that crashed after it had started serving is restarted automatically, after 1, 3, 6, 12
|
||||
and 30 seconds for consecutive crashes. A sixth crash within ten minutes stays on the recovery
|
||||
screen, as does a crash before the engine ever started (those repeat, and the screen names the
|
||||
fix). The screen says when an automatic restart is pending; Retry or Restart on CPU replaces it.
|
||||
|
||||
A fresh Windows environment has also completed a real frozen dependency installation and import check. The current packaged app repaired the isolated runtime after its dependency manifest changed, started backend 0.5.2, then relaunched against the same runtime without setup; renderer, preload bridge and same-origin API passed, and deliberate shutdown removed the run sentinel. A separate empty-runtime, empty-uv-cache and empty-Hugging-Face-cache run completed dependency setup, required-model download, onboarding and a paused 341804-byte first-sound WAV before shutting down cleanly. The segmented model downloader keeps both the canonical cache blob and snapshot pointer on Windows, using a hard link when symlinks are unavailable, so model loading does not download the same multi-gigabyte weight again.
|
||||
|
||||
Ubuntu 26.04 under WSL completed the current frozen dependency graph from an empty uv cache: 227 packages and a 7.9 GiB runtime. The current unpacked Linux package used its bundled uv 0.12.13, completed that explicit runtime installation from empty dependency and model caches, downloaded the 3,267,470,260-byte required OmniVoice model to a host-backed cache after preflight correctly rejected the space-constrained WSL disk, loaded it on the RTX 4090, and produced a paused 341,804-byte first-sound WAV before shutting down cleanly. A clean AppImage profile also completed the visible explicit setup action from the dependency cache and connected its packaged renderer to backend 0.5.2 under WSLg Wayland. The same profile relaunched without installation, reused its managed runtime, and cleared the backend run sentinel on both deliberate exits. These runs exposed and fixed Electron's missing POSIX nested-operation ownership descriptor.
|
||||
@@ -86,7 +91,7 @@ Remaining verification: fully uncached packaged installation through first gener
|
||||
|
||||
Deliberate shutdown remains available during deferred native and ML imports. Electron can therefore retire the backend run sentinel before Windows performs its bounded process-tree termination, so closing during “Preparing GPU libraries” does not become a false crash warning on the next launch. A packaged Windows acceptance quits inside that gated startup phase and verifies the sentinel is gone.
|
||||
|
||||
Closing the window quits the app on Windows and Linux and keeps it running on macOS. Settings → General → "Keep running in the tray when closed" (off by default, saved in `window-prefs.json` in the user-data folder) makes the close button hide the window to the system tray on every platform instead, so running jobs and the backend keep going; the tray icon reopens the window and its Quit entry exits through the normal orderly shutdown. Explicit quits (tray Quit, Cmd+Q, installing an update, Windows log off or shutdown) are never turned into a hide, and a terminal-started app without a window keeps its own idle shutdown. On Linux desktops that hide tray icons (for example GNOME without an AppIndicator extension), launching VoiceStudio again also reopens the hidden window.
|
||||
Closing the window quits the app on Windows and Linux and keeps it running on macOS. Settings → General → "Keep running in the tray when closed" (off by default, saved in `window-prefs.json` in the user-data folder) makes the close button hide the window to the system tray on every platform instead, so running jobs and the backend keep going; the tray icon reopens the window and its Quit entry exits through the normal orderly shutdown. Explicit quits (tray Quit, Cmd+Q, installing an update, Windows log off or shutdown) are never turned into a hide. When the local engine reports running work (a render, dub, batch, model download or engine install, or a generation or transcription it is still answering), a quit you start asks first, with Keep working as the default; an update install you already confirmed, an OS log off or shutdown, and a relaunch do not ask. After a launch, an interrupted audiobook or story render is announced once with a Resume action that opens its page. A terminal-started app without a window keeps its own idle shutdown. On Linux desktops that hide tray icons (for example GNOME without an AppIndicator extension), launching VoiceStudio again also reopens the hidden window.
|
||||
|
||||
The backend's default desktop origins include `app://voicestudio` alongside the Tauri origins. HTTP CORS and WebSocket checks share this list. An explicit `OMNIVOICE_ALLOWED_ORIGINS` overrides the defaults; deployments using it must include the Electron origin to allow native live dictation. Non-loopback WebSocket connections still require remote authorization.
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, it } from 'vitest';
|
||||
import {
|
||||
AUTO_RESTART_DELAYS_MS,
|
||||
AUTO_RESTART_WINDOW_MS,
|
||||
AutoRestartBudget,
|
||||
} from './backend-auto-restart';
|
||||
|
||||
it('backs off through the schedule, then stops at the crash-loop limit', () => {
|
||||
const budget = new AutoRestartBudget();
|
||||
const waits = AUTO_RESTART_DELAYS_MS.map((_, index) => budget.next(index * 1000));
|
||||
expect(waits).toEqual([...AUTO_RESTART_DELAYS_MS]);
|
||||
expect(budget.next(10_000)).toBeNull();
|
||||
});
|
||||
|
||||
it('forgets restarts once they leave the crash window', () => {
|
||||
const budget = new AutoRestartBudget();
|
||||
for (let i = 0; i < AUTO_RESTART_DELAYS_MS.length; i++) budget.next(0);
|
||||
expect(budget.next(AUTO_RESTART_WINDOW_MS)).toBe(AUTO_RESTART_DELAYS_MS[0]);
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Automatic restart of a local engine that crashed after it had started.
|
||||
*
|
||||
* Without it a crash mid-session left the app on the failure screen until the
|
||||
* user pressed Retry, even when the cause was transient (a GPU out-of-memory
|
||||
* kill, a driver reset). The schedule backs off and stops after a short run of
|
||||
* restarts, so a deterministic crash still reaches the failure screen instead
|
||||
* of looping.
|
||||
*/
|
||||
|
||||
/** Wait before each automatic restart inside one crash window. */
|
||||
export const AUTO_RESTART_DELAYS_MS = [1_000, 3_000, 6_000, 12_000, 30_000] as const;
|
||||
/** Restarts older than this no longer count toward the crash-loop limit. */
|
||||
export const AUTO_RESTART_WINDOW_MS = 10 * 60_000;
|
||||
|
||||
export class AutoRestartBudget {
|
||||
private attempts: number[] = [];
|
||||
|
||||
/** The wait before the next automatic restart, or null once the limit is reached. */
|
||||
next(now: number): number | null {
|
||||
this.attempts = this.attempts.filter((at) => now - at < AUTO_RESTART_WINDOW_MS);
|
||||
const wait = AUTO_RESTART_DELAYS_MS[this.attempts.length];
|
||||
if (wait === undefined) return null;
|
||||
this.attempts.push(now);
|
||||
return wait;
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ const mocks = vi.hoisted(() => ({
|
||||
spawn: vi.fn(),
|
||||
inFlight: vi.fn(async (_cache: string) => 0),
|
||||
hosts: vi.fn(async () => new Map<string, string>()),
|
||||
pinCpu: vi.fn(async (_dataDir: string) => {}),
|
||||
}));
|
||||
vi.mock('./compute-device-pref', () => ({ pinComputeDeviceToCpu: mocks.pinCpu }));
|
||||
vi.mock('electron', () => ({ app: { isPackaged: true, getPath: () => '/private/voicestudio' } }));
|
||||
// The setup screen's hardware line follows the torch choice in the environment.
|
||||
// Probes stay pending until a test settles them, so a race can be ordered.
|
||||
@@ -1291,6 +1293,139 @@ it('exposes the current process signal separately from the durable crash journal
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('restarts an engine that crashed after it was serving, then stops at the crash-loop limit', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));
|
||||
const supervisor = new BackendSupervisor();
|
||||
const internal = supervisor as unknown as {
|
||||
generation: number;
|
||||
readyGeneration: number;
|
||||
restart: () => Promise<void>;
|
||||
recoverAfterChildExit: (
|
||||
gen: number,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
) => Promise<void>;
|
||||
};
|
||||
const restart = vi.fn(async () => {
|
||||
internal.generation++;
|
||||
});
|
||||
internal.restart = restart;
|
||||
const crashAfterServing = async () => {
|
||||
const gen = internal.generation;
|
||||
internal.readyGeneration = gen;
|
||||
const recovery = internal.recoverAfterChildExit(gen, null, 'SIGKILL');
|
||||
await vi.advanceTimersByTimeAsync(10_500);
|
||||
expect(supervisor.status.stage).toBe('crashed');
|
||||
expect(supervisor.status.autoRestartAt).toBeTypeOf('number');
|
||||
await vi.advanceTimersByTimeAsync(31_000);
|
||||
await recovery;
|
||||
};
|
||||
internal.generation = 1;
|
||||
for (let attempt = 1; attempt <= 5; attempt++) {
|
||||
await crashAfterServing();
|
||||
expect(restart).toHaveBeenCalledTimes(attempt);
|
||||
}
|
||||
// A sixth crash inside the window is a crash loop: the failure screen stays.
|
||||
const gen = internal.generation;
|
||||
internal.readyGeneration = gen;
|
||||
const recovery = internal.recoverAfterChildExit(gen, null, 'SIGKILL');
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
await recovery;
|
||||
expect(restart).toHaveBeenCalledTimes(5);
|
||||
expect(supervisor.status.stage).toBe('crashed');
|
||||
expect(supervisor.status.autoRestartAt).toBeUndefined();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('leaves an engine that crashed before it ever served on the failure screen', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));
|
||||
const supervisor = new BackendSupervisor();
|
||||
const internal = supervisor as unknown as {
|
||||
generation: number;
|
||||
restart: () => Promise<void>;
|
||||
recoverAfterChildExit: (
|
||||
gen: number,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
) => Promise<void>;
|
||||
};
|
||||
const restart = vi.fn(async () => {});
|
||||
internal.restart = restart;
|
||||
internal.generation = 1;
|
||||
const recovery = internal.recoverAfterChildExit(1, 1, null);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
await recovery;
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
expect(supervisor.status.autoRestartAt).toBeUndefined();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('lets Retry during the wait replace the automatic restart', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));
|
||||
const supervisor = new BackendSupervisor();
|
||||
const internal = supervisor as unknown as {
|
||||
generation: number;
|
||||
readyGeneration: number;
|
||||
restart: () => Promise<void>;
|
||||
recoverAfterChildExit: (
|
||||
gen: number,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
) => Promise<void>;
|
||||
};
|
||||
const restart = vi.fn(async () => {});
|
||||
internal.restart = restart;
|
||||
internal.generation = 1;
|
||||
internal.readyGeneration = 1;
|
||||
const recovery = internal.recoverAfterChildExit(1, null, 'SIGKILL');
|
||||
await vi.advanceTimersByTimeAsync(10_500);
|
||||
internal.generation++; // the user pressed Retry
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await recovery;
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('lets Restart on CPU replace the automatic restart while it saves the choice', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));
|
||||
const supervisor = new BackendSupervisor();
|
||||
const internal = supervisor as unknown as {
|
||||
generation: number;
|
||||
readyGeneration: number;
|
||||
restart: () => Promise<void>;
|
||||
recoverAfterChildExit: (
|
||||
gen: number,
|
||||
code: number | null,
|
||||
signal: NodeJS.Signals | null,
|
||||
) => Promise<void>;
|
||||
};
|
||||
const restart = vi.fn(async () => {});
|
||||
internal.restart = restart;
|
||||
internal.generation = 1;
|
||||
internal.readyGeneration = 1;
|
||||
const recovery = internal.recoverAfterChildExit(1, null, 'SIGKILL');
|
||||
await vi.advanceTimersByTimeAsync(10_500);
|
||||
expect(supervisor.status.autoRestartAt).toBeTypeOf('number');
|
||||
// Restart on CPU begins while its preference write is still pending; the
|
||||
// automatic restart must not start the engine on the old device meanwhile.
|
||||
(internal as unknown as { launchLog: unknown }).launchLog = { env: {}, cwd: '/tmp' };
|
||||
let saved!: () => void;
|
||||
mocks.pinCpu.mockImplementationOnce(() => new Promise<void>((resolve) => (saved = resolve)));
|
||||
const cpu = supervisor.restartOnCpu();
|
||||
expect(supervisor.status.autoRestartAt).toBeUndefined();
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await recovery;
|
||||
expect(restart).not.toHaveBeenCalled();
|
||||
saved();
|
||||
await cpu;
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function impersonateHost(identity: { platform: NodeJS.Platform; arch: string }): void {
|
||||
const originals = new Map(
|
||||
['platform', 'arch'].map((property) => [
|
||||
|
||||
@@ -57,6 +57,7 @@ import { bundledPython, bundledRuntimeEnv } from './bundled-runtime';
|
||||
import { asciiSafePthFiles } from './pth-ascii';
|
||||
import { devProbeStamped, writeDevProbeStamp } from './dev-probe-stamp';
|
||||
import { applyWeightLoadFallback, CrashJournal } from './crash-journal';
|
||||
import { AutoRestartBudget } from './backend-auto-restart';
|
||||
import { pinComputeDeviceToCpu } from './compute-device-pref';
|
||||
import { nativeFaultSummary } from '../shared/utils/crashReport';
|
||||
import {
|
||||
@@ -1285,6 +1286,11 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
private exitCode: number | null | undefined;
|
||||
private exitSignal: string | null | undefined;
|
||||
private startedAt = Date.now();
|
||||
/** The ownership generation that last reached `ready`. */
|
||||
private readyGeneration = -1;
|
||||
private readonly autoRestarts = new AutoRestartBudget();
|
||||
/** When the pending automatic restart of a crashed engine runs (epoch ms). */
|
||||
private autoRestartAt: number | undefined;
|
||||
private child: ChildProcess | null = null;
|
||||
/** The last spawned backend's pid: Windows names a crash's faulting module by it. */
|
||||
private childPid: number | undefined;
|
||||
@@ -1544,6 +1550,8 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
}
|
||||
if (this.cpuSetupAvailable()) status.cpuSetupAvailable = true;
|
||||
if (this.cpuRestartAvailable()) status.cpuRestartAvailable = true;
|
||||
if (this.stage === 'crashed' && this.autoRestartAt !== undefined)
|
||||
status.autoRestartAt = this.autoRestartAt;
|
||||
if (/^(1|true|yes|on)$/i.test((process.env.OMNIVOICE_ANALYTICS_DISABLED ?? '').trim()))
|
||||
status.analyticsDisabled = true;
|
||||
if (this.diagnosis) status.diagnosis = this.diagnosis;
|
||||
@@ -2213,6 +2221,10 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
const launch = this.launchLog;
|
||||
if (!this.cpuRestartAvailable() || !launch)
|
||||
throw new Error('Restart on CPU is only available after the local engine crashed');
|
||||
// This restart replaces a pending automatic one, which could otherwise
|
||||
// start the engine on the old device while the preference is written.
|
||||
this.autoRestartAt = undefined;
|
||||
this.emitStatus();
|
||||
await pinComputeDeviceToCpu(backendDataDir(launch));
|
||||
this.pushLog(
|
||||
'out',
|
||||
@@ -2397,6 +2409,7 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
} = {},
|
||||
): void {
|
||||
this.stage = stage;
|
||||
if (stage !== 'crashed') this.autoRestartAt = undefined;
|
||||
this.diagnosis = patch.diagnosis;
|
||||
if ('managed' in patch) this.managed = patch.managed ?? false;
|
||||
if ('message' in patch) this.message = patch.message;
|
||||
@@ -2895,6 +2908,11 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
void this.setupRuntime();
|
||||
return;
|
||||
}
|
||||
// An engine that was serving and then died is restarted on its own, with
|
||||
// backoff and a crash-loop limit. One that never started is not: that
|
||||
// crash repeats, and its failure screen names the fix.
|
||||
const wait = this.readyGeneration === gen ? this.autoRestarts.next(exitedAt) : null;
|
||||
if (wait !== null) this.autoRestartAt = Date.now() + wait;
|
||||
this.setStage('crashed', {
|
||||
// The child was ours: the failure belongs to the managed runtime, and a
|
||||
// report that says "Managed: false" sends the triage the wrong way.
|
||||
@@ -2903,6 +2921,20 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
? `Backend failed to start during '${startup.step}' (${why}): ${startup.reason}`
|
||||
: `Backend exited unexpectedly (${why}).${lastLine ? ` Last output: ${lastLine}` : ''}${stderrTail(this.childErrorLog)}`,
|
||||
});
|
||||
if (wait === null) return;
|
||||
const crashedGeneration = this.generation;
|
||||
const scheduled = this.autoRestartAt;
|
||||
await delay(wait);
|
||||
// Retry, Restart on CPU or quitting during the wait takes over.
|
||||
if (
|
||||
crashedGeneration !== this.generation ||
|
||||
this.shuttingDown ||
|
||||
this.stage !== 'crashed' ||
|
||||
this.autoRestartAt !== scheduled
|
||||
)
|
||||
return;
|
||||
this.pushLog('out', `Restarting the engine automatically after the crash (${why}).`);
|
||||
await this.restart();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3059,6 +3091,7 @@ export class BackendSupervisor extends EventEmitter<{
|
||||
// A healthy run must not leave import errors behind: a later unrelated
|
||||
// exit would otherwise match them and be misread as a broken runtime.
|
||||
this.childErrorLog.length = 0;
|
||||
this.readyGeneration = gen;
|
||||
this.setStage('ready', patch);
|
||||
} else if (credentials === 'rejected') {
|
||||
if (this.diagnosis !== 'auth_required' || this.stage !== 'failed') {
|
||||
|
||||
@@ -152,9 +152,13 @@ describe('recovery when the tray icon is missing', () => {
|
||||
});
|
||||
|
||||
it('never lets the hide handler swallow an explicit quit', () => {
|
||||
// before-quit starts the orderly quit, which marks quitPreparation before the
|
||||
// window's close event runs; the close handler then decides "quit", never "hide".
|
||||
expect(source).toMatch(/app\.on\('before-quit'[\s\S]*?beginOrderlyQuit\(\)/);
|
||||
// before-quit cancels the default quit and runs the user-quit path (which may
|
||||
// ask about running work first), then the orderly quit marks quitPreparation;
|
||||
// the close handler then decides "quit", never "hide".
|
||||
expect(source).toMatch(
|
||||
/app\.on\('before-quit'[\s\S]*?event\.preventDefault\(\);\s*requestUserQuit\(\)/,
|
||||
);
|
||||
expect(source).toMatch(/function requestUserQuit\(\)[\s\S]*?beginOrderlyQuit\(\)/);
|
||||
expect(source).toMatch(/quitRequested: sessionEnding \|\| quitPreparation !== null/);
|
||||
expect(source).toMatch(/win\.on\('session-end'[\s\S]*?sessionEnding = true/);
|
||||
expect(decide({ closeToTray: true, quitRequested: true })).toBe('quit');
|
||||
|
||||
@@ -61,7 +61,13 @@ export function relaunchArguments(intent: LaunchIntent, currentArgv: readonly st
|
||||
];
|
||||
}
|
||||
|
||||
export type BackendActivity = { inflight: number; busy: string[]; idle_seconds: number };
|
||||
export type BackendActivity = {
|
||||
inflight: number;
|
||||
busy: string[];
|
||||
idle_seconds: number;
|
||||
/** Open requests that do work (a generation, a transcription); older engines omit it. */
|
||||
work_requests?: number;
|
||||
};
|
||||
|
||||
/** Stages where the backend is (re)starting or installing: never idle. */
|
||||
const STARTING: ReadonlySet<BackendStage> = new Set(['attaching', 'starting', 'installing']);
|
||||
|
||||
@@ -31,6 +31,13 @@ import { assertTrustedMainFrame, registerIpc, wireWindowMaximizeEvents } from '.
|
||||
import { APP_ORIGIN, installAppProtocol, registerAppScheme } from './protocol';
|
||||
import { electronProxyPort, startDevBackendProxy } from './dev-backend-proxy';
|
||||
import { DesktopUpdater, registerUpdateIpc } from './updater';
|
||||
import {
|
||||
busyForQuit,
|
||||
createQuitGuard,
|
||||
DEFAULT_QUIT_GUARD_LABELS,
|
||||
parseQuitGuardLabels,
|
||||
type QuitGuardLabels,
|
||||
} from './quit-guard';
|
||||
import { scheduleUpdateChecks } from './update-schedule';
|
||||
import { registerRepairAgents } from './repair-agents';
|
||||
import { installRendererPermissions } from './media-permissions';
|
||||
@@ -112,6 +119,9 @@ let diagnostics: DiagnosticReports | null = null;
|
||||
// False for quits that must not install a downloaded update: a relaunch, or
|
||||
// the uninstall exit. Read when the updater is torn down.
|
||||
let installUpdateOnQuit = true;
|
||||
// An update the user chose to install now: they were already asked about running work.
|
||||
let updateInstalling: () => boolean = () => false;
|
||||
let quitGuardLabels: QuitGuardLabels = DEFAULT_QUIT_GUARD_LABELS;
|
||||
|
||||
// A terminal command starts the app without a window (`--voicestudio-background`); the
|
||||
// window then opens on demand in this same process (see ./headless.ts).
|
||||
@@ -268,6 +278,53 @@ function beginOrderlyQuit(flushPersistence = true): Promise<void> {
|
||||
return quitPreparation;
|
||||
}
|
||||
|
||||
const confirmQuitWithRunningWork = createQuitGuard({
|
||||
readBusy: async () => {
|
||||
const backend = supervisor;
|
||||
if (!backend || !['ready', 'unresponsive'].includes(backend.status.stage)) return [];
|
||||
const activity = await readBackendActivity(backend);
|
||||
return activity ? busyForQuit(activity) : null;
|
||||
},
|
||||
confirm: async () => {
|
||||
const labels = quitGuardLabels;
|
||||
const options: Electron.MessageBoxOptions = {
|
||||
type: 'warning',
|
||||
title: labels.title,
|
||||
message: labels.message,
|
||||
detail: labels.detail,
|
||||
buttons: [labels.keep, labels.quit],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
};
|
||||
const owner = isLiveWindow(mainWindow) ? mainWindow : null;
|
||||
if (owner && !owner.isVisible()) owner.show();
|
||||
const { response } = owner
|
||||
? await dialog.showMessageBox(owner, options)
|
||||
: await dialog.showMessageBox(options);
|
||||
return response === 1;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* A quit the user asked for (Cmd+Q, the tray, closing the last window). It
|
||||
* asks first when the engine is running work; quits from an OS shutdown, an
|
||||
* update install the user already confirmed, or one already under way do not.
|
||||
*/
|
||||
function requestUserQuit(): void {
|
||||
if (quitPreparation || sessionEnding || updateInstalling()) {
|
||||
observeMainProcessTask(beginOrderlyQuit(), mainErrors, 'Orderly quit');
|
||||
return;
|
||||
}
|
||||
observeMainProcessTask(
|
||||
(async () => {
|
||||
if (await confirmQuitWithRunningWork()) await beginOrderlyQuit();
|
||||
})(),
|
||||
mainErrors,
|
||||
'Orderly quit',
|
||||
);
|
||||
}
|
||||
|
||||
function brandIconPath(file: string): string {
|
||||
return app.isPackaged
|
||||
? join(process.resourcesPath, 'brand', file)
|
||||
@@ -296,6 +353,13 @@ ipcMain.handle('app:set-close-to-tray', (event, enabled: unknown) => {
|
||||
return closeToTray;
|
||||
});
|
||||
|
||||
ipcMain.handle('app:set-quit-guard-labels', (event, raw: unknown) => {
|
||||
assertTrustedMainFrame(event, mainWindow);
|
||||
const labels = parseQuitGuardLabels(raw);
|
||||
if (!labels) throw new Error('Invalid quit dialog labels');
|
||||
quitGuardLabels = labels;
|
||||
});
|
||||
|
||||
ipcMain.handle(
|
||||
'app:is-fullscreen',
|
||||
(event) => {
|
||||
@@ -358,7 +422,7 @@ function createWindow(): BrowserWindow {
|
||||
if (action === 'allow') return;
|
||||
event.preventDefault();
|
||||
if (action === 'quit') {
|
||||
observeMainProcessTask(beginOrderlyQuit(), mainErrors, 'Orderly quit');
|
||||
requestUserQuit();
|
||||
return;
|
||||
}
|
||||
if (action === 'hide') {
|
||||
@@ -653,6 +717,7 @@ if (singleInstance && !app.requestSingleInstanceLock()) {
|
||||
'Backend startup',
|
||||
);
|
||||
const updater = new DesktopUpdater();
|
||||
updateInstalling = () => updater.installingUpdate;
|
||||
const closeUpdateIpc = registerUpdateIpc(
|
||||
updater,
|
||||
() => mainWindow,
|
||||
@@ -746,6 +811,6 @@ if (singleInstance && !app.requestSingleInstanceLock()) {
|
||||
app.on('before-quit', (event) => {
|
||||
if (quitting) return;
|
||||
event.preventDefault();
|
||||
observeMainProcessTask(beginOrderlyQuit(), mainErrors, 'Orderly quit');
|
||||
requestUserQuit();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import {
|
||||
busyForQuit,
|
||||
createQuitGuard,
|
||||
DEFAULT_QUIT_GUARD_LABELS,
|
||||
parseQuitGuardLabels,
|
||||
} from './quit-guard';
|
||||
|
||||
it('quits without asking when the engine is idle', async () => {
|
||||
const confirm = vi.fn(async () => false);
|
||||
const guard = createQuitGuard({ readBusy: async () => [], confirm });
|
||||
await expect(guard()).resolves.toBe(true);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks before stopping running work and honours the answer', async () => {
|
||||
const confirm = vi.fn(async () => false);
|
||||
const guard = createQuitGuard({ readBusy: async () => ['jobs'], confirm });
|
||||
await expect(guard()).resolves.toBe(false);
|
||||
confirm.mockResolvedValueOnce(true);
|
||||
await expect(guard()).resolves.toBe(true);
|
||||
expect(confirm).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('never traps the user when the engine cannot say what it is doing', async () => {
|
||||
const confirm = vi.fn(async () => false);
|
||||
const guard = createQuitGuard({ readBusy: async () => null, confirm });
|
||||
await expect(guard()).resolves.toBe(true);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shares one question between quits requested while it is open', async () => {
|
||||
let answer: (quit: boolean) => void = () => {};
|
||||
const confirm = vi.fn(() => new Promise<boolean>((resolve) => (answer = resolve)));
|
||||
const guard = createQuitGuard({ readBusy: async () => ['batch'], confirm });
|
||||
const first = guard();
|
||||
const second = guard();
|
||||
await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(1));
|
||||
answer(true);
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('accepts only a complete set of translated labels', () => {
|
||||
expect(parseQuitGuardLabels(DEFAULT_QUIT_GUARD_LABELS)).toEqual(DEFAULT_QUIT_GUARD_LABELS);
|
||||
expect(parseQuitGuardLabels({ ...DEFAULT_QUIT_GUARD_LABELS, quit: '' })).toBeNull();
|
||||
expect(parseQuitGuardLabels({ ...DEFAULT_QUIT_GUARD_LABELS, keep: 7 })).toBeNull();
|
||||
expect(parseQuitGuardLabels('Quit')).toBeNull();
|
||||
});
|
||||
|
||||
it('counts a generation or transcription still being answered as running work', () => {
|
||||
expect(busyForQuit({ busy: [], work_requests: 1 })).toEqual(['requests']);
|
||||
expect(busyForQuit({ busy: ['batch'], work_requests: 0 })).toEqual(['batch']);
|
||||
// An engine from before the count reports only its registered work.
|
||||
expect(busyForQuit({ busy: [] })).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Ask before a user's quit stops work the local engine is still doing.
|
||||
*
|
||||
* Quitting tears the engine down, so a render, dub, batch or model download
|
||||
* in progress stopped without a word. Restart-to-update already asks first;
|
||||
* an ordinary quit now does too. Quits the user did not start here (an OS
|
||||
* shutdown, an installer, a relaunch) never reach this guard.
|
||||
*/
|
||||
|
||||
/** Dialog text, translated by the renderer; English until it reports. */
|
||||
export interface QuitGuardLabels {
|
||||
title: string;
|
||||
message: string;
|
||||
detail: string;
|
||||
quit: string;
|
||||
keep: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_QUIT_GUARD_LABELS: QuitGuardLabels = {
|
||||
title: 'VoiceStudio',
|
||||
message: 'VoiceStudio is still working.',
|
||||
detail:
|
||||
'Quitting now stops the running tasks. When you open VoiceStudio again, unfinished batches continue and interrupted renders can be resumed.',
|
||||
quit: 'Quit anyway',
|
||||
keep: 'Keep working',
|
||||
};
|
||||
|
||||
/** Accepts only a complete set of short strings from the renderer. */
|
||||
export function parseQuitGuardLabels(raw: unknown): QuitGuardLabels | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const out: Partial<QuitGuardLabels> = {};
|
||||
for (const key of Object.keys(DEFAULT_QUIT_GUARD_LABELS) as (keyof QuitGuardLabels)[]) {
|
||||
const value = (raw as Record<string, unknown>)[key];
|
||||
if (typeof value !== 'string' || !value.trim() || value.length > 500) return null;
|
||||
out[key] = value;
|
||||
}
|
||||
return out as QuitGuardLabels;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a quit would stop: the engine's long-running work, plus "requests" while
|
||||
* a generation, clone, design or transcription is still being answered (those
|
||||
* run inside their request, with no job to register).
|
||||
*/
|
||||
export function busyForQuit(activity: { busy: string[]; work_requests?: number }): string[] {
|
||||
return activity.work_requests ? [...activity.busy, 'requests'] : activity.busy;
|
||||
}
|
||||
|
||||
export interface QuitGuardDeps {
|
||||
/** Names of running work, `[]` when idle, or null when the engine could not say. */
|
||||
readBusy(): Promise<string[] | null>;
|
||||
/** Shows the question; true means quit. */
|
||||
confirm(): Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves true when the quit may go ahead. Concurrent requests (a second
|
||||
* Cmd+Q while the question is open) share one question.
|
||||
*/
|
||||
export function createQuitGuard(deps: QuitGuardDeps): () => Promise<boolean> {
|
||||
let pending: Promise<boolean> | null = null;
|
||||
return () => {
|
||||
pending ??= (async () => {
|
||||
try {
|
||||
const busy = await deps.readBusy();
|
||||
// An engine that cannot answer is not trapping the user in the app.
|
||||
if (!busy?.length) return true;
|
||||
return await deps.confirm();
|
||||
} finally {
|
||||
pending = null;
|
||||
}
|
||||
})();
|
||||
return pending;
|
||||
};
|
||||
}
|
||||
@@ -975,6 +975,11 @@ export class DesktopUpdater {
|
||||
return this.snapshot();
|
||||
}
|
||||
|
||||
/** The user chose to install now; the app is quitting into the installer. */
|
||||
get installingUpdate(): boolean {
|
||||
return this.installing;
|
||||
}
|
||||
|
||||
install(): void {
|
||||
if (!this.updatesSupported() || this.state.status !== 'downloaded') return;
|
||||
if (this.state.availableVersion)
|
||||
|
||||
Vendored
+10
@@ -58,6 +58,8 @@ export interface BackendStatus {
|
||||
failure?: InstallFailure;
|
||||
/** The local engine crashed and can be started again on CPU (`backend.restartOnCpu`). */
|
||||
cpuRestartAvailable?: boolean;
|
||||
/** The engine crashed after it had started and restarts on its own at this time (epoch ms). */
|
||||
autoRestartAt?: number;
|
||||
stage: BackendStage;
|
||||
setupIssue?:
|
||||
| 'space'
|
||||
@@ -517,6 +519,14 @@ export interface VoiceStudioBridge {
|
||||
getCloseToTray(): Promise<boolean>;
|
||||
setCloseToTray(enabled: boolean): Promise<boolean>;
|
||||
onPersistenceFlush(callback: () => void | Promise<void>): () => void;
|
||||
/** Translated text for the question asked when quitting would stop running work. */
|
||||
setQuitGuardLabels?(labels: {
|
||||
title: string;
|
||||
message: string;
|
||||
detail: string;
|
||||
quit: string;
|
||||
keep: string;
|
||||
}): Promise<void>;
|
||||
};
|
||||
backend: {
|
||||
getStatus(): Promise<BackendStatus>;
|
||||
|
||||
@@ -88,6 +88,8 @@ const bridge: VoiceStudioBridge = {
|
||||
setCloseToTray: (enabled) =>
|
||||
ipcRenderer.invoke('app:set-close-to-tray', enabled) as Promise<boolean>,
|
||||
onFullScreen: (callback) => subscribe<boolean>('app:fullscreen', callback),
|
||||
setQuitGuardLabels: (labels) =>
|
||||
ipcRenderer.invoke('app:set-quit-guard-labels', labels) as Promise<void>,
|
||||
onPersistenceFlush: (callback) => {
|
||||
const listener = (_event: IpcRendererEvent, token: string) => {
|
||||
void (async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { FirstSoundHandoff } from '@/components/first-sound-handoff';
|
||||
import { stepAppearanceScale } from '@/hooks/use-appearance';
|
||||
import { recordRouteBreadcrumb } from '@/lib/report-breadcrumb';
|
||||
import { ModelInstallSync } from '@/hooks/use-model-install-sync';
|
||||
import { InterruptedRenderNotice } from '@/features/longform/interrupted-render-notice';
|
||||
import { RealtimeEventSync } from '@/hooks/use-realtime-events';
|
||||
import { GenerateBudgetSync } from '@/hooks/use-generate-budget-sync';
|
||||
import { runRendererTask } from '@/lib/global-error-recovery';
|
||||
@@ -81,6 +82,18 @@ export function App() {
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
// Main asks this question natively at quit time; hand it the current language.
|
||||
void getBridge()
|
||||
?.app.setQuitGuardLabels?.({
|
||||
title: t('app.name'),
|
||||
message: t('backend.quit_running_message'),
|
||||
detail: t('backend.quit_running_detail'),
|
||||
quit: t('backend.quit_anyway'),
|
||||
keep: t('backend.keep_working'),
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [t]);
|
||||
useEffect(() => {
|
||||
const app = getBridge()?.app;
|
||||
if (!app?.onPersistenceFlush) return;
|
||||
@@ -99,6 +112,7 @@ export function App() {
|
||||
<WebAuthGate>
|
||||
<NativeDictationSync />
|
||||
<ModelInstallSync />
|
||||
<InterruptedRenderNotice />
|
||||
<RealtimeEventSync />
|
||||
<GenerateBudgetSync />
|
||||
<AnalyticsRuntime />
|
||||
|
||||
@@ -51,6 +51,7 @@ beforeEach(() => {
|
||||
delete backendStatus.setupHardware;
|
||||
delete backendStatus.failure;
|
||||
delete backendStatus.cpuRestartAvailable;
|
||||
delete backendStatus.autoRestartAt;
|
||||
platform.current = 'linux';
|
||||
});
|
||||
|
||||
@@ -497,6 +498,25 @@ it('names a native crash and makes Copy diagnostics the primary action', () => {
|
||||
expect(screen.getByRole('button', { name: i18n.t('backend.retry') })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('says a crashed engine is restarting on its own while the restart is pending', () => {
|
||||
backendStatus.message = 'Backend exited unexpectedly (signal SIGKILL).';
|
||||
backendStatus.autoRestartAt = Date.now() + 1000;
|
||||
|
||||
renderGate('crashed');
|
||||
|
||||
expect(screen.getByTestId('backend-auto-restart')).toHaveTextContent(
|
||||
i18n.t('backend.auto_restarting'),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows no automatic restart once the crash-loop limit is reached', () => {
|
||||
backendStatus.message = 'Backend exited unexpectedly (signal SIGKILL).';
|
||||
|
||||
renderGate('crashed');
|
||||
|
||||
expect(screen.queryByTestId('backend-auto-restart')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('offers Restart on CPU after a graphics driver crash, without the engine running', async () => {
|
||||
const restartOnCpu = vi.fn(async () => undefined);
|
||||
bridgeStub.current = { backend: { restartOnCpu, restart: vi.fn() } };
|
||||
|
||||
@@ -450,6 +450,11 @@ export function BackendGate({ children, repairDock }: BackendGateProps) {
|
||||
>
|
||||
{stageText}
|
||||
</h1>
|
||||
{status.stage === 'crashed' && status.autoRestartAt ? (
|
||||
<p className="text-sm font-medium" data-testid="backend-auto-restart">
|
||||
{t('backend.auto_restarting')}
|
||||
</p>
|
||||
) : null}
|
||||
{problemText ? (
|
||||
<p
|
||||
className={cn(
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { act, cleanup, render } from '@testing-library/react';
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import '@/i18n';
|
||||
import {
|
||||
InterruptedRenderNotice,
|
||||
RECOVERY_CHECK_ATTEMPTS,
|
||||
RECOVERY_CHECK_RETRY_MS,
|
||||
} from './interrupted-render-notice';
|
||||
|
||||
const mock = vi.hoisted(() => ({ api: vi.fn(), toast: vi.fn() }));
|
||||
vi.mock('@/lib/api/client', () => ({ apiJson: mock.api }));
|
||||
vi.mock('@/hooks/use-backend-status', () => ({ useBackendStatus: () => ({ stage: 'ready' }) }));
|
||||
vi.mock('sonner', () => ({ toast: mock.toast }));
|
||||
vi.mock('@/router', () => ({
|
||||
router: { state: { location: { pathname: '/' } }, navigate: vi.fn() },
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
mock.api.mockReset();
|
||||
mock.toast.mockReset();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
const interrupted = {
|
||||
jobs: [
|
||||
{
|
||||
job_id: 'book',
|
||||
type: 'audiobook',
|
||||
title: 'Book',
|
||||
chapters_done: 1,
|
||||
total_chapters: 3,
|
||||
created_at: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('checks again after a failed check, so a brief outage does not hide the notice', async () => {
|
||||
vi.useFakeTimers();
|
||||
mock.api.mockRejectedValueOnce(new Error('offline')).mockResolvedValue(interrupted);
|
||||
render(<InterruptedRenderNotice />);
|
||||
await act(() => vi.advanceTimersByTimeAsync(0));
|
||||
expect(mock.api).toHaveBeenCalledTimes(1);
|
||||
expect(mock.toast).not.toHaveBeenCalled();
|
||||
await act(() => vi.advanceTimersByTimeAsync(RECOVERY_CHECK_RETRY_MS));
|
||||
expect(mock.api).toHaveBeenCalledTimes(2);
|
||||
expect(mock.toast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stops after a few failed checks', async () => {
|
||||
vi.useFakeTimers();
|
||||
mock.api.mockRejectedValue(new Error('offline'));
|
||||
render(<InterruptedRenderNotice />);
|
||||
for (let step = 0; step < 10; step++)
|
||||
await act(() => vi.advanceTimersByTimeAsync(RECOVERY_CHECK_RETRY_MS));
|
||||
expect(mock.api).toHaveBeenCalledTimes(RECOVERY_CHECK_ATTEMPTS);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { expect, it } from 'vitest';
|
||||
import { interruptedRendersToAnnounce } from './interrupted-render-notice';
|
||||
import type { Recovery } from './render-recovery';
|
||||
|
||||
const job = (job_id: string, type: string, created_at: number, plan_key?: string): Recovery => ({
|
||||
job_id,
|
||||
type,
|
||||
title: job_id,
|
||||
chapters_done: 1,
|
||||
total_chapters: 3,
|
||||
created_at,
|
||||
plan_key,
|
||||
});
|
||||
|
||||
it('announces the newest interrupted render of each page once', () => {
|
||||
const jobs = [
|
||||
job('old-book', 'audiobook', 1),
|
||||
job('new-book', 'audiobook', 2),
|
||||
job('story', 'story', 1),
|
||||
];
|
||||
expect(interruptedRendersToAnnounce(jobs, [], []).map(({ job }) => job.job_id)).toEqual([
|
||||
'story',
|
||||
'new-book',
|
||||
]);
|
||||
expect(interruptedRendersToAnnounce(jobs, [], ['story', 'new-book'])).toEqual([
|
||||
{ mode: 'audiobook', job: jobs[0] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('stays quiet about renders the user dismissed', () => {
|
||||
expect(interruptedRendersToAnnounce([job('a', 'story', 1)], ['a'], [])).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useBackendStatus } from '@/hooks/use-backend-status';
|
||||
import { apiJson } from '@/lib/api/client';
|
||||
import { runRendererTask } from '@/lib/global-error-recovery';
|
||||
import { readDismissed, recoveriesFor, type Recovery } from './render-recovery';
|
||||
import type { Mode } from './longform-session';
|
||||
|
||||
const NOTIFIED_KEY = 'voicestudio.longform.notified-recoveries';
|
||||
/** A failed check is tried again this many times, this far apart. */
|
||||
export const RECOVERY_CHECK_ATTEMPTS = 3;
|
||||
export const RECOVERY_CHECK_RETRY_MS = 5_000;
|
||||
const PAGE: Record<Mode, '/stories' | '/audiobook'> = {
|
||||
stories: '/stories',
|
||||
audiobook: '/audiobook',
|
||||
};
|
||||
|
||||
function readNotified(): string[] {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(NOTIFIED_KEY) ?? '[]');
|
||||
return Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The renders to announce at launch: one per page and render plan, skipping
|
||||
* ones the user dismissed or was already told about.
|
||||
*/
|
||||
export function interruptedRendersToAnnounce(
|
||||
jobs: readonly Recovery[],
|
||||
dismissed: readonly string[],
|
||||
notified: readonly string[],
|
||||
): { mode: Mode; job: Recovery }[] {
|
||||
return (['stories', 'audiobook'] as const).flatMap((mode) =>
|
||||
recoveriesFor(mode, jobs, dismissed)
|
||||
.filter((job) => !notified.includes(job.job_id))
|
||||
.slice(0, 1)
|
||||
.map((job) => ({ mode, job })),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A render cut short by a quit, crash or update shows its Resume card only on
|
||||
* its own page, and the app opens on Home. Once the engine is ready, point
|
||||
* the user to each interrupted render a single time.
|
||||
*/
|
||||
export function InterruptedRenderNotice() {
|
||||
const { t } = useTranslation();
|
||||
const ready = useBackendStatus().stage === 'ready';
|
||||
const checked = useRef(false);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!ready || checked.current || attempt >= RECOVERY_CHECK_ATTEMPTS) return;
|
||||
checked.current = true;
|
||||
let retry: ReturnType<typeof setTimeout> | undefined;
|
||||
void (async () => {
|
||||
const { jobs } = await apiJson<{ jobs: Recovery[] }>('/audiobook/jobs');
|
||||
const notified = readNotified();
|
||||
const announce = interruptedRendersToAnnounce(jobs ?? [], readDismissed(), notified);
|
||||
if (!announce.length) return;
|
||||
// Keep only ids the backend still lists, so the list never grows without bound.
|
||||
const listed = new Set((jobs ?? []).map((job) => job.job_id));
|
||||
const next = [
|
||||
...notified.filter((id) => listed.has(id)),
|
||||
...announce.map(({ job }) => job.job_id),
|
||||
];
|
||||
try {
|
||||
localStorage.setItem(NOTIFIED_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
// Unavailable storage only means the notice may show again next launch.
|
||||
}
|
||||
const { router } = await import('@/router');
|
||||
for (const { mode, job } of announce) {
|
||||
if (router.state.location.pathname === PAGE[mode]) continue;
|
||||
toast(t(mode === 'stories' ? 'stories.recovery_title' : 'audiobook.recovery_title'), {
|
||||
description: `${job.title || t(mode === 'stories' ? 'stories.untitled' : 'audiobook.untitled')} · ${t(
|
||||
'audiobook.recovery_progress',
|
||||
{ done: job.chapters_done, total: job.total_chapters },
|
||||
)}`,
|
||||
duration: 15_000,
|
||||
action: {
|
||||
label: t('common.resume'),
|
||||
onClick: () =>
|
||||
runRendererTask('Open interrupted render', () => router.navigate({ to: PAGE[mode] })),
|
||||
},
|
||||
});
|
||||
}
|
||||
})().catch(() => {
|
||||
// A briefly unreachable engine gets a few more tries; after that the
|
||||
// page's own Resume card still offers the render.
|
||||
checked.current = false;
|
||||
retry = setTimeout(() => setAttempt((n) => n + 1), RECOVERY_CHECK_RETRY_MS);
|
||||
});
|
||||
return () => clearTimeout(retry);
|
||||
}, [ready, t, attempt]);
|
||||
return null;
|
||||
}
|
||||
@@ -24,7 +24,7 @@ export const RECOVERY_JOB_TYPE: Record<Mode, string> = {
|
||||
|
||||
const DISMISSED_KEY = 'voicestudio.longform.dismissed-recoveries';
|
||||
|
||||
function readDismissed(): string[] {
|
||||
export function readDismissed(): string[] {
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(DISMISSED_KEY) ?? '[]');
|
||||
return Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
|
||||
|
||||
@@ -2265,6 +2265,11 @@
|
||||
"starting": "جارٍ بدء المحرك المحلي…",
|
||||
"attaching": "جارٍ الاتصال بالمحرك قيد التشغيل…",
|
||||
"crashed": "توقف المحرك المحلي بشكل غير متوقع.",
|
||||
"auto_restarting": "جارٍ إعادة تشغيل المحرك تلقائيًا…",
|
||||
"quit_running_message": "لا يزال VoiceStudio يعمل.",
|
||||
"quit_running_detail": "الإنهاء الآن يوقف المهام الجارية. عند فتح VoiceStudio مرة أخرى، تستمر الدفعات غير المكتملة ويمكن استئناف عمليات العرض المتوقفة.",
|
||||
"quit_anyway": "إنهاء على أي حال",
|
||||
"keep_working": "متابعة العمل",
|
||||
"unresponsive": "المحرك المحلي مشغول حالياً ولا يستجيب — سيستأنف العمل تلقائياً.",
|
||||
"unresponsive_remote": "تعذّر التأكد من الاتصال بالمحرك البعيد — تتم إعادة المحاولة تلقائياً.",
|
||||
"unhealthy": "المحرك يستجيب لكنه يبلغ أنه غير سليم. راجع الإعدادات ← السجلات ← الخلفية، ثم أعد المحاولة.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Lokale Engine wird gestartet…",
|
||||
"attaching": "Verbindung zur laufenden Engine wird hergestellt…",
|
||||
"crashed": "Die lokale Engine wurde unerwartet beendet.",
|
||||
"auto_restarting": "Die Engine wird automatisch neu gestartet…",
|
||||
"quit_running_message": "VoiceStudio arbeitet noch.",
|
||||
"quit_running_detail": "Wenn du jetzt beendest, werden laufende Aufgaben gestoppt. Beim nächsten Öffnen von VoiceStudio laufen unfertige Stapel weiter, und unterbrochene Renderings lassen sich fortsetzen.",
|
||||
"quit_anyway": "Trotzdem beenden",
|
||||
"keep_working": "Weiterarbeiten",
|
||||
"unresponsive": "Die lokale Engine ist gerade ausgelastet und antwortet nicht — sie erholt sich von selbst.",
|
||||
"unresponsive_remote": "Die Verbindung zur entfernten Engine lässt sich nicht bestätigen — es wird automatisch erneut versucht.",
|
||||
"unhealthy": "Die Engine antwortet, meldet aber, dass sie nicht gesund ist. Prüfe Einstellungen → Protokolle → Backend und versuche es erneut.",
|
||||
|
||||
@@ -367,6 +367,11 @@
|
||||
"attaching": "Connecting to the running engine…",
|
||||
"ready": "Engine ready",
|
||||
"crashed": "The local engine stopped unexpectedly.",
|
||||
"auto_restarting": "Restarting the engine automatically…",
|
||||
"quit_running_message": "VoiceStudio is still working.",
|
||||
"quit_running_detail": "Quitting now stops the running tasks. When you open VoiceStudio again, unfinished batches continue and interrupted renders can be resumed.",
|
||||
"quit_anyway": "Quit anyway",
|
||||
"keep_working": "Keep working",
|
||||
"unresponsive": "The local engine is busy and not answering right now — it recovers on its own.",
|
||||
"unresponsive_remote": "Can't confirm the connection to the remote engine — retrying automatically.",
|
||||
"unhealthy": "The engine is answering but reports that it isn't healthy. Check Settings → Logs → Backend, then retry.",
|
||||
|
||||
@@ -2215,6 +2215,11 @@
|
||||
"starting": "Iniciando el motor local…",
|
||||
"attaching": "Conectando con el motor en ejecución…",
|
||||
"crashed": "El motor local se detuvo inesperadamente.",
|
||||
"auto_restarting": "Reiniciando el motor automáticamente…",
|
||||
"quit_running_message": "VoiceStudio todavía está trabajando.",
|
||||
"quit_running_detail": "Salir ahora detiene las tareas en curso. Al volver a abrir VoiceStudio, los lotes sin terminar continúan y los renders interrumpidos se pueden reanudar.",
|
||||
"quit_anyway": "Salir de todos modos",
|
||||
"keep_working": "Seguir trabajando",
|
||||
"unresponsive": "El motor local está ocupado y no responde ahora mismo; se recuperará por sí solo.",
|
||||
"unresponsive_remote": "No se puede confirmar la conexión con el motor remoto; se reintentará automáticamente.",
|
||||
"unhealthy": "El motor responde, pero informa de que no está en buen estado. Revisa Ajustes → Registros → Backend y vuelve a intentarlo.",
|
||||
|
||||
@@ -2215,6 +2215,11 @@
|
||||
"starting": "Démarrage du moteur local…",
|
||||
"attaching": "Connexion au moteur en cours d’exécution…",
|
||||
"crashed": "Le moteur local s’est arrêté de manière inattendue.",
|
||||
"auto_restarting": "Redémarrage automatique du moteur…",
|
||||
"quit_running_message": "VoiceStudio est encore en train de travailler.",
|
||||
"quit_running_detail": "Quitter maintenant arrête les tâches en cours. À la prochaine ouverture de VoiceStudio, les lots inachevés reprennent et les rendus interrompus peuvent être repris.",
|
||||
"quit_anyway": "Quitter quand même",
|
||||
"keep_working": "Continuer",
|
||||
"unresponsive": "Le moteur local est occupé et ne répond pas pour le moment ; il reprendra de lui-même.",
|
||||
"unresponsive_remote": "Impossible de confirmer la connexion au moteur distant ; nouvelle tentative automatique.",
|
||||
"unhealthy": "Le moteur répond, mais signale qu'il n'est pas en bon état. Consultez Réglages → Journaux → Backend, puis réessayez.",
|
||||
|
||||
@@ -367,6 +367,11 @@
|
||||
"attaching": "Conectando ao motor en marcha…",
|
||||
"ready": "Motor listo",
|
||||
"crashed": "O motor local parou inesperadamente.",
|
||||
"auto_restarting": "Reiniciando o motor automaticamente…",
|
||||
"quit_running_message": "VoiceStudio aínda está traballando.",
|
||||
"quit_running_detail": "Saír agora detén as tarefas en curso. Ao abrir de novo VoiceStudio, os lotes sen rematar continúan e as renderizacións interrompidas pódense retomar.",
|
||||
"quit_anyway": "Saír igualmente",
|
||||
"keep_working": "Seguir traballando",
|
||||
"unresponsive": "O motor local está ocupado e non responde nestes momentos: recuperase por si só.",
|
||||
"unresponsive_remote": "Non se pode confirmar a conexión co motor remoto. Téntao de novo automaticamente.",
|
||||
"unhealthy": "O motor responde pero informa que non é saudable. Verifique Configuración → Rexistros → Backend e, a continuación, ténteo de novo.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "स्थानीय इंजन शुरू हो रहा है…",
|
||||
"attaching": "चल रहे इंजन से जुड़ रहा है…",
|
||||
"crashed": "स्थानीय इंजन अचानक बंद हो गया।",
|
||||
"auto_restarting": "इंजन अपने आप फिर से शुरू हो रहा है…",
|
||||
"quit_running_message": "VoiceStudio अभी भी काम कर रहा है।",
|
||||
"quit_running_detail": "अभी बंद करने से चल रहे कार्य रुक जाएँगे। VoiceStudio दोबारा खोलने पर अधूरे बैच जारी रहेंगे और रुके हुए रेंडर फिर से शुरू किए जा सकेंगे।",
|
||||
"quit_anyway": "फिर भी बंद करें",
|
||||
"keep_working": "काम जारी रखें",
|
||||
"unresponsive": "स्थानीय इंजन अभी व्यस्त है और जवाब नहीं दे रहा है — यह अपने आप ठीक हो जाएगा।",
|
||||
"unresponsive_remote": "दूरस्थ इंजन से कनेक्शन की पुष्टि नहीं हो पा रही है — अपने आप दोबारा कोशिश की जा रही है।",
|
||||
"unhealthy": "इंजन जवाब दे रहा है, लेकिन बता रहा है कि वह स्वस्थ नहीं है। सेटिंग्स → लॉग → बैकएंड देखें, फिर दोबारा कोशिश करें।",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Memulai mesin lokal…",
|
||||
"attaching": "Menghubungkan ke mesin yang sedang berjalan…",
|
||||
"crashed": "Mesin lokal berhenti secara tak terduga.",
|
||||
"auto_restarting": "Memulai ulang mesin secara otomatis…",
|
||||
"quit_running_message": "VoiceStudio masih bekerja.",
|
||||
"quit_running_detail": "Keluar sekarang akan menghentikan tugas yang berjalan. Saat Anda membuka VoiceStudio lagi, batch yang belum selesai akan berlanjut dan render yang terputus dapat dilanjutkan.",
|
||||
"quit_anyway": "Tetap keluar",
|
||||
"keep_working": "Lanjutkan bekerja",
|
||||
"unresponsive": "Mesin lokal sedang sibuk dan belum merespons — akan pulih sendiri.",
|
||||
"unresponsive_remote": "Koneksi ke mesin jarak jauh tidak dapat dipastikan — mencoba lagi secara otomatis.",
|
||||
"unhealthy": "Mesin merespons tetapi melaporkan dirinya tidak sehat. Periksa Pengaturan → Log → Backend, lalu coba lagi.",
|
||||
|
||||
@@ -2215,6 +2215,11 @@
|
||||
"starting": "Avvio del motore locale…",
|
||||
"attaching": "Connessione al motore in esecuzione…",
|
||||
"crashed": "Il motore locale si è arrestato in modo imprevisto.",
|
||||
"auto_restarting": "Riavvio automatico del motore…",
|
||||
"quit_running_message": "VoiceStudio sta ancora lavorando.",
|
||||
"quit_running_detail": "Uscire ora interrompe le attività in corso. Alla prossima apertura di VoiceStudio i batch non finiti proseguono e i rendering interrotti possono essere ripresi.",
|
||||
"quit_anyway": "Esci comunque",
|
||||
"keep_working": "Continua a lavorare",
|
||||
"unresponsive": "Il motore locale è occupato e al momento non risponde — si riprenderà da solo.",
|
||||
"unresponsive_remote": "Impossibile confermare la connessione al motore remoto: nuovo tentativo automatico.",
|
||||
"unhealthy": "Il motore risponde ma segnala di non essere in buono stato. Controlla Impostazioni → Log → Backend, poi riprova.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "ローカルエンジンを起動中…",
|
||||
"attaching": "実行中のエンジンに接続中…",
|
||||
"crashed": "ローカルエンジンが予期せず停止しました。",
|
||||
"auto_restarting": "エンジンを自動的に再起動しています…",
|
||||
"quit_running_message": "VoiceStudio はまだ処理中です。",
|
||||
"quit_running_detail": "今終了すると実行中のタスクが停止します。次に VoiceStudio を開くと、未完了のバッチは続行され、中断されたレンダリングは再開できます。",
|
||||
"quit_anyway": "それでも終了",
|
||||
"keep_working": "作業を続ける",
|
||||
"unresponsive": "ローカルエンジンが混雑しており、現在応答していません。処理が終わると自動的に回復します。",
|
||||
"unresponsive_remote": "リモートエンジンへの接続を確認できません。自動的に再試行しています。",
|
||||
"unhealthy": "エンジンは応答していますが、正常ではないと報告しています。設定 → ログ → バックエンドを確認して、もう一度お試しください。",
|
||||
|
||||
@@ -2212,6 +2212,11 @@
|
||||
"starting": "로컬 엔진 시작 중…",
|
||||
"attaching": "실행 중인 엔진에 연결 중…",
|
||||
"crashed": "로컬 엔진이 예기치 않게 중지되었습니다.",
|
||||
"auto_restarting": "엔진을 자동으로 다시 시작하는 중…",
|
||||
"quit_running_message": "VoiceStudio가 아직 작업 중입니다.",
|
||||
"quit_running_detail": "지금 종료하면 실행 중인 작업이 중지됩니다. VoiceStudio를 다시 열면 끝나지 않은 일괄 작업이 계속되고 중단된 렌더링은 이어서 할 수 있습니다.",
|
||||
"quit_anyway": "그래도 종료",
|
||||
"keep_working": "계속 작업",
|
||||
"unresponsive": "로컬 엔진이 현재 바빠 응답하지 않습니다. 작업이 끝나면 자동으로 복구됩니다.",
|
||||
"unresponsive_remote": "원격 엔진과의 연결을 확인할 수 없습니다. 자동으로 다시 시도합니다.",
|
||||
"unhealthy": "엔진이 응답하지만 정상 상태가 아니라고 보고합니다. 설정 → 로그 → 백엔드를 확인한 뒤 다시 시도하세요.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Lokale engine starten…",
|
||||
"attaching": "Verbinding maken met de actieve engine…",
|
||||
"crashed": "De lokale engine is onverwacht gestopt.",
|
||||
"auto_restarting": "De engine wordt automatisch opnieuw gestart…",
|
||||
"quit_running_message": "VoiceStudio is nog bezig.",
|
||||
"quit_running_detail": "Nu afsluiten stopt de lopende taken. Wanneer je VoiceStudio opnieuw opent, gaan onvoltooide batches verder en kun je onderbroken renders hervatten.",
|
||||
"quit_anyway": "Toch afsluiten",
|
||||
"keep_working": "Doorwerken",
|
||||
"unresponsive": "De lokale engine is bezet en reageert nu niet — hij komt vanzelf weer terug.",
|
||||
"unresponsive_remote": "De verbinding met de externe engine kan niet worden bevestigd — er wordt automatisch opnieuw geprobeerd.",
|
||||
"unhealthy": "De engine reageert, maar meldt dat hij niet gezond is. Bekijk Instellingen → Logboeken → Backend en probeer het opnieuw.",
|
||||
|
||||
@@ -2239,6 +2239,11 @@
|
||||
"starting": "Uruchamianie lokalnego silnika…",
|
||||
"attaching": "Łączenie z działającym silnikiem…",
|
||||
"crashed": "Lokalny silnik nieoczekiwanie się zatrzymał.",
|
||||
"auto_restarting": "Automatyczne ponowne uruchamianie silnika…",
|
||||
"quit_running_message": "VoiceStudio nadal pracuje.",
|
||||
"quit_running_detail": "Zamknięcie teraz zatrzyma uruchomione zadania. Po ponownym otwarciu VoiceStudio niedokończone partie będą kontynuowane, a przerwane renderowanie będzie można wznowić.",
|
||||
"quit_anyway": "Zamknij mimo to",
|
||||
"keep_working": "Pracuj dalej",
|
||||
"unresponsive": "Silnik lokalny jest zajęty i nie odpowiada — sam wróci do normy.",
|
||||
"unresponsive_remote": "Nie można potwierdzić połączenia ze zdalnym silnikiem — ponawiam automatycznie.",
|
||||
"unhealthy": "Silnik odpowiada, ale zgłasza, że nie jest sprawny. Sprawdź Ustawienia → Dzienniki → Backend i spróbuj ponownie.",
|
||||
|
||||
@@ -2215,6 +2215,11 @@
|
||||
"starting": "Iniciando o motor local…",
|
||||
"attaching": "Conectando ao motor em execução…",
|
||||
"crashed": "O motor local parou inesperadamente.",
|
||||
"auto_restarting": "Reiniciando o mecanismo automaticamente…",
|
||||
"quit_running_message": "O VoiceStudio ainda está trabalhando.",
|
||||
"quit_running_detail": "Sair agora interrompe as tarefas em andamento. Ao abrir o VoiceStudio novamente, os lotes inacabados continuam e as renderizações interrompidas podem ser retomadas.",
|
||||
"quit_anyway": "Sair mesmo assim",
|
||||
"keep_working": "Continuar trabalhando",
|
||||
"unresponsive": "O motor local está ocupado e não está a responder neste momento — recupera sozinho.",
|
||||
"unresponsive_remote": "Não é possível confirmar a ligação ao motor remoto — a tentar novamente automaticamente.",
|
||||
"unhealthy": "O motor está a responder, mas indica que não está saudável. Verifique Definições → Registos → Backend e tente novamente.",
|
||||
|
||||
@@ -2239,6 +2239,11 @@
|
||||
"starting": "Запуск локального движка…",
|
||||
"attaching": "Подключение к работающему движку…",
|
||||
"crashed": "Локальный движок неожиданно остановился.",
|
||||
"auto_restarting": "Движок перезапускается автоматически…",
|
||||
"quit_running_message": "VoiceStudio ещё работает.",
|
||||
"quit_running_detail": "Если выйти сейчас, выполняемые задачи остановятся. При следующем запуске VoiceStudio незавершённые пакеты продолжатся, а прерванный рендеринг можно будет возобновить.",
|
||||
"quit_anyway": "Всё равно выйти",
|
||||
"keep_working": "Продолжить работу",
|
||||
"unresponsive": "Локальный движок занят и сейчас не отвечает — он восстановится сам.",
|
||||
"unresponsive_remote": "Не удаётся подтвердить соединение с удалённым движком — повторные попытки выполняются автоматически.",
|
||||
"unhealthy": "Движок отвечает, но сообщает, что он неисправен. Проверьте «Настройки» → «Журналы» → «Бэкенд» и повторите попытку.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Startar den lokala motorn…",
|
||||
"attaching": "Ansluter till den körande motorn…",
|
||||
"crashed": "Den lokala motorn stannade oväntat.",
|
||||
"auto_restarting": "Motorn startas om automatiskt…",
|
||||
"quit_running_message": "VoiceStudio arbetar fortfarande.",
|
||||
"quit_running_detail": "Om du avslutar nu stoppas pågående uppgifter. När du öppnar VoiceStudio igen fortsätter ofullständiga batcher och avbrutna renderingar kan återupptas.",
|
||||
"quit_anyway": "Avsluta ändå",
|
||||
"keep_working": "Fortsätt arbeta",
|
||||
"unresponsive": "Den lokala motorn är upptagen och svarar inte just nu — den återgår av sig själv.",
|
||||
"unresponsive_remote": "Det går inte att bekräfta anslutningen till den fjärranslutna motorn — försöker igen automatiskt.",
|
||||
"unhealthy": "Motorn svarar men rapporterar att den inte mår bra. Kontrollera Inställningar → Loggar → Backend och försök igen.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "กำลังเริ่มเอนจินในเครื่อง…",
|
||||
"attaching": "กำลังเชื่อมต่อกับเอนจินที่ทำงานอยู่…",
|
||||
"crashed": "เอนจินในเครื่องหยุดทำงานโดยไม่คาดคิด",
|
||||
"auto_restarting": "กำลังเริ่มเอนจินใหม่โดยอัตโนมัติ…",
|
||||
"quit_running_message": "VoiceStudio ยังทำงานอยู่",
|
||||
"quit_running_detail": "การออกตอนนี้จะหยุดงานที่กำลังทำอยู่ เมื่อคุณเปิด VoiceStudio อีกครั้ง ชุดงานที่ยังไม่เสร็จจะทำต่อ และการเรนเดอร์ที่ถูกขัดจังหวะสามารถทำต่อได้",
|
||||
"quit_anyway": "ออกต่อไป",
|
||||
"keep_working": "ทำงานต่อ",
|
||||
"unresponsive": "เอนจิ้นในเครื่องกำลังยุ่งและยังไม่ตอบสนอง — จะกลับมาทำงานเอง",
|
||||
"unresponsive_remote": "ยืนยันการเชื่อมต่อกับเอนจิ้นระยะไกลไม่ได้ — กำลังลองใหม่โดยอัตโนมัติ",
|
||||
"unhealthy": "เอนจิ้นตอบสนอง แต่รายงานว่าไม่อยู่ในสภาพปกติ ตรวจสอบการตั้งค่า → บันทึก → แบ็กเอนด์ แล้วลองอีกครั้ง",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Yerel motor başlatılıyor…",
|
||||
"attaching": "Çalışan motora bağlanılıyor…",
|
||||
"crashed": "Yerel motor beklenmedik şekilde durdu.",
|
||||
"auto_restarting": "Motor otomatik olarak yeniden başlatılıyor…",
|
||||
"quit_running_message": "VoiceStudio hâlâ çalışıyor.",
|
||||
"quit_running_detail": "Şimdi çıkmak çalışan görevleri durdurur. VoiceStudio'yu yeniden açtığınızda bitmemiş toplu işler devam eder ve yarıda kalan işlemeler sürdürülebilir.",
|
||||
"quit_anyway": "Yine de çık",
|
||||
"keep_working": "Çalışmaya devam et",
|
||||
"unresponsive": "Yerel motor şu anda meşgul ve yanıt vermiyor — kendiliğinden toparlanacak.",
|
||||
"unresponsive_remote": "Uzak motorla bağlantı doğrulanamıyor — otomatik olarak yeniden deneniyor.",
|
||||
"unhealthy": "Motor yanıt veriyor ancak sağlıklı olmadığını bildiriyor. Ayarlar → Günlükler → Arka uç bölümüne bakın, ardından yeniden deneyin.",
|
||||
|
||||
@@ -2239,6 +2239,11 @@
|
||||
"starting": "Запуск локального рушія…",
|
||||
"attaching": "Підключення до запущеного рушія…",
|
||||
"crashed": "Локальний рушій несподівано зупинився.",
|
||||
"auto_restarting": "Рушій перезапускається автоматично…",
|
||||
"quit_running_message": "VoiceStudio ще працює.",
|
||||
"quit_running_detail": "Якщо вийти зараз, запущені завдання зупиняться. Коли ви знову відкриєте VoiceStudio, незавершені пакети продовжаться, а перерваний рендеринг можна буде відновити.",
|
||||
"quit_anyway": "Усе одно вийти",
|
||||
"keep_working": "Продовжити роботу",
|
||||
"unresponsive": "Локальний рушій зайнятий і зараз не відповідає — він відновиться сам.",
|
||||
"unresponsive_remote": "Не вдається підтвердити з'єднання з віддаленим рушієм — повторні спроби виконуються автоматично.",
|
||||
"unhealthy": "Рушій відповідає, але повідомляє, що він несправний. Перевірте «Налаштування» → «Журнали» → «Бекенд» і повторіть спробу.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "Đang khởi động bộ máy cục bộ…",
|
||||
"attaching": "Đang kết nối với bộ máy đang chạy…",
|
||||
"crashed": "Bộ máy cục bộ đã dừng đột ngột.",
|
||||
"auto_restarting": "Đang tự động khởi động lại công cụ…",
|
||||
"quit_running_message": "VoiceStudio vẫn đang xử lý.",
|
||||
"quit_running_detail": "Thoát bây giờ sẽ dừng các tác vụ đang chạy. Khi bạn mở lại VoiceStudio, các lô chưa xong sẽ tiếp tục và các bản kết xuất bị gián đoạn có thể được tiếp tục.",
|
||||
"quit_anyway": "Vẫn thoát",
|
||||
"keep_working": "Tiếp tục làm việc",
|
||||
"unresponsive": "Động cơ cục bộ đang bận và tạm thời không phản hồi — nó sẽ tự phục hồi.",
|
||||
"unresponsive_remote": "Không thể xác nhận kết nối tới công cụ từ xa — đang tự động thử lại.",
|
||||
"unhealthy": "Công cụ có phản hồi nhưng báo rằng nó không ổn định. Hãy xem Cài đặt → Nhật ký → Backend rồi thử lại.",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "正在启动本地引擎…",
|
||||
"attaching": "正在连接运行中的引擎…",
|
||||
"crashed": "本地引擎意外停止。",
|
||||
"auto_restarting": "正在自动重启引擎…",
|
||||
"quit_running_message": "VoiceStudio 仍在工作。",
|
||||
"quit_running_detail": "现在退出会停止正在运行的任务。再次打开 VoiceStudio 时,未完成的批处理会继续,中断的渲染可以恢复。",
|
||||
"quit_anyway": "仍然退出",
|
||||
"keep_working": "继续工作",
|
||||
"unresponsive": "本地引擎正忙,暂时没有响应,任务结束后会自动恢复。",
|
||||
"unresponsive_remote": "无法确认与远程引擎的连接,正在自动重试。",
|
||||
"unhealthy": "引擎有响应,但报告自身状态不正常。请查看 设置 → 日志 → 后端,然后重试。",
|
||||
|
||||
@@ -2213,6 +2213,11 @@
|
||||
"starting": "正在啟動本機引擎…",
|
||||
"attaching": "正在連線至執行中的引擎…",
|
||||
"crashed": "本機引擎意外停止。",
|
||||
"auto_restarting": "正在自動重新啟動引擎…",
|
||||
"quit_running_message": "VoiceStudio 仍在工作。",
|
||||
"quit_running_detail": "現在結束會停止正在執行的工作。再次開啟 VoiceStudio 時,未完成的批次會繼續,中斷的算繪可以繼續進行。",
|
||||
"quit_anyway": "仍要結束",
|
||||
"keep_working": "繼續工作",
|
||||
"unresponsive": "本機引擎忙碌中,暫時沒有回應,工作完成後會自動恢復。",
|
||||
"unresponsive_remote": "無法確認與遠端引擎的連線,正在自動重試。",
|
||||
"unhealthy": "引擎有回應,但回報自身狀態不正常。請查看 設定 → 記錄 → 後端,然後重試。",
|
||||
|
||||
@@ -1572,7 +1572,12 @@ try {
|
||||
await dialog.getByRole('button', { name: 'Voice', exact: true }).click();
|
||||
const voiceSearch = dialog.getByRole('combobox', { name: 'Voice', exact: true });
|
||||
await voiceSearch.waitFor({ timeout: 5000 });
|
||||
assert.equal(await voiceSearch.evaluate((input) => input === document.activeElement), true);
|
||||
// The picker moves focus a frame after the field becomes visible.
|
||||
await page.waitForFunction(
|
||||
(input) => input === document.activeElement,
|
||||
await voiceSearch.elementHandle(),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
await voiceSearch.fill('Fixture Voice');
|
||||
await dialog.getByRole('option', { name: 'Fixture Voice', exact: true }).waitFor();
|
||||
await voiceSearch.press('Enter');
|
||||
|
||||
@@ -9,16 +9,17 @@ from core import activity
|
||||
def isolated(monkeypatch):
|
||||
monkeypatch.setattr(activity, '_probes', {})
|
||||
monkeypatch.setattr(activity, '_inflight', 0)
|
||||
monkeypatch.setattr(activity, '_work_requests', 0)
|
||||
|
||||
|
||||
def run(app, path, scope_type='http'):
|
||||
def run(app, path, scope_type='http', method='GET'):
|
||||
async def receive():
|
||||
return {'type': 'http.request', 'body': b''}
|
||||
|
||||
async def send(_message):
|
||||
pass
|
||||
|
||||
asyncio.run(app({'type': scope_type, 'path': path}, receive, send))
|
||||
asyncio.run(app({'type': scope_type, 'path': path, 'method': method}, receive, send))
|
||||
|
||||
|
||||
def test_requests_reset_idle_time_but_owner_polls_do_not(isolated, monkeypatch):
|
||||
@@ -38,7 +39,24 @@ def test_requests_reset_idle_time_but_owner_polls_do_not(isolated, monkeypatch):
|
||||
run(middleware, '/profiles')
|
||||
assert seen == [0, 0, 1]
|
||||
clock[0] = 170.0
|
||||
assert activity.snapshot() == {'inflight': 0, 'busy': [], 'idle_seconds': 10.0}
|
||||
assert activity.snapshot() == {
|
||||
'inflight': 0, 'work_requests': 0, 'busy': [], 'idle_seconds': 10.0}
|
||||
|
||||
|
||||
def test_counts_open_requests_that_do_work_but_not_reads(isolated):
|
||||
# The desktop asks before a quit would cut a generation or transcription
|
||||
# short; an open read (or a WebSocket session) loses nothing.
|
||||
seen = []
|
||||
|
||||
async def endpoint(scope, receive, send):
|
||||
seen.append(activity.snapshot()['work_requests'])
|
||||
|
||||
middleware = activity.ActivityMiddleware(endpoint)
|
||||
run(middleware, '/profiles')
|
||||
run(middleware, '/generate', method='POST')
|
||||
run(middleware, '/ws/events', scope_type='websocket')
|
||||
assert seen == [0, 1, 0]
|
||||
assert activity.snapshot()['work_requests'] == 0
|
||||
|
||||
|
||||
def test_open_stream_keeps_the_backend_busy(isolated):
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Unfinished batch jobs survive a quit, crash or update restart.
|
||||
|
||||
The queue used to live only in memory: a backend restart dropped the rest of a
|
||||
long batch, and its uploads stayed on disk with nothing pointing at them.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def batch(tmp_path, monkeypatch):
|
||||
from api.routers import batch
|
||||
|
||||
monkeypatch.setattr(batch, "DATA_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(batch, "_jobs", {})
|
||||
monkeypatch.setattr(batch, "_queue", asyncio.Queue())
|
||||
monkeypatch.setattr(batch, "_ensure_queue", lambda: None)
|
||||
return batch
|
||||
|
||||
|
||||
def _queued(batch, tmp_path, job_id, created_at, status="queued"):
|
||||
root = tmp_path / "batch"
|
||||
root.mkdir(exist_ok=True)
|
||||
video = root / f"{job_id}.mp4"
|
||||
video.write_bytes(b"video")
|
||||
job = {
|
||||
"id": job_id, "status": status, "filename": f"{job_id}.mp4", "video_path": str(video),
|
||||
"langs": ["es", "fr"], "voice_id": "v1", "preserve_bg": False,
|
||||
"translation_provider": "argos", "created_at": created_at, "attempts": 2,
|
||||
}
|
||||
batch._jobs[job_id] = job
|
||||
batch._save_record(job)
|
||||
return job
|
||||
|
||||
|
||||
async def _restart(batch, monkeypatch):
|
||||
"""A fresh process: nothing in memory, only what is on disk."""
|
||||
monkeypatch.setattr(batch, "_jobs", {})
|
||||
monkeypatch.setattr(batch, "_queue", asyncio.Queue())
|
||||
return await batch.restore_interrupted_jobs()
|
||||
|
||||
|
||||
async def test_restart_queues_unfinished_jobs_again_in_order(batch, tmp_path, monkeypatch):
|
||||
_queued(batch, tmp_path, "second", created_at=20)
|
||||
running = _queued(batch, tmp_path, "first", created_at=10, status="running")
|
||||
partial = tmp_path / "batch" / "first"
|
||||
partial.mkdir()
|
||||
(partial / "dubbed_es.wav").write_bytes(b"half")
|
||||
|
||||
assert await _restart(batch, monkeypatch) == 2
|
||||
|
||||
assert [batch._queue.get_nowait(), batch._queue.get_nowait()] == ["first", "second"]
|
||||
job = batch._jobs["first"]
|
||||
assert job["status"] == "queued" and job["restored"] is True
|
||||
assert job["langs"] == ["es", "fr"] and job["voice_id"] == "v1"
|
||||
assert job["preserve_bg"] is False and job["attempts"] == 2
|
||||
assert job["video_path"] == running["video_path"]
|
||||
# A half-written output from the killed run is not mistaken for a result.
|
||||
assert not partial.exists()
|
||||
|
||||
|
||||
async def test_finished_cancelled_and_deleted_jobs_are_not_restored(batch, tmp_path, monkeypatch):
|
||||
for job_id in ("done", "cancelled", "deleted"):
|
||||
_queued(batch, tmp_path, job_id, created_at=1)
|
||||
batch._discard_record("done") # the worker's terminal path
|
||||
batch.cancel_batch_job("cancelled")
|
||||
batch._jobs["deleted"]["status"] = "failed"
|
||||
batch.delete_batch_job("deleted")
|
||||
|
||||
assert await _restart(batch, monkeypatch) == 0
|
||||
assert batch._jobs == {}
|
||||
|
||||
|
||||
async def test_shutdown_keeps_the_running_job_for_the_next_start(batch, tmp_path, monkeypatch):
|
||||
_queued(batch, tmp_path, "live", created_at=1)
|
||||
started = asyncio.Event()
|
||||
|
||||
async def pipeline(job_id, job):
|
||||
started.set()
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
monkeypatch.setattr(batch, "_run_batch_pipeline", pipeline)
|
||||
await batch._queue.put("live")
|
||||
worker = asyncio.ensure_future(batch._worker())
|
||||
await asyncio.wait_for(started.wait(), 5)
|
||||
worker.cancel() # backend shutdown cancels the worker task
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await worker
|
||||
|
||||
assert await _restart(batch, monkeypatch) == 1
|
||||
|
||||
|
||||
async def test_a_record_without_its_upload_or_outside_the_folder_is_dropped(batch, tmp_path, monkeypatch):
|
||||
gone = _queued(batch, tmp_path, "gone", created_at=1)
|
||||
(tmp_path / "batch" / "gone.mp4").unlink()
|
||||
outside = tmp_path / "elsewhere.mp4"
|
||||
outside.write_bytes(b"video")
|
||||
record = tmp_path / "batch" / "escape.queued.json"
|
||||
record.write_text(json.dumps({**gone, "id": "escape", "video_path": str(outside)}))
|
||||
(tmp_path / "batch" / "broken.queued.json").write_text("{not json")
|
||||
|
||||
assert await _restart(batch, monkeypatch) == 0
|
||||
assert not list((tmp_path / "batch").glob("*.queued.json"))
|
||||
assert outside.exists()
|
||||
|
||||
|
||||
async def test_records_hold_only_the_upload_name_and_survive_a_moved_data_folder(
|
||||
batch, tmp_path, monkeypatch):
|
||||
_queued(batch, tmp_path, "moved", created_at=1)
|
||||
record = json.loads((tmp_path / "batch" / "moved.queued.json").read_text())
|
||||
assert record["video_path"] == "moved.mp4"
|
||||
|
||||
# The user moves the data folder; the copied record still finds its upload.
|
||||
moved_to = tmp_path / "elsewhere"
|
||||
moved_to.mkdir()
|
||||
(tmp_path / "batch").rename(moved_to / "batch")
|
||||
monkeypatch.setattr(batch, "DATA_DIR", str(moved_to))
|
||||
assert await _restart(batch, monkeypatch) == 1
|
||||
assert batch._jobs["moved"]["video_path"] == str((moved_to / "batch" / "moved.mp4").resolve())
|
||||
|
||||
|
||||
async def test_a_save_racing_a_cancel_does_not_bring_the_job_back(batch, tmp_path, monkeypatch):
|
||||
job = _queued(batch, tmp_path, "raced", created_at=1)
|
||||
batch.cancel_batch_job("raced")
|
||||
batch._save_record(job) # the retry's write finishing after the cancel
|
||||
assert await _restart(batch, monkeypatch) == 0
|
||||
|
||||
|
||||
async def test_the_worker_drops_the_record_of_a_job_cancelled_while_queued(batch, tmp_path):
|
||||
job = _queued(batch, tmp_path, "skipped", created_at=1)
|
||||
job["status"] = "cancelled"
|
||||
await batch._queue.put("skipped")
|
||||
worker = asyncio.create_task(batch._worker())
|
||||
await batch._queue.join()
|
||||
worker.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await worker
|
||||
assert not (tmp_path / "batch" / "skipped.queued.json").exists()
|
||||
|
||||
|
||||
async def test_a_record_that_cannot_be_removed_is_marked_finished(batch, tmp_path, monkeypatch):
|
||||
_queued(batch, tmp_path, "stuck", created_at=1)
|
||||
(tmp_path / "batch" / "stuck").mkdir()
|
||||
(tmp_path / "batch" / "stuck" / "dubbed_es.mp4").write_bytes(b"result")
|
||||
|
||||
def refuse(_path):
|
||||
raise batch.FileCleanupError("locked")
|
||||
|
||||
monkeypatch.setattr(batch, "unlink_if_present", refuse)
|
||||
batch._discard_record("stuck") # the worker's terminal path
|
||||
monkeypatch.undo()
|
||||
monkeypatch.setattr(batch, "DATA_DIR", str(tmp_path))
|
||||
assert await _restart(batch, monkeypatch) == 0
|
||||
# The finished job's results are left alone.
|
||||
assert (tmp_path / "batch" / "stuck" / "dubbed_es.mp4").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field, value", [
|
||||
("created_at", "yesterday"), ("created_at", True), ("attempts", "2"), ("attempts", 0),
|
||||
("langs", ["es", 3]), ("video_path", 7), ("voice_id", ["v1"]),
|
||||
])
|
||||
async def test_one_malformed_record_is_dropped_without_blocking_the_rest(
|
||||
batch, tmp_path, monkeypatch, field, value):
|
||||
_queued(batch, tmp_path, "good", created_at=5)
|
||||
_queued(batch, tmp_path, "bad", created_at=1)
|
||||
path = tmp_path / "batch" / "bad.queued.json"
|
||||
record = json.loads(path.read_text())
|
||||
record[field] = value
|
||||
path.write_text(json.dumps(record))
|
||||
|
||||
assert await _restart(batch, monkeypatch) == 1
|
||||
assert list(batch._jobs) == ["good"]
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
async def test_a_job_finding_its_speech_model_removed_fails_instead_of_downloading(
|
||||
monkeypatch, tmp_path):
|
||||
# Enqueue checks the model; a job that waited in the queue (or came back
|
||||
# after a restart) must check again rather than let the transcriber fetch it.
|
||||
from api.routers import batch
|
||||
from services import asr_backend
|
||||
|
||||
monkeypatch.setattr(batch, "DATA_DIR", str(tmp_path))
|
||||
missing = {"error": "asr_model_missing", "missing_repo_id": "Systran/faster-whisper-large-v3",
|
||||
"recommended": None}
|
||||
monkeypatch.setattr(asr_backend, "asr_model_missing_error", lambda **_kw: missing)
|
||||
loaded = []
|
||||
monkeypatch.setattr(asr_backend, "load_active_asr_backend", lambda: loaded.append(1))
|
||||
|
||||
class _Probe:
|
||||
stdout = b""
|
||||
stderr = b"Duration: 00:00:02.00, start: 0.000000, bitrate: 1000 kb/s\n"
|
||||
|
||||
monkeypatch.setattr("subprocess.run", lambda *a, **k: _Probe())
|
||||
monkeypatch.setattr("services.ffmpeg_utils.find_ffmpeg", lambda: "ffmpeg")
|
||||
video = tmp_path / "in.mp4"
|
||||
video.write_bytes(b"video")
|
||||
job = {"id": "nomodel", "status": "running", "filename": "in.mp4", "video_path": str(video),
|
||||
"langs": ["es"], "voice_id": None, "preserve_bg": False,
|
||||
"translation_provider": "argos", "created_at": 1, "attempts": 1}
|
||||
with pytest.raises(RuntimeError, match="(?i)model"):
|
||||
await batch._run_batch_pipeline("nomodel", job)
|
||||
assert loaded == []
|
||||
Reference in new issue
Block a user