Files
VoiceStudio/tests/test_backend_activity.py
Palash Debnath d6bd82844c 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.
2026-12-04 03:43:28 +05:30

103 lines
3.5 KiB
Python

"""The idle signal the desktop app uses to stop a terminal-started backend."""
import asyncio
import pytest
from core import activity
@pytest.fixture
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', method='GET'):
async def receive():
return {'type': 'http.request', 'body': b''}
async def send(_message):
pass
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):
clock = [100.0]
monkeypatch.setattr(activity.time, 'monotonic', lambda: clock[0])
activity.touch()
seen = []
async def endpoint(scope, receive, send):
seen.append(activity.snapshot()['inflight'])
middleware = activity.ActivityMiddleware(endpoint)
clock[0] = 160.0
run(middleware, '/health')
run(middleware, '/system/activity')
assert activity.snapshot()['idle_seconds'] == 60.0
run(middleware, '/profiles')
assert seen == [0, 0, 1]
clock[0] = 170.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):
gate = asyncio.Event()
snapshots = []
async def stream(scope, receive, send):
await gate.wait()
async def scenario():
task = asyncio.create_task(activity.ActivityMiddleware(stream)(
{'type': 'websocket', 'path': '/ws/events'}, None, None))
await asyncio.sleep(0)
snapshots.append(activity.snapshot())
gate.set()
await task
asyncio.run(scenario())
assert snapshots[0]['inflight'] == 1 and snapshots[0]['idle_seconds'] == 0
assert activity.snapshot()['inflight'] == 0
def test_running_work_and_unreadable_registries_keep_the_backend_alive(isolated):
def broken():
raise RuntimeError('registry changed during iteration')
activity.register_probe('downloads', lambda: True)
activity.register_probe('calls', lambda: False)
activity.register_probe('jobs', broken)
state = activity.snapshot()
assert state['busy'] == ['downloads', 'jobs']
assert state['idle_seconds'] == 0
def test_owning_modules_register_their_work():
import importlib
for module in ['core.job_store', 'services.proc_registry', 'services.dub_pipeline',
'services.sidecar_install', 'services.audiocpp_runtime_install',
'api.routers.batch', 'api.routers.setup.download', 'api.routers.project_bundles',
'services.telephony.calls']:
importlib.import_module(module)
assert {'jobs', 'subprocesses', 'dub-ingest', 'engine-installs', 'runtime-install', 'batch',
'model-downloads', 'project-transfers', 'calls'} <= set(activity._probes)