feat(cli): add the voicestudio terminal command

Add a terminal command that drives the desktop app's local backend.

- The desktop app owns the backend. When no backend answers, the CLI
  starts the installed app in the background (no window); it publishes
  its address in backend.json and quits after 10 idle minutes. Opening
  the app later shows a window in the same process, so a terminal
  session and the GUI never run two backends.
- The backend reports activity (requests, jobs, downloads, installs,
  calls) at /system/activity so idle shutdown never interrupts work, and
  holds a kernel lock on its data directory so a second backend fails
  fast with an actionable message.
- `voicestudio stop` stops a background app; commands that only report
  state never start it, and `status` exits 3 when it is not running.
- Output is readable tables and fields chosen from each result's shape;
  `--json` prints the raw data and piped output is tab-separated.
- Tab completion for bash, zsh, fish and PowerShell
  (`voicestudio completion <shell>`), without building the command tree.
- `voicestudio update` opens the app's updater; the CLI itself makes no
  network requests.
- Settings → General shows the terminal command and can add it to PATH
  on request; shell profiles are only edited with that consent.
This commit is contained in:
mostafa-ismail-2004 committed 2026-11-05 18:18:58 +02:00
1 parent 522bdc0e34
commit 4708ae9a51
109 files changed
+8650 -36

No files matched your search

+14 -1
View File
@@ -314,7 +314,7 @@ jobs:
run: bun run check:electron
- name: Snap artifact repair regression
run: node --test electron/tests/snap-artifact-verification.test.mjs electron/tests/snap-launcher.test.mjs electron/tests/snap-store-packaging.test.mjs electron/tests/omnivoice-tts-bundle.test.mjs
run: node --test electron/tests/snap-artifact-verification.test.mjs electron/tests/snap-launcher.test.mjs electron/tests/snap-store-packaging.test.mjs electron/tests/omnivoice-tts-bundle.test.mjs electron/tests/cli-bundle.test.mjs
# Split from Tests (Electron) so the two ~7 minute halves run side by side.
# The browser workflow smokes need only the checked-out sources.
@@ -754,6 +754,19 @@ jobs:
HF_HUB_OFFLINE: "1" # same no-silent-downloads guard as the main pytest job
HF_HUB_CACHE: ${{ runner.temp }}/pockettts-empty-hf-cache
- name: Run terminal command tests
# Desktop discovery, background launch and the data-directory lock
# (flock vs msvcrt) differ per OS; the Linux `test` job alone misses that.
if: matrix.backend_supported
run: uv run --no-sync pytest tests/cli/ tests/test_runtime_owner.py tests/test_backend_activity.py -q --tb=short
env:
HF_HUB_OFFLINE: "1"
- name: Run terminal command tests on the newest supported Python
# The CLI supports Python 3.11+ (uv/pip installs); argparse wording and
# stdlib behaviour change between versions, which 3.11 alone misses.
run: uvx --python 3.13 --with pytest pytest tests/cli -q --tb=short -p no:cacheprovider --rootdir tests/cli --confcutdir tests/cli
# The isolated backend session, on Windows. The `test` job runs it on
# Linux only, which is how four tests that CANNOT pass on Windows shipped
# unnoticed: two reach for os.WNOHANG and os.waitid (POSIX-only, an
+5 -1
View File
@@ -40,7 +40,7 @@ AGPL-3.0 text in [`LICENSE`](LICENSE).)
These terms cover the VoiceStudio application — the Electron desktop and web
app (`electron/`), its native desktop helper (`native/`), the FastAPI backend
(`backend/`), and supporting build / packaging files (`scripts/`, `deploy/`,
(`backend/`), the unified command package (`cli/`), and supporting build / packaging files (`scripts/`, `deploy/`,
`.github/`). Electron components adapted from T3 Code keep their MIT notice in
`electron/T3CODE-LICENSE.txt`.
@@ -82,6 +82,10 @@ model currently has the complete evidence needed for this reviewed workflow.
Third-party dependencies retain their own licenses. See `bun.lock`, `uv.lock`,
and `native/desktop-bridge/Cargo.lock` for the resolved set.
The desktop's terminal command bundles a Python interpreter using PyInstaller
(build pin in `electron/cli-bundle.mjs`). Interpreter and bootloader notices ship
under `resources/cli/_internal/licenses` (`Contents/Resources` on macOS).
The locked PyAV 15.1.0 wheels bundle FFmpeg and x264/x265 libraries. PyAV's source
licence alone does not describe those binaries' terms. The
[wheel audit](docs/licensing/pyav-15.1.0-audit.md) records their hashes, build flags,
+1 -1
View File
@@ -174,7 +174,7 @@ Upgrading from 0.5.3 or older (the Tauri app)? [Install the new app separately](
| Setup help | [Troubleshooting](docs/install/troubleshooting.md) · [Model downloads](docs/downloading-models.md) |
| Guides | [Multi-speaker dubbing](docs/dubbing/multi-speaker-guide.md) · [Expressive speech](docs/expressive-speech.md) · [Exporting dubs](docs/dubbing/export.md) |
| Models & quality | [Engine guides](docs/engines/README.md) · [whisper.cpp ASR](docs/engines/whisper-cpp.md) · [Benchmarks](docs/benchmarks.md) |
| Integrations | [Local API](docs/speech-platform.md) · [MCP](docs/mcp.md) · [Examples](examples/README.md) |
| Integrations | [CLI](docs/install/script.md#terminal-command) · [Local API](docs/speech-platform.md) · [MCP](docs/mcp.md) · [Examples](examples/README.md) |
| Phone apps | [iOS and Android](docs/mobile.md) |
| Development | [Contributing](.github/CONTRIBUTING.md) ([sign the CLA](.github/CONTRIBUTING.md#contribution-licensing) before your first PR) · [Changelog](CHANGELOG.md) |
+5
View File
@@ -67,6 +67,11 @@ _job_reservations: set[str] = set()
_reservation_lock = threading.Lock()
_jobs: dict = {} # job_id → status dict
from core import activity as _activity # noqa: E402
_activity.register_probe("batch", lambda: any(
job.get("status") not in {"done", "failed", "cancelled"} for job in list(_jobs.values())))
class BatchJobStatus(BaseModel):
id: str
+4
View File
@@ -28,6 +28,10 @@ MAX_RETAINED_EXPORT_BYTES = 2 * bundles.MAX_TOTAL
_transfer_lock = threading.RLock()
_active_transfers: dict[Path, int] = {}
from core import activity as _activity # noqa: E402
_activity.register_probe("project-transfers", lambda: any(count > 0 for count in list(_active_transfers.values())))
class _BundleResponse(FileResponse):
"""Keep a retained export alive until its last in-flight download finishes."""
+4
View File
@@ -99,6 +99,10 @@ _active_installs_lock = threading.Lock()
_install_tasks: set[asyncio.Task] = set()
_install_tasks_by_repo: dict[str, asyncio.Task] = {}
from core import activity as _activity # noqa: E402
_activity.register_probe("model-downloads", lambda: bool(_active_installs or _install_tasks))
def _download_max_workers() -> int:
"""Parallel-FILES worker count for snapshot_download (FDL-02). Default 8 —
+88
View File
@@ -0,0 +1,88 @@
"""Report whether this backend is doing work, for idle shutdown by its owner.
The desktop app stops a backend it started for a terminal command once the
backend has been idle for a while. "Idle" must be conservative: a dub, a batch,
a model download or an open stream all keep it alive. Requests and WebSocket
sessions are counted by middleware; long-running work that outlives its request
registers a probe from the module that owns the work, so this module never
imports engine code and new job types extend the rule where they are defined.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Callable
from starlette.types import ASGIApp, Receive, Scope, Send
logger = logging.getLogger("omnivoice.activity")
# Polls of these paths are how owners observe the backend; they are not use.
_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity"})
_lock = threading.Lock()
_inflight = 0
_last_activity = time.monotonic()
_probes: dict[str, Callable[[], bool]] = {}
def register_probe(name: str, probe: Callable[[], bool]) -> None:
"""Register ``probe() -> True`` while work named ``name`` is running."""
with _lock:
_probes[name] = probe
def touch() -> None:
global _last_activity
with _lock:
_last_activity = time.monotonic()
def _enter() -> None:
global _inflight, _last_activity
with _lock:
_inflight += 1
_last_activity = time.monotonic()
def _leave() -> None:
global _inflight, _last_activity
with _lock:
_inflight -= 1
_last_activity = time.monotonic()
def snapshot() -> dict:
with _lock:
inflight = _inflight
idle = time.monotonic() - _last_activity
probes = list(_probes.items())
busy = []
for name, probe in probes:
try:
if probe():
busy.append(name)
except Exception:
# An unreadable registry must keep the backend alive, never stop it.
logger.debug("activity probe %s failed", name, exc_info=True)
busy.append(name)
if inflight or busy:
idle = 0.0
return {"inflight": inflight, "busy": sorted(busy), "idle_seconds": round(idle, 1)}
class ActivityMiddleware:
"""Count open HTTP requests (including streams) and WebSocket sessions."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in {"http", "websocket"} or scope.get("path") in _PASSIVE_PATHS:
await self.app(scope, receive, send)
return
_enter()
try:
await self.app(scope, receive, send)
finally:
_leave()
+13
View File
@@ -186,3 +186,16 @@ def sweep_orphans_on_startup() -> int:
if n:
logger.info("Job sweep: marked %d orphaned job(s) as failed after restart.", n)
return n
def has_active() -> bool:
"""Whether any persisted job is still queued or running in this process."""
with db_conn() as conn:
return conn.execute(
"SELECT 1 FROM jobs WHERE status IN ('pending', 'running') LIMIT 1"
).fetchone() is not None
from core import activity as _activity # noqa: E402
_activity.register_probe("jobs", has_active)
+67
View File
@@ -0,0 +1,67 @@
"""Allow one backend process per data directory.
The lock file is never removed: replacing it would let two processes lock
different inodes. Kernel locks, rather than saved PIDs, establish ownership, so
a crashed backend releases the directory with its process.
"""
from __future__ import annotations
import errno
import os
from pathlib import Path
import time
_CONTENDED = {errno.EAGAIN, errno.EACCES, getattr(errno, 'EWOULDBLOCK', errno.EAGAIN),
getattr(errno, 'EDEADLK', 36), 36}
class DataDirectoryBusy(RuntimeError):
pass
class DataDirectoryLease:
def __init__(self, directory: str | os.PathLike[str], timeout: float = 0) -> None:
self.directory = Path(directory)
self.timeout = timeout
self.stream = None
def __enter__(self) -> DataDirectoryLease:
self.directory.mkdir(parents=True, exist_ok=True)
fd = os.open(self.directory / '.runtime.lock', os.O_RDWR | os.O_CREAT, 0o600)
self.stream = os.fdopen(fd, 'r+b', buffering=0)
if os.fstat(fd).st_size == 0:
self.stream.write(b'\0')
deadline = time.monotonic() + self.timeout
while True:
try:
if os.name == 'nt':
import msvcrt
self.stream.seek(0)
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return self
except OSError as exc:
if exc.errno not in _CONTENDED:
self.stream.close()
raise
if time.monotonic() >= deadline:
self.stream.close()
raise DataDirectoryBusy(
f'Another VoiceStudio backend is already using {self.directory}. '
'Quit VoiceStudio (or run "voicestudio stop"), or set OMNIVOICE_DATA_DIR '
'to a different folder, then start this backend again.') from None
time.sleep(.05)
def __exit__(self, *args: object) -> None:
try:
if os.name == 'nt':
import msvcrt
self.stream.seek(0)
msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN)
finally:
self.stream.close()
+24 -1
View File
@@ -1242,7 +1242,7 @@ async def _phase_b(app: FastAPI) -> None:
@asynccontextmanager
async def lifespan(app: FastAPI):
async def _application_lifespan(app: FastAPI):
from api.dependencies import validate_server_admin_key
validate_server_admin_key()
@@ -1464,6 +1464,18 @@ async def lifespan(app: FastAPI):
from core.version import APP_VERSION # single source of truth (pyproject metadata)
@asynccontextmanager
async def lifespan(app: FastAPI):
from core.runtime_owner import DataDirectoryLease
from core.config import DATA_DIR
# One backend per data directory: two would race on the database, job
# recovery and model files. Held through teardown, where workers can still
# write. The short wait covers a restart whose predecessor is still exiting.
with DataDirectoryLease(DATA_DIR, timeout=15):
async with _application_lifespan(app):
yield
app = FastAPI(
title=f"{PRODUCT_NAME} API",
version=APP_VERSION,
@@ -1975,6 +1987,9 @@ _allowed = allowed_origin_values()
# Registered FIRST → innermost: the startup gate holds every request except
# the two probe paths until the deferred startup completes (and is a no-op
# forever after).
from core.activity import ActivityMiddleware
# Innermost: only requests that passed every gate count as use of the backend.
app.add_middleware(ActivityMiddleware)
from core.render_trace import RenderTraceMiddleware
app.add_middleware(RenderTraceMiddleware)
app.add_middleware(StartupGateMiddleware)
@@ -2109,6 +2124,14 @@ async def health():
return {"status": "ok", "device": _cached_health_device(), "version": APP_VERSION}
# The desktop app polls this to stop a backend it started for terminal
# commands once nothing has used it for a while (see core/activity.py).
@app.get("/system/activity", include_in_schema=False)
async def system_activity():
from core import activity
return activity.snapshot()
# ── Startup progress ────────────────────────────────────────────────────
# Always 200, even post-ready — the one endpoint whose job is to say what the
# backend is doing before it can serve, so "starting at step X" / "ready" /
@@ -21,6 +21,10 @@ _CHUNK = 256 * 1024
_lock = threading.Lock()
_job = {"state": "idle", "progress": 0.0, "error": None}
from core import activity as _activity # noqa: E402
_activity.register_probe("runtime-install", lambda: _job.get("state") == "running")
def _snapshot() -> dict:
with _lock:
+4
View File
@@ -134,6 +134,10 @@ _dub_jobs_lock = threading.RLock()
#: that has no row yet — it would appear in no id list otherwise.
_inflight_jobs: set[str] = set()
from core import activity as _activity # noqa: E402
_activity.register_probe("dub-ingest", lambda: bool(_inflight_jobs))
#: Recently-deleted job ids, most-recent last. Guarded by ``_dub_jobs_lock``.
#:
#: Dict membership alone cannot express "the user withdrew this job" (#1252
+4
View File
@@ -21,6 +21,10 @@ logger = logging.getLogger("omnivoice.api")
_active_procs: dict[str, list] = {}
_active_procs_lock = threading.Lock()
from core import activity as _activity # noqa: E402
_activity.register_probe("subprocesses", lambda: any(list(_active_procs.values())))
def register_proc(job_id: str, proc) -> None:
"""Track an in-flight subprocess so /dub/abort can kill it."""
+5
View File
@@ -1033,6 +1033,11 @@ STEP_IDS = (
_jobs: dict[str, dict] = {}
_jobs_lock = threading.Lock()
from core import activity as _activity # noqa: E402
_activity.register_probe("engine-installs", lambda: any(
job.get("state") == "running" for job in list(_jobs.values())))
# Guards each job's log deque: the worker thread appends while the status
# poll copies it, and list() over a deque raises RuntimeError if it mutates
# mid-iteration. One module-level lock is plenty — appends are tiny and at
+4
View File
@@ -396,6 +396,10 @@ def delete_record(call_id: str) -> bool:
_sessions: dict[str, CallSession] = {}
_registry_lock = threading.Lock()
from core import activity as _activity # noqa: E402
_activity.register_probe("calls", lambda: bool(_sessions))
def get_live(call_id: str) -> CallSession | None:
with _registry_lock:
+5
View File
@@ -0,0 +1,5 @@
"""Native console entry point built from the same package as the Python wheel."""
from voicestudio_cli.__main__ import main
if __name__ == '__main__':
raise SystemExit(main())
+25
View File
@@ -0,0 +1,25 @@
"""Derive release metadata from the repository's single version source."""
import json
from pathlib import Path
from hatchling.metadata.plugin.interface import MetadataHookInterface
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class CustomMetadataHook(MetadataHookInterface):
def update(self, metadata):
root = Path(self.root)
canonical = root.parent / 'package.json'
if not canonical.is_file():
canonical = root / 'package.json' # Included verbatim in source distributions.
version = json.loads(canonical.read_text(encoding='utf-8'))['version']
metadata['version'] = version.replace('-beta.', 'b')
class CustomBuildHook(BuildHookInterface):
def initialize(self, version, build_data):
root = Path(self.root)
license_file = root.parent / 'LICENSE'
if not license_file.is_file():
license_file = root / 'LICENSE'
if self.target_name == 'wheel':
build_data.setdefault('force_include', {})[str(license_file)] = 'voicestudio_cli/licenses/AGPL-3.0.txt'
+28
View File
@@ -0,0 +1,28 @@
[build-system]
requires = ["hatchling==1.27.0"]
build-backend = "hatchling.build"
[project]
name = "voicestudio-cli"
dynamic = ["version"]
description = "Unified VoiceStudio desktop launcher and HTTP command-line client"
requires-python = ">=3.11"
license = "AGPL-3.0-only"
dependencies = []
[project.scripts]
voicestudio = "voicestudio_cli.__main__:main"
[tool.hatch.metadata.hooks.custom]
[tool.hatch.build.targets.wheel]
packages = ["voicestudio_cli"]
[tool.hatch.build.hooks.custom]
[tool.hatch.build.targets.sdist]
include = ["voicestudio_cli", "frozen_main.py", "hatch_build.py", "pyproject.toml", "package.json", "LICENSE"]
[tool.hatch.build.targets.sdist.force-include]
"../package.json" = "package.json"
"../LICENSE" = "LICENSE"
+1
View File
@@ -0,0 +1 @@
"""VoiceStudio desktop launcher and standard-library HTTP CLI."""
+961
View File
@@ -0,0 +1,961 @@
"""Command tree and shared terminal contracts."""
import argparse
import difflib
import io
import json
import math
import os
from pathlib import Path
import re
import sys
import tempfile
from contextlib import contextmanager
from urllib.parse import quote
from .application import app_version, installed_application
from .config import connection, load_config, save_config
from .errors import CLIError, scrub
from .registry import COMMANDS
from .transport import Client, download
from . import updates
from .desktop import launch_desktop, split_arguments
from .render import render
class Parser(argparse.ArgumentParser):
"""argparse with plain-language errors that do not depend on its message wording."""
def _check_value(self, action, value):
# argparse's own "invalid choice" text differs between Python versions,
# so build the message from the real choices instead of parsing it.
if action.choices is None or value in action.choices:
return
choices = [str(choice) for choice in action.choices]
listed = choices
if isinstance(action, argparse._SubParsersAction):
listed = [choice.dest for choice in action._choices_actions] # visible names only
close = difflib.get_close_matches(str(value), listed, n=1)
if isinstance(action, argparse._SubParsersAction):
message = f"Unknown command '{value}'."
else:
name = (action.metavar if isinstance(action.metavar, str) else None) or (
action.option_strings[-1] if action.option_strings else action.dest)
message = f"'{value}' is not a valid {name.lstrip('-').replace('-', ' ').replace('_', ' ').lower()}."
if not close:
message += ' Choose one of: ' + ', '.join(listed) + '.'
if close:
message += f" Did you mean '{close[0]}'?"
raise CLIError('usage_error', f'{message} Run {self.prog} --help.', exit_code=2)
def error(self, message):
message = message[:1].upper() + message[1:].rstrip('.') + '.'
raise CLIError('usage_error', f'{message} Run {self.prog} --help.', exit_code=2)
class AppVersionAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print('VoiceStudio ' + app_version())
parser.exit()
def positive(value):
try:
number = float(value)
except ValueError:
raise argparse.ArgumentTypeError('must be a positive number') from None
if not math.isfinite(number) or number <= 0:
raise argparse.ArgumentTypeError('must be a positive finite number')
return number
def common(parser):
# Suppressed defaults prevent a nested parser resetting inherited flags.
parser.add_argument('--url', default=argparse.SUPPRESS,
help='Use the VoiceStudio backend at this address instead of this computer\'s app')
parser.add_argument('--json', action='store_true', default=argparse.SUPPRESS,
help='Print machine-readable JSON (errors too, on stderr)')
parser.add_argument('--verbose', action='store_true', default=argparse.SUPPRESS,
help='Show more detail when something goes wrong')
parser.add_argument('--timeout', type=positive, default=argparse.SUPPRESS,
help='Seconds to wait for a response (default: 600)')
parser.add_argument('-o', '--output', default=argparse.SUPPRESS,
help='Save the result to this file; - prints it')
parser.add_argument('--overwrite', action='store_true', default=argparse.SUPPRESS,
help='Replace the --output file if it exists')
parser.add_argument('--yes', action='store_true', default=argparse.SUPPRESS,
help='Delete without asking for confirmation')
# Commands with hand-written arguments and handlers (the rest come from the registry).
CUSTOM = {'status', 'version', 'help', 'connection show', 'connection set', 'connection test',
'connection auth set', 'connection auth clear', 'speak', 'transcribe', 'translate-audio',
'voices clone', 'voices design', 'voices describe', 'voices consent show',
'voices compare', 'projects rename', 'history star', 'history unstar',
'models list', 'models install', 'models install-cancel', 'models license accept',
'engines list', 'engines select', 'engines install', 'engines install-status',
'settings get', 'settings set', 'settings hf-token set',
'integrations api docs', 'integrations mcp config', 'integrations mcp bindings set',
'dub export', 'update', 'update info', 'update check', 'stop', 'completion'}
def build_parser(only=None):
"""The command tree; ``only`` builds just one command path, for fast completion."""
root = Parser(prog='voicestudio', description='Launch VoiceStudio with no arguments, or use its features from the terminal.', allow_abbrev=False)
common(root)
root.add_argument('-v', '--version', action=AppVersionAction, nargs=0, help='Show the installed VoiceStudio version')
nodes = {(): root}
groups = {}
def command(path, handler, description, hidden=False):
parts = tuple(path.split())
for n in range(1, len(parts) + 1):
key, parent = parts[:n], parts[:n-1]
if key not in nodes:
if parent not in groups:
groups[parent] = nodes[parent].add_subparsers(dest=f'command_{n}', title='Commands', metavar='COMMAND')
if n == len(parts):
text = description
elif hidden:
text = 'Former command group; run voicestudio --help for current names'
else:
text = GROUPS.get(' '.join(key), key[-1])
# Old names stay accepted but are left out of help listings.
listing = {} if hidden else {'help': text}
parser = groups[parent].add_parser(key[-1], description=text, allow_abbrev=False, **listing)
common(parser)
nodes[key] = parser
parser = nodes[parts]
parser.set_defaults(handler=handler)
return parser
def paths(name):
"""The public path, plus the hidden former path of a renamed command."""
description = DESCRIPTIONS.get(name) or next(spec.description for spec in COMMANDS if spec.name == name)
if name in HIDDEN:
yield name, f'Former command; run voicestudio --help for current names', True
return
yield RENAMED.get(name, name), description, False
if name in RENAMED:
yield name, f'Former name of voicestudio {RENAMED[name]}', True
custom = CUSTOM
def registry_args(p, spec):
p.set_defaults(spec=spec)
for param in spec.params:
p.add_argument(param, help='Backend resource identifier')
if spec.upload:
p.add_argument('input', help='Local file to upload; - reads stdin')
p.add_argument('--stdin-filename', default='upload.bin', help='Filename/format hint for stdin uploads')
p.add_argument('--file', help='Request details as a JSON file; - reads stdin' if spec.body
else 'Request details as a JSON file (optional); - reads stdin')
p.add_argument('--field', action='append', default=[], metavar='NAME=VALUE', help='Request field; values accept JSON or plain text')
p.add_argument('--query', action='append', default=[], metavar='NAME=VALUE', help='Query parameter')
def custom_args(p, name):
if name == 'help':
p.add_argument('path', nargs='*', help='Command path to describe')
elif name == 'completion':
p.add_argument('shell', choices=['bash', 'zsh', 'fish', 'powershell'])
elif name in {'connection set'}:
p.add_argument('backend_url')
elif name == 'connection test':
p.add_argument('backend_url', nargs='?')
elif name == 'connection auth set' or name == 'settings hf-token set':
p.add_argument('--stdin', action='store_true', required=True)
elif name in {'speak', 'voices compare'}:
if name == 'voices compare':
p.add_argument('ids', nargs='+')
p.add_argument('--out-dir', required=True)
p.add_argument('--text', required=True)
else:
p.add_argument('text', nargs='?')
p.add_argument('--text-file')
p.add_argument('--voice', required=name == 'speak')
p.add_argument('--engine', help='Per-request TTS engine override')
p.add_argument('--language')
p.add_argument('--speed', type=positive, default=1)
p.add_argument('--seed', type=int)
p.add_argument('--instruct')
elif name in {'transcribe', 'translate-audio'}:
p.add_argument('input')
p.add_argument('--model', default='whisper-1', help='ASR compatibility alias or the already-active ASR engine ID')
p.add_argument('--language')
p.add_argument('--format', choices=['text', 'json', 'verbose_json', 'srt', 'vtt'], default='text')
p.add_argument('--stdin-filename', default='audio.wav')
elif name in {'voices clone', 'voices design'}:
p.add_argument('--name', required=True)
p.add_argument('--language', default='Auto')
p.add_argument('--engine')
if name.endswith('clone'):
p.add_argument('--audio', required=True)
p.add_argument('--ref-text', default='')
else:
p.add_argument('--description', required=True)
elif name == 'voices describe':
p.add_argument('description')
elif name == 'voices consent show':
p.add_argument('id')
elif name in {'projects rename'}:
p.add_argument('id'); p.add_argument('name')
elif name in {'history star', 'history unstar'}:
p.add_argument('id')
elif name == 'models list':
p.add_argument('--installed', action='store_true')
elif name in {'models install', 'models install-cancel', 'models license accept'}:
p.add_argument('id', help='Catalogue model ID from models list')
if name != 'models install-cancel':
p.add_argument('--accept-license', action='store_true', help='Explicitly accept the displayed current model terms')
elif name in {'engines list', 'engines select', 'engines install', 'engines install-status'}:
p.add_argument('--type', choices=['tts', 'asr', 'llm', 'translation', 'diarisation'],
required=name != 'engines list')
if name != 'engines list':
p.add_argument('id')
if name == 'engines select':
p.add_argument('--model', help='Supported engine-specific checkpoint ID')
elif name in {'settings get', 'settings set'}:
p.add_argument('key', choices=list(SETTINGS), metavar='SETTING', nargs='?' if name == 'settings get' else None,
help='Setting name (see the list below)' + ('; omit to show all' if name == 'settings get' else ''))
if name == 'settings set':
p.add_argument('value', help='New value: JSON or plain text')
p.formatter_class = argparse.RawDescriptionHelpFormatter
p.epilog = 'Settings:\n' + '\n'.join(f' {key:<21} {text}' for key, text in SETTING_HELP.items())
elif name == 'integrations mcp config':
p.add_argument('--client', default='generic', choices=['generic', 'claude-code', 'cursor', 'codex'])
elif name == 'integrations mcp bindings set':
p.add_argument('client'); p.add_argument('--voice', required=True)
elif name == 'dub export':
p.add_argument('id')
p.add_argument('--format', choices=list(DUB_EXPORTS), default='video')
p.add_argument('--language')
def wanted(path):
return only is None or tuple(path.split()) == tuple(only)
for spec in COMMANDS:
if spec.name not in custom:
for path, description, hidden in paths(spec.name):
if wanted(path):
registry_args(command(path, spec.name, description, hidden), spec)
for name in sorted(custom, key=lambda name: (len(name.split()), name)):
for path, description, hidden in paths(name):
if wanted(path):
custom_args(command(path, name, description, hidden), name)
# Groups without a handler show their own remaining command tree.
for key, parser in nodes.items():
parser.set_defaults(current_parser=parser)
name = parser.get_default('handler')
spec = parser.get_default('spec')
hidden = set()
if not key:
hidden = {'output', 'overwrite', 'yes'}
elif parser.get_default('handler') is None:
hidden = set(GLOBAL_FLAGS) # a group only lists its commands
else:
if name in OFFLINE:
hidden |= {'url', 'timeout', 'output', 'overwrite'}
if not (spec and spec.destructive):
hidden.add('yes')
for action in parser._actions:
if action.dest in hidden:
action.help = argparse.SUPPRESS
# A command whose subcommands are all former names lists no "Commands:" section.
for group in groups.values():
if not group._choices_actions:
group.help = argparse.SUPPRESS
return root, nodes
DESCRIPTIONS = {
'version': 'Show the installed VoiceStudio version',
'help': 'Show help for a command, for example: voicestudio help voices clone',
'status': 'Show whether VoiceStudio is running',
'stop': 'Stop VoiceStudio when it runs in the background for terminal commands',
'speak': 'Turn text into speech with a saved voice (by name or ID)',
'transcribe': 'Turn speech in an audio file into text',
'translate-audio': 'Turn speech in an audio file into English text',
'connection show': 'Show which VoiceStudio backend commands use',
'connection set': 'Use another VoiceStudio backend, for example on another computer',
'connection test': 'Check that the selected backend responds',
'connection auth set': 'Save the API key for the selected backend (read from stdin)',
'connection auth clear': 'Forget the saved API key',
'voices clone': 'Create a voice from a recording',
'voices design': 'Create a voice from a text description',
'voices describe': 'Preview how a text description maps to voice-design settings',
'voices compare': 'Speak the same text with several voices to compare them',
'voices consent show': 'Show the consent recorded for a voice',
'projects rename': 'Rename a project',
'history star': 'Star a generated clip',
'history unstar': 'Remove the star from a generated clip',
'models list': 'List available models',
'models install': "Download a model (after you accept its license)",
'models install-cancel': 'Stop a model download',
'models license accept': "Accept a model's license terms",
'engines list': 'List engines',
'engines select': 'Choose the engine used for a task',
'engines install': 'Install an engine',
'engines install-status': 'Show engine installation progress',
'settings get': 'Show settings',
'settings set': 'Change a setting',
'settings hf-token set': 'Save a Hugging Face token (read from stdin)',
'integrations api docs': 'Show the address of the API documentation',
'integrations mcp config': 'Print the configuration that connects an AI agent to VoiceStudio',
'integrations mcp bindings set': 'Choose the voice an AI agent uses',
'dub export': 'Save a dubbed video, audio track or subtitles',
'update': "Open the app's updater to check for and install an update",
'update info': 'Show how VoiceStudio is installed and how it updates',
'update check': "Open the app's updater to check for an update",
'completion': 'Print a script that enables Tab completion for your shell',
}
GROUPS = {
'voices': 'Your saved voices: create, change, share',
'voices reference': "A voice's reference recording",
'voices image': "A voice's picture",
'voices consent': 'Consent recorded for cloned voices',
'gallery': 'Voice gallery, presets and community voices',
'gallery presets': 'Ready-made voice presets',
'gallery community': 'Voices shared by the community',
'dictation': 'Speech-to-text dictation',
'dictation preferences': 'How dictation behaves',
'audiobook': 'Audiobooks and stories: plan, render, resume, download',
'dub': 'Dub videos into other languages',
'dub subtitles': 'Subtitles of a dubbing job',
'dub transcript': 'Transcript of a dubbing job',
'batch': 'Dub many videos in a queue',
'jobs': 'Background jobs',
'history': 'Generated clips',
'projects': 'Projects and their glossaries',
'projects glossary': 'Terms a project always translates the same way',
'audio': 'Audio tools: clean, normalize, convert, watermark',
'audio watermark': 'Audio watermarks',
'pronunciation': 'Pronunciation rules',
'engines': 'Speech, transcription and translation engines',
'engines quants': 'Size and quality variants of the GGUF engine',
'models': 'Download models and manage their licenses and memory',
'models license': 'Model license terms',
'settings': 'App settings',
'settings providers': 'AI text providers',
'settings skills': 'AI text skills',
'settings hf-token': 'Hugging Face token',
'settings storage': 'Disk space',
'sharing': 'Let other devices use this VoiceStudio',
'sharing tailscale': 'Sharing over Tailscale',
'integrations': 'Connect other apps and AI agents',
'integrations api': 'HTTP API',
'integrations mcp': 'AI agents (MCP)',
'integrations mcp bindings': 'Voices chosen for AI agents',
'calls': 'Phone calls',
'diagnostics': 'Troubleshooting information',
'connection': 'Which VoiceStudio backend commands use',
'connection auth': 'API key for the selected backend',
}
# Renamed commands: internal ID (kept for contracts and policies) -> public path.
# The former path keeps working, hidden from help, so existing scripts do not break.
RENAMED = {
'voices inspect': 'voices show-file',
'voices reference get': 'voices reference download',
'dub transcript get': 'dub transcript show',
'dub history-delete': 'dub history delete',
'settings hf-token status': 'settings hf-token show',
'models install-status': 'models progress',
'models install-cancel': 'models cancel',
'engines install-status': 'engines progress',
'gallery save-voice': 'gallery use',
'audiobook jobs': 'audiobook resumable',
'jobs longform list': 'audiobook finished',
'jobs longform delete': 'audiobook delete',
'stories render': 'audiobook render-story',
'stories encode': 'audio encode',
}
# Kept only for compatibility: duplicates or folded into another command.
HIDDEN = {'stories resume', 'update info', 'update check'}
GLOBAL_FLAGS = ('url', 'json', 'verbose', 'timeout', 'output', 'overwrite', 'yes')
# Commands that never contact a backend; backend options would do nothing.
OFFLINE = {'version', 'help', 'stop', 'completion', 'update', 'update info', 'update check',
'connection set', 'connection auth clear'}
SETTING_HELP = {
'compute-device': 'Processor used to run models (CPU or a GPU)',
'performance-profile': 'Preference for speed or quality',
'history-retention': 'How many generated clips are kept',
'hf-mirror': 'Mirror used for Hugging Face downloads',
'analytics': 'Whether anonymous usage analytics are shared',
'pause-fill': 'What fills pauses: silence or room_tone',
}
SETTINGS = {
'compute-device': ('compute-device', 'value'),
'performance-profile': ('performance-profile', 'tier'),
'history-retention': ('history-retention', 'cap'),
'hf-mirror': ('hf-mirror', 'url'),
'analytics': ('analytics', 'enabled'),
'pause-fill': ('pause-fill', 'mode'),
}
DUB_EXPORTS = {'video': 'download', 'audio': 'download-audio', 'mp3': 'download-mp3',
'srt': 'srt', 'vtt': 'vtt', 'ass': 'ass', 'stems': 'export-stems', 'segments': 'export-segments'}
def value(raw):
try:
return json.loads(raw, parse_constant=reject_constant)
except ValueError:
return raw
def reject_constant(name):
raise ValueError(f'Non-finite JSON value: {name}')
def assignments(items):
result = {}
for item in items:
key, sep, text = item.partition('=')
if not sep or not re.fullmatch(r'[A-Za-z_][\w\[\]-]*', key):
raise CLIError('usage_error', 'Expected NAME=VALUE', exit_code=2)
if key in result:
raise CLIError('usage_error', f'Duplicate field: {key}', exit_code=2)
result[key] = value(text)
return result
def read_text(path):
return sys.stdin.read() if path == '-' else Path(path).expanduser().read_text(encoding='utf-8')
def document(path):
try:
result = json.loads(read_text(path), parse_constant=reject_constant)
except ValueError:
raise CLIError('usage_error', 'Request file contains invalid JSON', exit_code=2) from None
if not isinstance(result, dict):
raise CLIError('usage_error', 'Request file must contain a JSON object', exit_code=2)
return result
def confirm(args, description):
if getattr(args, 'yes', False):
return
if not sys.stdin.isatty():
raise CLIError('confirmation_required', description + '. Rerun with --yes to confirm.')
print(description + ' [y/N] ', end='', file=sys.stderr, flush=True)
if sys.stdin.readline().strip().lower() not in {'y', 'yes'}:
raise CLIError('cancelled', 'Cancelled; nothing was changed.')
def stream_events(response, *, quiet=False):
"""Decode SSE or NDJSON, refusing error events even after a successful HTTP status."""
ct = response.headers.get('Content-Type', '')
sse = 'event-stream' in ct
last = None
data = []
event_type = ''
buffered = 0
def decode(text, kind=''):
try:
event = json.loads(text)
except ValueError:
raise CLIError('invalid_response', 'Backend returned a malformed stream event') from None
if not isinstance(event, dict):
raise CLIError('invalid_response', 'Expected a stream event object')
if kind == 'error' or event.get('type') == 'error' or event.get('error'):
raise CLIError('backend_error', str(event.get('detail') or event.get('message') or event.get('error') or 'Streaming operation failed'))
# Never print inline audio chunks into a terminal or JSON metadata stream.
summary = {k: v for k, v in event.items() if k not in {'pcm', 'audio', 'wav_base64'}}
if not quiet:
print(scrub(json.dumps(summary, ensure_ascii=False)), file=sys.stderr)
return event
while True:
line = response.readline(1024 * 1024 + 1)
if not line:
break
if len(line) > 1024 * 1024:
raise CLIError('invalid_response', 'Stream event exceeded 1 MiB')
text = line.decode('utf-8').rstrip('\r\n')
if not sse:
if text.strip():
last = decode(text)
elif not text:
if data:
last = decode('\n'.join(data), event_type)
data, event_type, buffered = [], '', 0
elif text.startswith('data:'):
buffered += len(line)
if buffered > 1024 * 1024:
raise CLIError('invalid_response', 'Stream event exceeded 1 MiB')
data.append(text[5:].lstrip(' '))
elif text.startswith('event:'):
event_type = text[6:].strip()
if data:
last = decode('\n'.join(data), event_type)
if last is None:
raise CLIError('incomplete_response', 'Backend stream ended without any events')
return last
def response_result(client, method, path, args, *, binary=False, stream=False, **kwargs):
output = getattr(args, 'output', None)
with client.open(method, path, **kwargs) as response:
ct = response.headers.get('Content-Type', '')
if 'event-stream' in ct or 'ndjson' in ct:
result = stream_events(response, quiet=getattr(args, 'json', False))
if result.get('type') not in {'done', 'complete', 'completed', 'result'} and stream and method == 'POST':
raise CLIError('incomplete_response', 'Backend stream ended without a completion event')
if output:
audio = result.get('audio_url') or result.get('url')
if not audio and (result.get('audio_path') or result.get('output')):
audio = '/audio/' + quote(str(result.get('audio_path') or result['output']), safe='/')
if not audio:
raise CLIError('invalid_response', 'Completed render has no downloadable result URL')
return response_result(client, 'GET', audio, args, binary=True)
return result
if 'json' in ct:
raw = response.read(16 * 1024 * 1024 + 1)
if len(raw) > 16 * 1024 * 1024:
raise CLIError('invalid_response', 'JSON response exceeded 16 MiB')
try:
result = json.loads(raw) if raw else {'ok': True}
except ValueError:
raise CLIError('invalid_response', 'Backend returned invalid JSON') from None
if binary:
if isinstance(result, dict) and result.get('audio_url') and output:
return response_result(client, 'GET', result['audio_url'], args, binary=True)
raise CLIError('invalid_response', 'Expected audio/file bytes but backend returned JSON')
if output and isinstance(result, dict) and result.get('output') and stream:
return response_result(client, 'GET', '/audio/' + quote(str(result['output']), safe='/'), args, binary=True)
if output:
return write_json(result, args)
return result
if response.status == 204:
return {'ok': True}
if binary and not output:
raise CLIError('usage_error', 'This command needs --output <file> (or - for stdout)', exit_code=2)
if output:
args.output_written = True
return download(response, output, overwrite=getattr(args, 'overwrite', False))
raw = response.read(16 * 1024 * 1024 + 1)
if len(raw) > 16 * 1024 * 1024:
raise CLIError('invalid_response', 'Response too large; use --output')
if 'text/' not in ct:
raise CLIError('invalid_response', 'Expected JSON/text response; use --output for files')
try:
return raw.decode('utf-8')
except UnicodeError:
raise CLIError('invalid_response', 'Backend returned invalid UTF-8 text') from None
def write_json(result, args):
raw = (json.dumps(result, ensure_ascii=False, indent=2) + '\n').encode()
response = io.BytesIO(raw)
response.headers = {'Content-Length': str(len(raw))}
args.output_written = True
return download(response, args.output, overwrite=getattr(args, 'overwrite', False))
def resolve_voice(client, selected):
profiles = client.json('GET', '/profiles')
if not isinstance(profiles, list):
raise CLIError('invalid_response', 'Expected a voice profile list')
for profile in profiles:
if profile.get('id') == selected:
return selected
matches = [p['id'] for p in profiles if p.get('name', '').casefold() == selected.casefold()]
if len(matches) > 1:
raise CLIError('ambiguous_voice', 'More than one voice has that name; use a profile ID')
if not matches:
raise CLIError('voice_not_found', 'Voice was not found; run voicestudio voices list')
return matches[0]
def dispatch(args):
name = args.handler
if name == 'completion':
from .completion import script
return script(args.shell)
if name == 'version':
if getattr(args, 'verbose', False):
return updates.install_info(installed_application())
return {'version': app_version()} if getattr(args, 'json', False) else 'VoiceStudio ' + app_version()
if name == 'connection set':
from .config import normalize_url
config = load_config(); config['url'] = normalize_url(args.backend_url); save_config(config)
return {'url': config['url']}
if name == 'connection auth clear':
config = load_config(); config.pop('api_key', None); config.pop('credential_url', None); save_config(config)
return {'cleared': True}
if name.startswith('update'):
app = installed_application()
info = updates.install_info(app)
if name == 'update info':
return info
# The app's updater is the only update check; the CLI makes no network requests.
return updates.open_app_updater(info)
url, key, source = connection(getattr(args, 'url', None))
quiet = getattr(args, 'json', False)
if name == 'stop':
if source != 'default':
raise CLIError('usage_error', 'stop manages this machine\'s VoiceStudio app; it never stops a backend '
'selected with --url, VOICESTUDIO_URL or a saved connection.', exit_code=2)
from .runtime import stop_backend
return stop_backend(url)
if name == 'connection show':
return {'url': url, 'source': source, 'authenticated': bool(key)}
if name == 'connection auth set':
secret = sys.stdin.read().strip()
if not secret or any(c in secret for c in '\r\n'):
raise CLIError('usage_error', 'Expected one nonempty credential on stdin', exit_code=2)
args.redaction_secrets.append(secret)
from .config import normalize_url
Client(url, secret) # Validate transport before saving anything.
config = load_config(); config.update(api_key=secret, credential_url=normalize_url(url)); save_config(config)
return {'saved': True, 'url': url}
test_url = getattr(args, 'backend_url', None)
if test_url and test_url.rstrip('/') != url:
key = '' # A one-off probe must not forward another endpoint's credential.
client = Client(test_url or url, key, getattr(args, 'timeout', 600))
if name in {'status', 'connection test'}:
if source == 'default' and not test_url:
from .runtime import LocalClient
client = LocalClient(url, key, getattr(args, 'timeout', 600), name, quiet=quiet)
try:
health = client.health()
except CLIError as exc:
if name != 'status' or exc.code != 'backend_stopped':
raise
# "Not running" is an answer, not a failure; exit 3 as `systemctl status` does.
args.exit_code = 3
return {'running': False, 'message': 'VoiceStudio is not running.'}
version = health.get('version', '')
return {'running': True, 'url': client.url, **health,
'message': f'VoiceStudio {version} is running at {client.url}.'.replace(' ', ' ')}
if name == 'integrations api docs':
return client.url + '/docs'
if name == 'integrations mcp config':
headers = {'X-OmniVoice-Client-Id': args.client}
if args.client == 'codex':
return ('[mcp_servers.voicestudio]\nurl = ' + json.dumps(client.url + '/mcp/') +
'\nhttp_headers = { "X-OmniVoice-Client-Id" = "codex" }')
entry = {'url': client.url + '/mcp/', 'headers': headers}
return {'mcpServers': {'voicestudio': entry}}
if source == 'default':
from .runtime import LocalClient
client = LocalClient(url, key, getattr(args, 'timeout', 600), name, quiet=quiet)
if name == 'integrations mcp bindings set':
return client.json('PUT', '/api/mcp/bindings', payload={'client_id': args.client,
'label': args.client, 'profile_id': resolve_voice(client, args.voice)})
if name == 'models list':
result = client.json('GET', '/models')
if args.installed:
result['models'] = [m for m in result['models'] if m['installed']]
return result
if name in {'engines list', 'engines select', 'engines install', 'engines install-status'}:
if name == 'engines list':
return client.json('GET', '/engines' + ('/' + args.type if args.type else ''))
if name == 'engines select':
if args.type in {'translation', 'diarisation'}:
if args.model:
raise CLIError('usage_error', '--model is not supported by this engine family', exit_code=2)
return client.json('POST', f'/engines/{args.type}/select', payload={'engine_id': args.id})
payload = {'family': args.type, 'backend_id': args.id}
if args.model:
payload['model_id'] = args.model
return client.json('POST', '/engines/select', payload=payload)
if args.type == 'translation':
route = f'/engines/translation/{quote(args.id, safe="")}/install'
if name.endswith('status'):
return client.json('GET', '/engines/translation')
else:
route = f'/engines/sidecar/{quote(args.id, safe="")}/install'
return client.json('GET' if name.endswith('status') else 'POST', route + ('/status' if name.endswith('status') else ''))
if name in {'models install', 'models license accept', 'models install-cancel'}:
return model_operation(client, args)
if name == 'voices describe':
return client.json('POST', '/design/describe', payload={'description': args.description})
if name == 'voices consent show':
profile = client.json('GET', '/profiles/' + quote(args.id, safe=''))
return {k: v for k, v in profile.items() if 'consent' in k or 'attest' in k or k == 'id'}
if name in {'voices clone', 'voices design'}:
form = {'name': args.name, 'language': args.language}
if not args.name.strip():
raise CLIError('usage_error', 'Voice name must not be empty', exit_code=2)
if args.engine:
form['engine'] = args.engine
files = {}
if name.endswith('clone'):
form.update(kind='clone', ref_text=args.ref_text); files['ref_audio'] = args.audio
else:
design = client.json('POST', '/design/describe', payload={'description': args.description})
if not design.get('matched'):
raise CLIError('validation_error', 'No supported voice attributes matched the description')
form.update(kind='design', vd_states=json.dumps(design['attrs']), instruct=design['instruct'])
return client.json('POST', '/profiles', form=form, files=files)
if name in {'speak', 'voices compare'}:
return speak(client, args)
if name in {'transcribe', 'translate-audio'}:
form = {'model': args.model, 'response_format': args.format}
if args.language:
form['language'] = args.language
route = '/v1/audio/' + ('transcriptions' if name == 'transcribe' else 'translations')
with input_file(args.input, args.stdin_filename) as input_path:
return response_result(client, 'POST', route, args, form=form, files={'file': input_path})
if name == 'projects rename':
return client.json('PATCH', '/projects/' + quote(args.id, safe=''), payload={'name': args.name})
if name in {'history star', 'history unstar'}:
return client.json('PUT', '/history/' + quote(args.id, safe='') + '/starred', payload={'starred': name.endswith(' star')})
if name == 'settings get' and not args.key:
result = {}
for setting, (route, field) in SETTINGS.items():
try:
state = client.json('GET', '/api/settings/' + route)
except CLIError as exc:
if exc.status != 404:
raise
continue # an older backend without this setting
result[setting] = state.get(field, state) if isinstance(state, dict) else state
return result
if name in {'settings get', 'settings set'}:
route, field = SETTINGS[args.key]
return client.json('GET' if name.endswith('get') else 'PUT', '/api/settings/' + route,
**({} if name.endswith('get') else {'payload': {field: value(args.value)}}))
if name == 'settings hf-token set':
token = sys.stdin.read().strip()
if not token:
raise CLIError('usage_error', 'Expected a token on stdin', exit_code=2)
args.redaction_secrets.append(token)
return client.json('POST', '/api/settings/hf-token', payload={'token': token})
if name == 'dub export':
if not getattr(args, 'output', None):
raise CLIError('usage_error', 'Export needs --output', exit_code=2)
return response_result(client, 'GET', '/dub/' + DUB_EXPORTS[args.format] + '/' + quote(args.id, safe=''), args,
binary=True, query={'lang': args.language} if args.language else None)
return generic(client, args)
@contextmanager
def input_file(path, filename='audio.wav'):
if path != '-':
yield Path(path).expanduser()
return
suffix = Path(filename).suffix
with tempfile.TemporaryDirectory(prefix='voicestudio-stdin-') as directory:
temp = Path(directory) / ('stdin' + suffix)
with temp.open('wb') as output:
while chunk := sys.stdin.buffer.read(64 * 1024):
output.write(chunk)
yield temp
def speak(client, args):
if args.handler == 'voices compare':
directory = Path(args.out_dir); directory.mkdir(parents=True, exist_ok=True)
results = []
from copy import copy
for index, voice in enumerate(args.ids):
child = copy(args); child.handler = 'speak'; child.voice = voice
child.output = str(directory / f'voice-{index + 1}.wav'); child.text_file = None
results.append(speak(client, child))
return results
if bool(args.text is not None) == bool(args.text_file):
raise CLIError('usage_error', 'Supply text or --text-file, but not both', exit_code=2)
text = read_text(args.text_file) if args.text_file else args.text
if not text.strip():
raise CLIError('usage_error', 'Text must not be empty', exit_code=2)
if not getattr(args, 'output', None):
raise CLIError('usage_error', 'Speech generation needs --output', exit_code=2)
form = {'text': text, 'profile_id': resolve_voice(client, args.voice), 'speed': args.speed}
for key in ['engine', 'language', 'seed', 'instruct']:
if getattr(args, key, None) is not None:
form[key] = getattr(args, key)
return response_result(client, 'POST', '/generate', args, form=form, binary=True)
def model_operation(client, args):
if args.handler == 'models install-cancel':
return client.json('POST', '/models/install/cancel', payload={'repo_id': args.id})
model = next((m for m in client.json('GET', '/models')['models'] if m['repo_id'] == args.id), None)
if model is None:
raise CLIError('model_not_found', 'Unknown catalogue model; run voicestudio models list')
if args.handler == 'models install' and model.get('installed'):
return {'message': 'Model is already installed', 'id': args.id}
if not model.get('supported', True):
raise CLIError('unsupported_model', 'This model is unsupported on the backend host')
terms = client.json('GET', '/models/licenses/acceptance/' + quote(args.id, safe=''))
acceptance = terms.get('acceptance', terms)
if acceptance.get('required') and not acceptance.get('accepted'):
details = client.json('GET', '/models/licenses/details/' + quote(args.id, safe=''))
if not getattr(args, 'json', False):
print(scrub(json.dumps(details, ensure_ascii=False, indent=2)), file=sys.stderr)
if not args.accept_license:
raise CLIError('license_required', 'Review the model terms, then rerun with --accept-license to accept them explicitly.', details=details)
client.json('POST', '/models/licenses/accept', payload={'repo_id': args.id,
'fingerprint': acceptance['fingerprint'], 'accepted': True})
if args.handler == 'models license accept':
return {'id': args.id, 'accepted': True}
return client.json('POST', '/models/install', payload={'repo_id': args.id, 'target': 'local'})
def generic(client, args):
spec = args.spec
if spec.binary and not getattr(args, 'output', None):
raise CLIError('usage_error', 'This command needs --output', exit_code=2)
contracts = json.loads(Path(__file__).with_name('contracts.json').read_text())
contract = contracts.get(spec.name, {})
if args.file == '-' and spec.upload and args.input == '-':
raise CLIError('usage_error', 'JSON fields and upload cannot both read stdin', exit_code=2)
fields = document(args.file) if args.file else {}
fields.update(assignments(args.field))
remember_secrets(fields, args.redaction_secrets)
query = assignments(args.query)
for key in list(fields):
if key in contract.get('query', []):
query[key] = fields.pop(key)
declared = contract.get('fields', [])
unknown = set(fields) - set(declared)
if declared and unknown:
raise CLIError('usage_error', 'Unknown request fields: ' + ', '.join(sorted(unknown)), exit_code=2)
for required in contract.get('required_query', []):
if required not in query:
raise CLIError('usage_error', f'Missing query parameter {required}; use --query {required}=VALUE', exit_code=2)
files = {spec.upload: args.input} if spec.upload and spec.upload != '@raw' else {}
for required in contract.get('required', []):
if required not in fields and required not in files:
raise CLIError('usage_error', f'Missing request field {required}; use --file or --field {required}=VALUE', exit_code=2)
route = spec.route.format(**{param: quote(getattr(args, param), safe='') for param in spec.params})
if spec.destructive:
confirm(args, f'Confirm {spec.name}')
encoding = contract.get('encoding', '')
kwargs = {'query': query}
if spec.upload == '@raw':
kwargs['raw_file'] = args.input
elif files or encoding in {'multipart/form-data', 'application/x-www-form-urlencoded'}:
kwargs.update(form=fields, files=files)
elif fields or encoding == 'application/json':
kwargs['payload'] = fields
if spec.upload:
with input_file(args.input, args.stdin_filename) as uploaded:
if spec.upload == '@raw':
kwargs['raw_file'] = uploaded
else:
kwargs['files'] = {spec.upload: uploaded}
return response_result(client, spec.method, route, args, binary=spec.binary, stream=spec.stream, **kwargs)
return response_result(client, spec.method, route, args, binary=spec.binary, stream=spec.stream, **kwargs)
def emit(result, args):
if getattr(args, 'output', None) and not getattr(args, 'output_written', False):
result = write_json(result, args)
if getattr(args, 'output', None) == '-':
return
text = json.dumps(result, ensure_ascii=False, indent=2) if getattr(args, 'json', False) else render(result)
key = os.environ.get('OMNIVOICE_API_KEY', '')
text = scrub(text, [key, *getattr(args, 'redaction_secrets', [])])
if not text:
return
sys.stdout.write(text)
if not text.endswith('\n'):
sys.stdout.write('\n')
def remember_secrets(value, secrets):
if isinstance(value, dict):
for key, child in value.items():
if str(key).lower() in {'api_key', 'token', 'password', 'access_token', 'refresh_token', 'pin'} and isinstance(child, str):
secrets.append(child)
else:
remember_secrets(child, secrets)
elif isinstance(value, list):
for child in value:
remember_secrets(child, secrets)
def main(argv=None):
# Piped text has the same encoding on Windows, macOS and Linux.
for stream in [sys.stdin, sys.stdout, sys.stderr]:
if hasattr(stream, 'reconfigure'):
try:
stream.reconfigure(encoding='utf-8')
except (OSError, ValueError):
pass # Embedders may already have read from a text stream.
argv = list(sys.argv[1:] if argv is None else argv)
if argv[:1] == ['__complete']:
# Called by the shell on every Tab; must stay fast and never fail loudly.
from .completion import complete
try:
for line in complete(argv[1:]):
print(line)
except Exception:
pass
return 0
json_errors = '--json' in argv
secrets = [os.environ.get('OMNIVOICE_API_KEY', '')]
try:
argv, desktop_arguments = split_arguments(argv)
if not argv:
return launch_desktop(desktop_arguments)
root, nodes = build_parser()
args = root.parse_args(argv)
if not hasattr(args, 'handler'):
args.current_parser.print_help()
return 0
if args.handler == 'help':
target = nodes.get(tuple(args.path))
if target is None:
raise CLIError('usage_error', 'Unknown help command path; run voicestudio --help.', exit_code=2)
target.print_help()
return 0
if hasattr(args, 'output') and args.output != '-':
target = Path(args.output).expanduser()
if target.exists() and not getattr(args, 'overwrite', False):
raise CLIError('output_exists', 'Output exists; use --overwrite to replace it.')
if not target.parent.is_dir():
raise CLIError('file_error', 'Output directory does not exist.')
if args.handler != 'version' and not args.handler.startswith('update'):
secrets.append(load_config().get('api_key', ''))
args.redaction_secrets = secrets
result = dispatch(args)
emit(result, args)
return getattr(args, 'exit_code', 0)
except CLIError as exc:
message = scrub(str(exc), secrets)
if json_errors:
detail = {'code': exc.code, 'message': message}
if exc.status is not None:
detail['status'] = exc.status
if exc.retry_after:
detail['retry_after'] = exc.retry_after
if exc.details is not None:
detail['details'] = exc.details
print(scrub(json.dumps({'error': detail}, ensure_ascii=False), secrets), file=sys.stderr)
else:
print(f'voicestudio: {message}', file=sys.stderr)
if exc.details is not None and '--verbose' in argv:
print(f'voicestudio: details: {scrub(str(exc.details), secrets)}', file=sys.stderr)
return exc.exit_code
except KeyboardInterrupt:
print(json.dumps({'error': {'code': 'cancelled', 'message': 'Cancelled.'}}) if json_errors else
'voicestudio: Cancelled.', file=sys.stderr)
return 130
except BrokenPipeError:
# Prevent a second failure when Python flushes stdout during shutdown.
try:
sink = os.open(os.devnull, os.O_WRONLY)
try:
os.dup2(sink, sys.stdout.fileno())
finally:
os.close(sink)
except (OSError, io.UnsupportedOperation):
pass
return 1
except (OSError, UnicodeError) as exc:
code, message = 'file_error', scrub(str(exc), secrets)
except Exception as exc:
code = 'internal_error'
message = 'Unexpected CLI error. Rerun with --verbose for diagnostic details.'
if '--verbose' in argv:
message += ' ' + type(exc).__name__ + ': ' + scrub(str(exc), secrets)
if json_errors:
print(json.dumps({'error': {'code': code, 'message': message}}), file=sys.stderr)
else:
print('voicestudio: ' + message, file=sys.stderr)
return 1
if __name__ == '__main__':
raise SystemExit(main())
+254
View File
@@ -0,0 +1,254 @@
"""Read installed application metadata without starting Electron or the backend."""
from dataclasses import dataclass, asdict
import hashlib
import json
import os
from pathlib import Path
import platform
import plistlib
import re
import shlex
import shutil
import struct
import subprocess
import sys
import tempfile
from . import desktop
from .config import cache_dir
from .errors import CLIError
VERSION = re.compile(r'^\d+\.\d+\.\d+(?:-beta\.\d+)?$')
@dataclass(frozen=True)
class Application:
version: str
executable: Path
method: str
platform: str
arch: str
distribution: str = 'direct'
def info(self):
return asdict(self) | {'executable': str(self.executable)}
def native_arch(path=None):
if path and path.is_file():
with path.open('rb') as stream:
data = stream.read(64)
if data.startswith(b'\x7fELF') and len(data) >= 20:
machine = int.from_bytes(data[18:20], 'little' if data[5] == 1 else 'big')
return {62: 'x64', 183: 'arm64'}.get(machine, platform.machine())
if data.startswith(b'MZ') and len(data) >= 64:
stream.seek(int.from_bytes(data[60:64], 'little') + 4)
return {0x8664: 'x64', 0xaa64: 'arm64'}.get(int.from_bytes(stream.read(2), 'little'), 'x64')
return {'amd64': 'x64', 'x86_64': 'x64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(
platform.machine().lower(), platform.machine().lower())
def asar_package(path):
# ASAR stores a JSON directory in a Pickle header; entry offsets start after it.
with path.open('rb') as stream:
size_pickle = stream.read(8)
if len(size_pickle) != 8 or struct.unpack('<I', size_pickle[:4])[0] != 4:
raise ValueError('invalid ASAR header')
size = struct.unpack('<I', size_pickle[4:])[0]
if not 8 <= size <= 64 * 1024 * 1024:
raise ValueError('invalid ASAR header size')
header = stream.read(size)
if len(header) != size:
raise ValueError('truncated ASAR header')
length = struct.unpack('<I', header[4:8])[0]
if length > size - 8:
raise ValueError('invalid ASAR JSON length')
entry = json.loads(header[8:8 + length])['files']['package.json']
offset, length = int(entry['offset']), int(entry['size'])
if entry.get('unpacked') or offset < 0 or not 0 < length <= 2 * 1024 * 1024:
raise ValueError('invalid package metadata entry')
if 8 + size + offset + length > os.fstat(stream.fileno()).st_size:
raise ValueError('package metadata exceeds archive')
stream.seek(8 + size + offset)
return json.loads(stream.read(length))
def package_metadata(directory):
archive = directory / 'app.asar'
if archive.is_file():
return asar_package(archive)
return json.loads((directory / 'app/package.json').read_text(encoding='utf-8'))
def image_fingerprint(path):
stat = path.stat()
return {'path': str(path), 'device': stat.st_dev, 'inode': stat.st_ino,
'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns, 'ctime_ns': stat.st_ctime_ns}
def appimage_metadata(path):
fingerprint = image_fingerprint(path)
key = hashlib.sha256(os.fsencode(str(path))).hexdigest()
cached = cache_dir() / f'appimage-{key}.json'
try:
with cached.open('rb') as stream:
record = json.loads(stream.read(64 * 1024))
metadata = record['metadata']
if (record.get('schema') == 1 and record.get('fingerprint') == fingerprint and
isinstance(metadata, dict) and isinstance(metadata.get('version'), str) and
VERSION.fullmatch(metadata['version'])):
return metadata
except (OSError, ValueError, KeyError, TypeError, AttributeError):
pass
with tempfile.TemporaryDirectory(prefix='voicestudio-metadata-') as work:
result = subprocess.run([str(path), '--appimage-extract', 'resources/app.asar'],
cwd=work, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
if result.returncode:
raise ValueError('AppImage metadata extraction failed')
metadata = package_metadata(Path(work) / 'squashfs-root/resources')
if not isinstance(metadata, dict) or not isinstance(metadata.get('version'), str) or not VERSION.fullmatch(metadata['version']):
raise ValueError('invalid application version')
if fingerprint != image_fingerprint(path):
raise ValueError('AppImage changed while reading its metadata; retry the command')
temporary = None
try:
cached.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.appimage-', dir=cached.parent)
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
json.dump({'schema': 1, 'fingerprint': fingerprint,
'metadata': {'version': metadata['version'],
'voicestudioDistribution': metadata.get('voicestudioDistribution', 'direct')}}, stream)
os.replace(temporary, cached)
except OSError:
pass # Cache availability must not affect offline application inspection.
finally:
if temporary:
try:
Path(temporary).unlink(missing_ok=True)
except OSError:
pass
return metadata
def unwrap_launcher(path):
"""Inspect literal exec targets; never evaluate a shell launcher as code."""
seen = set()
for _ in range(8):
path = path.resolve()
if path in seen:
raise ValueError('recursive desktop launcher')
seen.add(path)
if path.is_dir():
return path
with path.open('rb') as stream:
header = stream.read(65536)
if not header.startswith(b'#!'):
return path
targets = []
for line in header.decode('utf-8').splitlines():
if not line.strip().startswith('exec '):
continue
words = shlex.split(line.strip(), comments=True)[1:]
if not words:
continue
if Path(words[0]).name == 'env':
words = words[1:]
while words and '=' in words[0] and not words[0].startswith('/'):
words.pop(0)
if words and Path(words[0]).name == 'open' and '-a' in words:
targets.append(words[words.index('-a') + 1])
elif words:
targets.append(words[0])
if len(targets) != 1 or any(c in targets[0] for c in ['$(', '`', '\n']):
raise ValueError('launcher does not have one literal desktop executable')
target = os.path.expandvars(os.path.expanduser(targets[0]))
if '$' in target:
raise ValueError('unresolved launcher variable')
if not Path(target).is_absolute():
target = shutil.which(target) or ''
if not target:
raise ValueError('launcher executable was not found')
path = Path(target)
raise ValueError('too many launcher indirections')
def inspect_application(path):
path = unwrap_launcher(path)
arch = native_arch(path)
if path.suffix.lower() == '.app':
with (path / 'Contents/Info.plist').open('rb') as stream:
info = plistlib.load(stream)
metadata = package_metadata(path / 'Contents/Resources')
metadata['version'] = info['CFBundleShortVersionString']
method = 'dmg'
elif path.suffix.lower() == '.appimage':
with path.open('rb') as stream:
header = stream.read(11)
if not header.startswith(b'\x7fELF') or header[8:11] != b'AI\x02':
raise ValueError('not a type-2 AppImage')
metadata = appimage_metadata(path)
method = 'appimage'
else:
# A macOS executable can be selected directly instead of its .app bundle.
if path.parent.name == 'MacOS' and path.parent.parent.name == 'Contents':
return inspect_application(path.parent.parent.parent)
metadata = package_metadata(path.parent / 'resources')
method = 'nsis' if sys.platform == 'win32' else 'directory'
if sys.platform == 'linux' and (path.parent == Path('/opt/VoiceStudio') or
path.parent == Path('/opt/voicestudio-electron')):
method = 'deb'
version = metadata['version']
if not isinstance(version, str) or not VERSION.fullmatch(version):
raise ValueError('invalid application version')
distribution = metadata.get('voicestudioDistribution', 'direct')
if distribution in {'snap-store', 'mac-app-store'}:
method = 'store'
return Application(version, path, method, sys.platform, arch, distribution)
def installed_application():
try:
manifest = desktop.bundled_launcher()
if manifest:
record = json.loads(manifest.read_text(encoding='utf-8'))
version = record.get('version')
if not isinstance(version, str) or not VERSION.fullmatch(version):
raise ValueError('bundled application version is missing or invalid')
if record.get('method') not in {'appimage', 'dmg', 'nsis', 'deb', 'directory', 'store'}:
raise ValueError('invalid application installation format')
if record.get('arch') not in {'x64', 'arm64'}:
raise ValueError('invalid application architecture')
executable = Path(record['application']).expanduser()
if not executable.is_absolute():
executable = manifest.parent / executable
method = record['method']
if sys.platform == 'linux' and os.environ.get('APPIMAGE'):
executable, method = Path(os.environ['APPIMAGE']), 'appimage'
elif sys.platform == 'linux' and str(executable.resolve()).startswith('/opt/'):
method = 'deb'
if record.get('distribution') in {'snap-store', 'mac-app-store'}:
method = 'store'
return Application(version, executable.resolve(), method, sys.platform,
record['arch'], record.get('distribution', 'direct'))
command = desktop.resolve_desktop()
target = command[2] if command[0] == '/usr/bin/open' else command[0]
return inspect_application(Path(target))
except CLIError as exc:
# A checkout is itself an application installation, but never overrides an
# explicitly selected or registered desktop installation.
if exc.code == 'desktop_not_found' and not os.environ.get('VOICESTUDIO_DESKTOP_APP') and not desktop.launcher_config().exists():
root = Path(__file__).resolve().parents[2]
canonical = root / 'package.json'
if canonical.is_file() and (root / 'electron').is_dir():
version = json.loads(canonical.read_text(encoding='utf-8'))['version']
if VERSION.fullmatch(version):
return Application(version, root, 'source', sys.platform, native_arch())
raise
except (OSError, ValueError, KeyError, TypeError, struct.error, subprocess.TimeoutExpired) as exc:
# The technical reason stays available to scripts and --verbose, not the headline.
raise CLIError('app_metadata_error', "Can't find the VoiceStudio app. Install VoiceStudio, or set "
'VOICESTUDIO_DESKTOP_APP to where the app is installed.', details=str(exc)) from None
def app_version():
return installed_application().version
+146
View File
@@ -0,0 +1,146 @@
"""Tab completion for bash, zsh, fish and PowerShell.
Each shell script calls ``voicestudio __complete <words…>`` on every Tab; the
last word is the one being completed (empty after a space). Command names come
from a lightweight index of command paths, so completing them builds no
parsers at all. Options and fixed choices build the parser of the one command
being typed. Nothing here contacts a backend or starts the app.
"""
# Global options that take a value: their value is not a command word.
VALUE_OPTIONS = {'--url', '--timeout', '-o', '--output'}
def _index():
"""Visible command paths -> description, from data only (no argparse)."""
from .__main__ import CUSTOM, DESCRIPTIONS, GROUPS, HIDDEN, RENAMED
from .registry import COMMANDS
commands = {}
for spec in COMMANDS:
if spec.name not in CUSTOM and spec.name not in HIDDEN:
commands[RENAMED.get(spec.name, spec.name)] = spec.description
for name in CUSTOM - HIDDEN:
commands[RENAMED.get(name, name)] = DESCRIPTIONS.get(name, '')
groups = {}
for path in commands:
words = path.split()
for n in range(1, len(words)):
group = ' '.join(words[:n])
groups.setdefault(group, GROUPS.get(group, ''))
return commands, groups
def _children(prefix, commands, groups):
depth = len(prefix)
found = {}
for path, description in [*groups.items(), *commands.items()]:
words = path.split()
if len(words) == depth + 1 and words[:depth] == prefix:
found.setdefault(words[-1], description)
return found
def _parser(path):
from .__main__ import build_parser
root, nodes = build_parser(only=tuple(path))
return nodes.get(tuple(path)) or root
def _options(parser):
import argparse
found = {}
for action in parser._actions:
if action.help == argparse.SUPPRESS:
continue
for flag in action.option_strings:
if flag.startswith('--') or not any(o.startswith('--') for o in action.option_strings):
found[flag] = (action.help or '').split(';')[0]
return found
def complete(words):
"""Candidates as ``value<TAB>description`` lines for the word being typed."""
words = list(words) or ['']
current, before = words[-1], words[:-1]
commands, groups = _index()
path, skip, previous = [], False, None
for word in before:
if skip:
skip = False
previous = None
continue
if word.startswith('-'):
skip = word in VALUE_OPTIONS
previous = word
continue
if ' '.join([*path, word]) in commands or ' '.join([*path, word]) in groups:
path.append(word)
elif ' '.join(path) not in commands:
return [] # an unknown (or former, unlisted) name: nothing sensible to offer
previous = None
joined = ' '.join(path)
is_command = joined in commands
if skip and previous:
return [] # a value the user supplies (URL, file, number): let the shell offer files
if current.startswith('-'):
options = _options(_parser(path)) if is_command else {
'--help': 'Show help', '--json': 'Print machine-readable JSON', '--version': 'Show the installed version'}
return [f'{flag}\t{text}' for flag, text in sorted(options.items()) if flag.startswith(current)]
if not is_command or joined in groups:
children = _children(path, commands, groups)
if children:
return [f'{name}\t{text}' for name, text in sorted(children.items()) if name.startswith(current)]
if is_command:
parser = _parser(path)
for action in parser._actions:
if action.choices and not isinstance(action.choices, dict):
if previous in action.option_strings or (not action.option_strings and previous is None):
return [str(choice) for choice in action.choices if str(choice).startswith(current)]
return []
BASH = r'''# VoiceStudio Tab completion for bash: eval "$(voicestudio completion bash)"
_voicestudio() {
local IFS=$'\n'
COMPREPLY=($(voicestudio __complete "${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null | cut -f1))
}
complete -o default -F _voicestudio voicestudio
'''
ZSH = r'''# VoiceStudio Tab completion for zsh: eval "$(voicestudio completion zsh)"
_voicestudio() {
local -a items
local line
for line in "${(@f)$(voicestudio __complete "${(@)words[2,CURRENT]}" 2>/dev/null)}"; do
[[ -n $line ]] && items+=("${${line%%$'\t'*}//:/\\:}:${line#*$'\t'}")
done
if (( ${#items} )); then _describe 'voicestudio' items; else _files; fi
}
(( $+functions[compdef] )) || { autoload -Uz compinit && compinit; }
compdef _voicestudio voicestudio
'''
FISH = r'''# VoiceStudio Tab completion for fish: voicestudio completion fish | source
complete -c voicestudio -e
complete -c voicestudio -a '(voicestudio __complete (commandline -opc)[2..-1] (commandline -ct) 2>/dev/null)'
'''
POWERSHELL = r'''# VoiceStudio Tab completion for PowerShell: voicestudio completion powershell | Out-String | Invoke-Expression
Register-ArgumentCompleter -Native -CommandName voicestudio -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$words = @($commandAst.CommandElements | Select-Object -Skip 1 |
Where-Object { $_.Extent.EndOffset -le $cursorPosition } | ForEach-Object { $_.ToString() })
if ($wordToComplete -eq '') { $words += '' }
voicestudio __complete @words 2>$null | ForEach-Object {
$name, $description = $_ -split "`t", 2
if (-not $description) { $description = $name }
[System.Management.Automation.CompletionResult]::new($name, $name, 'ParameterValue', $description)
}
}
'''
SCRIPTS = {'bash': BASH, 'zsh': ZSH, 'fish': FISH, 'powershell': POWERSHELL}
def script(shell):
return SCRIPTS[shell]
+101
View File
@@ -0,0 +1,101 @@
"""Private CLI configuration, independent of Electron browser storage."""
import json
import os
from pathlib import Path
import tempfile
import sys
from urllib.parse import urlsplit
import ipaddress
from .errors import CLIError
def config_path() -> Path:
override = os.environ.get('VOICESTUDIO_CONFIG')
base = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config')))
return Path(override).expanduser() if override else base / 'voicestudio-cli' / 'config.json'
def cache_dir() -> Path:
if os.environ.get('VOICESTUDIO_CONFIG'):
return config_path().parent / 'cache'
if sys.platform == 'darwin':
return Path.home() / 'Library/Caches/voicestudio-cli'
if sys.platform == 'win32':
return Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData/Local')) / 'voicestudio-cli/Cache'
return Path(os.environ.get('XDG_CACHE_HOME', Path.home() / '.cache')) / 'voicestudio-cli'
def load_config() -> dict:
try:
value = json.loads(config_path().read_text(encoding='utf-8'))
except FileNotFoundError:
return {}
except (OSError, ValueError) as exc:
raise CLIError('config_error', f'Cannot read CLI configuration: {exc}') from exc
if not isinstance(value, dict):
raise CLIError('config_error', 'CLI configuration must be a JSON object')
for key in ['url', 'api_key', 'credential_url']:
if key in value and not isinstance(value[key], str):
raise CLIError('config_error', f'CLI configuration field {key} must be text')
return value
def save_config(value: dict) -> None:
path = config_path()
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(prefix='.config-', dir=path.parent)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
json.dump(value, stream, indent=2)
stream.write('\n')
os.replace(temp, path)
finally:
Path(temp).unlink(missing_ok=True)
def normalize_url(value: str) -> str:
try:
url = urlsplit(value)
port = url.port
except (ValueError, TypeError) as exc:
raise CLIError('usage_error', 'Invalid backend URL', exit_code=2) from exc
if (url.scheme not in {'http', 'https'} or not url.hostname or
url.username or url.password or url.query or url.fragment or
any(ord(c) < 33 for c in value)):
raise CLIError('usage_error', 'Use an http(s) backend URL without credentials, query or fragment', exit_code=2)
if port == 0:
raise CLIError('usage_error', 'Backend port must be between 1 and 65535', exit_code=2)
return value.rstrip('/')
def loopback(host: str | None) -> bool:
if host == 'localhost':
return True
try:
return ipaddress.ip_address(host or '').is_loopback
except ValueError:
return False
def connection(explicit: str | None) -> tuple[str, str, str]:
config = load_config()
candidates = [(explicit, 'flag'), (os.environ.get('VOICESTUDIO_URL'), 'environment'),
(config.get('url'), 'configuration')]
chosen = next(((value, source) for value, source in candidates if value), None)
if chosen:
raw, source = chosen
else:
raw_port = os.environ.get('OMNIVOICE_PORT', '3900')
if not raw_port.isascii() or not raw_port.isdecimal() or not 0 < int(raw_port) < 65536:
raise CLIError('config_error', 'OMNIVOICE_PORT must be an integer from 1 to 65535')
raw, source = f'http://127.0.0.1:{int(raw_port)}', 'default'
url = normalize_url(raw)
# Credentials saved for one endpoint must never follow a --url override elsewhere.
saved_key = config.get('api_key', '') if config.get('credential_url') == url else ''
key = os.environ.get('OMNIVOICE_API_KEY', saved_key).strip()
if any(c in key for c in '\r\n'):
raise CLIError('config_error', 'Invalid API credential')
if key and urlsplit(url).scheme != 'https' and not loopback(urlsplit(url).hostname):
raise CLIError('credential_transport', 'Remote credentials require HTTPS')
return url, key, source
File diff suppressed because it is too large. Load diff
+202
View File
@@ -0,0 +1,202 @@
"""Resolve and launch installed desktop distributions."""
import ctypes
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from .config import config_path
from .errors import CLIError
# Desktop-ownership switches understood by the Electron app (electron/src/main/headless.ts).
BACKGROUND_FLAG = '--voicestudio-background'
STOP_FLAG = '--voicestudio-stop'
CHECK_UPDATES_FLAG = '--voicestudio-check-updates'
# Snap injects --no-sandbox even for CLI invocations. Route launcher switches
# separately so they do not enter the HTTP command parser. The Linux package's
# public executable is this CLI, so the app's own relaunches pass through here.
DESKTOP_SWITCHES = {'--no-sandbox', '--disable-gpu', '--disable-gpu-compositing',
BACKGROUND_FLAG, STOP_FLAG, CHECK_UPDATES_FLAG}
DESKTOP_VALUES = {'--user-data-dir', '--ozone-platform', '--force-device-scale-factor'}
def split_arguments(argv):
desktop, commands = [], []
index = 0
while index < len(argv):
item = argv[index]
name = item.split('=', 1)[0]
if not commands and name in DESKTOP_SWITCHES:
desktop.append(item)
elif not commands and name in DESKTOP_VALUES:
desktop.append(item)
if '=' not in item:
index += 1
if index >= len(argv) or argv[index].startswith('-'):
raise CLIError('usage_error', f'{name} requires a value.', exit_code=2)
desktop.append(argv[index])
else:
commands.extend(argv[index:])
break
index += 1
return commands, desktop
def launcher_config() -> Path:
# Separate from HTTP credentials: corrupt connection settings must not block launch.
return config_path().with_name('desktop.json')
def _read_launcher(path):
try:
data = json.loads(path.read_text(encoding='utf-8'))
executable = data['executable']
if not isinstance(executable, str) or not executable:
raise ValueError('executable must be a nonempty path')
target = Path(executable).expanduser()
return target if target.is_absolute() else path.parent / target
except FileNotFoundError:
return None
except (OSError, ValueError, KeyError, TypeError) as exc:
raise CLIError('desktop_config_error', f'Cannot read desktop launcher {path}: {exc}') from None
def bundled_launcher():
if getattr(sys, 'frozen', False):
return Path(sys.executable).resolve().with_name('desktop.json')
return None
def desktop_candidates():
"""Return locations used by supported desktop installers."""
home = Path.home()
if sys.platform == 'darwin':
return [home / 'Applications/VoiceStudio.app', Path('/Applications/VoiceStudio.app')]
if sys.platform == 'win32':
roots = [Path(os.environ[key]) for key in ['LOCALAPPDATA', 'ProgramFiles', 'ProgramFiles(x86)']
if os.environ.get(key)]
candidates = [root / sub / 'VoiceStudio.exe' for root in roots
for sub in ['Programs/VoiceStudio', 'VoiceStudio', 'voicestudio-electron']]
# Respect NSIS's user-selected installation directory.
import winreg
for hive in [winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE]:
for view in [winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY]:
try:
with winreg.OpenKey(hive, r'Software\Microsoft\Windows\CurrentVersion\Uninstall',
0, winreg.KEY_READ | view) as uninstall:
index = 0
while True:
try:
name = winreg.EnumKey(uninstall, index)
except OSError:
break
index += 1
try:
with winreg.OpenKey(uninstall, name) as entry:
title = winreg.QueryValueEx(entry, 'DisplayName')[0]
if title == 'VoiceStudio':
location = winreg.QueryValueEx(entry, 'InstallLocation')[0]
candidates.insert(0, Path(location) / 'VoiceStudio.exe')
except OSError:
pass
except OSError:
pass
return candidates
candidates = [home / '.local/bin/VoiceStudio']
for root in [Path('/opt/VoiceStudio'), Path('/opt/voicestudio-electron')]:
candidates.extend(root / name for name in ['voicestudio-desktop', 'voicestudio-electron'])
if found := shutil.which('VoiceStudio'):
candidates.append(Path(found))
return candidates
def resolve_desktop():
explicit = os.environ.get('VOICESTUDIO_DESKTOP_APP')
manifest = bundled_launcher()
selected = Path(explicit).expanduser() if explicit else (
_read_launcher(manifest) if manifest else _read_launcher(launcher_config()))
candidates = [selected] if selected is not None else desktop_candidates()
own = Path(sys.executable).resolve() if getattr(sys, 'frozen', False) else None
# Never resolve the lowercase public command through PATH: that would recurse.
for candidate in candidates:
if candidate is None:
continue
candidate = candidate.resolve()
if candidate == own:
raise CLIError('desktop_config_error', 'Desktop executable points back to the CLI.')
if sys.platform == 'darwin' and candidate.suffix == '.app' and candidate.is_dir():
return ['/usr/bin/open', '-a', str(candidate), '--args']
if candidate.is_file() and (sys.platform == 'win32' or os.access(candidate, os.X_OK)):
return [str(candidate)]
raise CLIError('desktop_not_found', "Can't find the VoiceStudio app. Install VoiceStudio, or set "
'VOICESTUDIO_DESKTOP_APP to where the app is installed.')
def desktop_environment():
env = dict(os.environ)
env.pop('ELECTRON_RUN_AS_NODE', None)
# The frozen interpreter's library path must not leak into Electron or its Python backend.
if getattr(sys, 'frozen', False):
env['PYINSTALLER_RESET_ENVIRONMENT'] = '1'
for key in ['LD_LIBRARY_PATH', 'LIBPATH']:
original = env.pop(key + '_ORIG', None)
if original is None:
env.pop(key, None)
else:
env[key] = original
if sys.platform == 'win32':
ctypes.windll.kernel32.SetDllDirectoryW(None)
return env
def _direct_command(command):
"""An executable that receives arguments even when the app is already running.
``open -a`` drops arguments for a running app, and a command inside an
AppImage mount dies with this process; launch the bundle binary or the
image itself instead.
"""
if getattr(sys, 'frozen', False) and os.environ.get('APPIMAGE'):
return [os.environ['APPIMAGE']]
if command[:2] == ['/usr/bin/open', '-a'] and len(command) >= 3:
import plistlib
bundle = Path(command[2])
try:
with (bundle / 'Contents/Info.plist').open('rb') as stream:
name = plistlib.load(stream)['CFBundleExecutable']
except (OSError, KeyError, ValueError, plistlib.InvalidFileException):
name = bundle.stem
return [str(bundle / 'Contents/MacOS' / name)]
return command
def desktop_process(arguments, *, detached=False):
"""Start the desktop app with ownership switches; it may hand them to a running instance."""
command = _direct_command(resolve_desktop())
if user_data := os.environ.get('VOICESTUDIO_USER_DATA'):
arguments = [*arguments, '--user-data-dir=' + str(Path(user_data).expanduser())]
options = {'stdin': subprocess.DEVNULL, 'stdout': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL}
if detached:
options.update({'creationflags': subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
'close_fds': True} if os.name == 'nt' else {'start_new_session': True})
try:
return subprocess.Popen([*command, *arguments], env=desktop_environment(), **options)
except OSError as exc:
raise CLIError('desktop_launch_failed', f'Could not launch VoiceStudio: {exc}') from None
def launch_desktop(arguments=()):
command = resolve_desktop()
env = desktop_environment()
try:
# Wait so AppImage's mount stays alive while Electron uses its resources.
result = subprocess.run([*command, *arguments], env=env)
except OSError as exc:
raise CLIError('desktop_launch_failed', f'Could not launch VoiceStudio: {exc}') from None
if result.returncode:
raise CLIError('desktop_launch_failed', f'VoiceStudio desktop exited with status {result.returncode}.')
return 0
+25
View File
@@ -0,0 +1,25 @@
"""One error contract for parsers, transports and command handlers."""
import re
class CLIError(Exception):
def __init__(self, code: str, message: str, *, status: int | None = None,
exit_code: int = 1, retry_after: str | None = None, details=None):
super().__init__(message)
self.code, self.status, self.exit_code = code, status, exit_code
self.retry_after = retry_after
self.details = details
def scrub(value: str, secrets=()) -> str:
for secret in secrets:
if secret:
value = value.replace(secret, '[redacted]')
value = re.sub(r'(?i)(bearer\s+)[^\s"<>]+', r'\1[redacted]', value)
value = re.sub(r'(https?://)[^/\s@]+@', r'\1[redacted]@', value)
value = re.sub(r'(?i)((?:api_key|token|password|pin)=)[^&\s]+', r'\1[redacted]', value)
value = re.sub(r'(?i)("(?:api_key|token|password|access_token|refresh_token)"\s*:\s*)"(?:[^"\\]|\\.)*"',
r'\1"[redacted]"', value)
# Strip remote control characters to prevent terminal escape injection.
value = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', value)
return ''.join(c for c in value if c in '\n\t' or ord(c) >= 32).replace('\x7f', '')
+108
View File
@@ -0,0 +1,108 @@
"""Install the application's terminal command and handle launcher conflicts."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from .desktop import launcher_config
from .errors import CLIError
def atomic_write(path, content, mode=0o600):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(prefix='.launcher-', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as stream:
stream.write(content)
os.chmod(temp, mode)
os.replace(temp, path)
finally:
Path(temp).unlink(missing_ok=True)
def install(source, *, replace_launcher=False, update_shell=True, uv='uv'):
"""Install with uv, preserving an explicitly replaced launcher for desktop dispatch."""
bin_dir = Path(subprocess.check_output([uv, 'tool', 'dir', '--bin'], text=True).strip())
target = bin_dir / ('voicestudio.exe' if sys.platform == 'win32' else 'voicestudio')
installed = subprocess.check_output([uv, 'tool', 'list'], text=True)
owns_command = any(line.startswith('voicestudio-cli v') for line in installed.splitlines())
manifest = launcher_config()
previous_manifest = manifest.read_bytes() if manifest.exists() else None
saved = None
symlink = None
old_mode = None
backup = manifest.with_name('desktop-launcher')
backup_created = False
if (target.exists() or target.is_symlink()) and not owns_command:
if not replace_launcher:
raise CLIError('command_exists', f'{target} already exists. Rerun with --replace-launcher to '
'back up the existing launcher and replace the command.')
if target.is_symlink():
symlink = os.readlink(target)
executable = str(target.resolve())
if not target.is_file():
raise CLIError('invalid_launcher', 'Existing launcher does not point to a file.')
with target.open('rb') as stream:
header = stream.read(8192)
if header.startswith(b'#!') and b'voicestudio_cli' in header:
raise CLIError('invalid_launcher', 'Existing command points to another CLI installation. '
'Remove it with its package manager before migrating.')
else:
with target.open('rb') as stream:
header = stream.read(8192)
old_mode = target.stat().st_mode & 0o777
# Moving a native application binary away from its resources breaks it.
if not header.startswith(b'#!') or b'voicestudio_cli' in header:
raise CLIError('invalid_launcher', 'Existing executable is not a desktop shell wrapper. '
'Use a different UV_TOOL_BIN_DIR to install without replacing this executable.')
if backup.exists() or backup.is_symlink():
raise CLIError('command_exists', f'A saved launcher already exists at {backup}; inspect it before replacing another launcher.')
saved = target.read_bytes()
atomic_write(backup, saved, 0o700)
backup_created = True
executable = str(backup)
atomic_write(manifest, (json.dumps({'executable': executable}, indent=2) + '\n').encode())
try:
subprocess.run([uv, 'tool', 'install', '--force', str(source)], check=True)
except (OSError, subprocess.CalledProcessError):
if symlink is not None:
target.unlink(missing_ok=True)
target.symlink_to(symlink)
elif saved is not None:
atomic_write(target, saved, old_mode)
if previous_manifest is not None:
atomic_write(manifest, previous_manifest)
else:
manifest.unlink(missing_ok=True)
if backup_created:
backup.unlink(missing_ok=True)
message = 'CLI installation failed.'
if saved is not None or symlink is not None:
message += ' The previous launcher was restored.'
raise CLIError('install_failed', message) from None
if update_shell:
result = subprocess.run([uv, 'tool', 'update-shell'])
if result.returncode:
print(f'voicestudio: warning: PATH configuration failed; add {bin_dir} to PATH.', file=sys.stderr)
print(f'Installed command: {target}')
def main(argv=None):
parser = argparse.ArgumentParser(description='Install the VoiceStudio terminal command using uv.')
parser.add_argument('source', help='CLI package directory, wheel, or explicit package specifier')
parser.add_argument('--replace-launcher', action='store_true', help='Preserve an existing desktop launcher and replace its public command')
parser.add_argument('--no-modify-path', action='store_true', help='Skip uv tool update-shell')
args = parser.parse_args(argv)
try:
install(args.source, replace_launcher=args.replace_launcher, update_shell=not args.no_modify_path)
except (CLIError, OSError, subprocess.CalledProcessError) as exc:
print(f'voicestudio: {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())
+344
View File
@@ -0,0 +1,344 @@
"""Declarative HTTP commands. Resource IDs are encoded by the dispatcher."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Command:
name: str
method: str
route: str
description: str
params: tuple[str, ...] = ()
body: bool = False
upload: str = ''
binary: bool = False
destructive: bool = False
stream: bool = False
COMMANDS: list[Command] = []
# Plain-language help, written for people rather than derived from routes.
# How input is passed (--file, --field) belongs to the option help, not here.
DESCRIPTIONS = {
'voices show': 'Show a saved voice',
'voices usage': 'Show where a saved voice has been used',
'voices update': 'Change a saved voice',
'voices reference get': "Download a voice's reference recording",
'voices reference set': "Replace a voice's reference recording",
'voices image set': "Replace a voice's picture",
'voices consent set': 'Record consent for a cloned voice (consent text via --field consent_text=...)',
'voices consent revoke': 'Withdraw recorded consent for a voice',
'voices lock': 'Protect a voice from changes',
'voices unlock': 'Remove protection from a voice',
'voices export': 'Export a voice as a shareable file',
'voices inspect': 'Show what a shareable voice file contains, without importing it',
'voices import': 'Import a shareable voice file',
'voices describe': 'Preview how a text description maps to voice-design settings',
'gallery list': 'List voices in the gallery',
'gallery import': 'Add an audio clip to the gallery',
'gallery download': 'Download audio from a link into the gallery',
'gallery search': 'Search online videos for voice samples',
'gallery preview': 'Download a gallery voice preview',
'gallery update': 'Change a gallery voice',
'gallery save-voice': 'Save a gallery voice as one of your voices',
'gallery delete': 'Delete a gallery voice',
'gallery presets list': 'List ready-made voice presets',
'gallery presets use': 'Create a voice from a preset',
'gallery community list': 'List voices shared by the community',
'gallery community preview': 'Download a community voice preview',
'gallery community use': 'Create a voice from a community voice',
'gallery community submit': 'Show where to submit a voice to the community gallery',
'dictation models': 'List dictation models',
'dictation readiness': 'Check whether dictation is ready to use',
'dictation preferences show': 'Show dictation preferences',
'dictation preferences set': 'Change dictation preferences',
'stories render': 'Render a story to audio from a chapter plan',
'stories encode': 'Convert a WAV file to another format (--field format=mp3)',
'audiobook jobs': 'List interrupted audiobook and story renders you can resume',
'stories resume': 'Resume an interrupted story render',
'audiobook plan': 'Plan chapters and voices for an audiobook',
'audiobook preview': 'Render a short audiobook preview',
'audiobook render': 'Render an audiobook',
'dub transcript get': "Show a dubbing job's transcript",
'dub transcript set': "Replace a dubbing job's transcript",
'dub transcript clean': "Tidy a dubbing job's transcript segments",
'dub translate': 'Translate transcript segments',
'dub fit': 'Shorten translations to fit the original timing',
'dub generate': 'Generate the dubbed speech',
'dub preview': 'Generate one segment to preview it',
'dub cancel': 'Stop a running dubbing job',
'dub history': 'List past dubbing jobs',
'dub history-delete': 'Delete a past dubbing job',
'batch enqueue': 'Queue a video for dubbing (languages via --field langs=es,fr)',
'batch show': 'Show a batch job',
'batch cancel': 'Stop a batch job',
'batch retry': 'Retry a failed batch job',
'batch delete': 'Delete a batch job',
'jobs list': 'List background jobs',
'jobs show': 'Show a background job',
'jobs events': "Show a background job's progress events",
'jobs cancel': 'Stop a background job',
'jobs longform list': 'List finished audiobook and story renders',
'jobs longform delete': 'Delete a finished audiobook or story render',
'history list': 'List generated clips',
'history download': 'Download a generated clip by its file name',
'history quality': 'Show audio quality measurements for a clip',
'history delete': 'Delete a generated clip',
'history clear': 'Delete all generated clips',
'projects show': 'Show a project',
'projects export': 'Export a project to share or move it',
'projects import': 'Import an exported project',
'projects glossary list': "Show a project's glossary",
'projects glossary add': 'Add a glossary term',
'projects glossary update': 'Change a glossary term',
'projects glossary delete': 'Delete a glossary term',
'projects glossary extract': 'Suggest glossary terms from the project',
'audio clean': 'Remove noise from a recording',
'audio normalize': 'Even out the loudness of speech',
'audio convert-voice': 'Make a recording sound like a saved voice',
'audio direction': 'Read delivery directions from a script',
'audio rate-fit': 'Adjust speech speed to fit a duration',
'audio effects': 'List available audio effects',
'audio plugins': 'List installed audio plugins',
'audio watermark status': 'Check whether audio watermarking is available',
'audio watermark detect': 'Check a recording for a VoiceStudio watermark',
'audio watermark settings': 'Change watermark settings',
'pronunciation add': 'Add a pronunciation rule',
'pronunciation test': 'Show how text is read with the current rules',
'pronunciation export': 'Export pronunciation rules',
'pronunciation import': 'Import pronunciation rules',
'engines health': 'Check whether an engine is working',
'engines selftest': 'Run a quick test of an engine',
'engines disk-usage': 'Show how much disk space an engine uses',
'engines quants list': 'List size and quality variants of the GGUF engine',
'engines quants select': 'Choose a GGUF engine variant',
'engines quants download': 'Download a GGUF engine variant',
'models recommend': 'Suggest models that suit this computer',
'models access': 'Check whether a model can be downloaded (--query repo_id=<id>)',
'models install-status': 'Show model downloads in progress',
'models loaded': 'List models loaded in memory',
'models unload': 'Free the memory used by a loaded model',
'models delete': "Delete a model's downloaded files",
'models license show': "Show a model's license terms",
'models license revoke': "Withdraw acceptance of a model's terms",
'settings providers list': 'List AI text providers (used for translation and scripts)',
'settings providers configure': 'Set up an AI text provider',
'settings providers select': 'Choose the AI text provider to use',
'settings providers test': 'Check that an AI text provider responds',
'settings skills list': 'List AI text skills',
'settings skills set': 'Change an AI text skill',
'settings hf-token status': 'Show whether a Hugging Face token is saved',
'settings hf-token clear': 'Remove the saved Hugging Face token',
'settings storage show': 'Show how much disk space VoiceStudio uses',
'settings storage clear-temp': 'Delete temporary files',
'sharing status': 'Show whether other devices on your network can connect',
'sharing enable': 'Let other devices on your network connect',
'sharing disable': 'Stop other devices on your network from connecting',
'sharing tailscale status': 'Show Tailscale sharing status',
'sharing tailscale enable': 'Share VoiceStudio over Tailscale',
'sharing tailscale disable': 'Stop sharing VoiceStudio over Tailscale',
'integrations api schema': "Download the API's OpenAPI description",
'integrations mcp bindings list': 'List which voice each AI agent uses',
'integrations mcp bindings delete': "Remove an AI agent's voice choice",
'calls options': 'List call options',
'calls readiness': 'Check whether calls are ready to use',
'calls list': 'List calls',
'calls start': 'Start a call',
'calls configure': 'Change call settings',
'calls show': 'Show a call',
'calls events': "Follow a call's live events",
'calls say': 'Speak a line in a live call',
'calls takeover': 'Take over a live call yourself',
'calls hangup': 'End a call',
'calls delete': 'Delete a call record',
'calls recording': 'Download a call recording',
'diagnostics system': 'Show system and hardware information',
'diagnostics preflight': 'Check that this computer is ready to run VoiceStudio',
'diagnostics logs': 'Show recent backend logs',
'diagnostics errors': 'Show recent errors',
'diagnostics crashes': 'Show details of the last crash',
'diagnostics usage': 'Show usage statistics recorded on this computer',
'diagnostics notifications': 'Show app notifications',
'diagnostics bundle': 'Create a diagnostics file to attach to a bug report',
'diagnostics flush-memory': 'Free memory held by models and caches',
'diagnostics media-tools': 'Check the bundled ffmpeg and media tools',
'dub ingest': 'Start a dubbing job from a video link',
'projects create': 'Create a project',
'projects update': 'Change a project',
}
def add(name, method, route, description, params=(), **kwargs):
description = DESCRIPTIONS.get(name, description)
COMMANDS.append(Command(name, method, route, description, tuple(params), **kwargs))
add('voices list', 'GET', '/profiles', 'List your saved voices')
add('voices show', 'GET', '/profiles/{id}', 'Inspect a voice profile', ['id'])
add('voices update', 'PUT', '/profiles/{id}', 'Edit profile fields from --file JSON', ['id'], body=True)
add('voices usage', 'GET', '/profiles/{id}/usage', 'Inspect voice usage', ['id'])
add('voices delete', 'DELETE', '/profiles/{id}', 'Delete a saved voice', ['id'], destructive=True)
add('voices reference get', 'GET', '/profiles/{id}/audio', 'Download reference audio', ['id'], binary=True)
add('voices reference set', 'PUT', '/profiles/{id}/audio', 'Replace reference audio', ['id'], upload='ref_audio')
add('voices image set', 'PUT', '/profiles/{id}/image', 'Replace profile artwork', ['id'], upload='image')
add('voices consent set', 'POST', '/profiles/{id}/consent', 'Upload consent audio; --field consent_text=...', ['id'], upload='consent_audio')
add('voices consent revoke', 'DELETE', '/profiles/{id}/consent', 'Revoke consent', ['id'], destructive=True)
add('voices lock', 'POST', '/profiles/{id}/lock', 'Lock a voice with --file JSON', ['id'], body=True)
add('voices unlock', 'POST', '/profiles/{id}/unlock', 'Unlock with the required proof in --file JSON', ['id'], body=True)
add('voices export', 'POST', '/personas/export/{id}', 'Export a portable persona', ['id'], binary=True)
add('voices inspect', 'POST', '/personas/inspect', 'Inspect a portable persona bundle', upload='file')
add('voices import', 'POST', '/personas/import', 'Import a portable persona bundle', upload='file')
add('voices describe', 'POST', '/design/describe', 'Map a description to voice-design attributes', body=True)
for name, method, route, params, body, upload, binary in [
('list', 'GET', '/gallery/voices', (), False, '', False),
('import', 'POST', '/gallery/upload', (), False, 'audio', False),
('download', 'POST', '/gallery/download', (), True, '', False),
('search', 'POST', '/gallery/search/youtube', (), True, '', False),
('preview', 'GET', '/gallery/voices/{id}/preview', ('id',), False, '', True),
('update', 'PATCH', '/gallery/voices/{id}', ('id',), True, '', False),
('save-voice', 'POST', '/gallery/voices/{id}/save-as-profile', ('id',), True, '', False),
('delete', 'DELETE', '/gallery/voices/{id}', ('id',), False, '', False),
('presets list', 'GET', '/archetypes', (), False, '', False),
('presets use', 'POST', '/archetypes/{id}/use', ('id',), True, '', False),
('community list', 'GET', '/community/items', (), False, '', False),
('community preview', 'GET', '/community/items/{id}/preview', ('id',), False, '', True),
('community use', 'POST', '/community/items/{id}/use', ('id',), True, '', False),
('community submit', 'GET', '/community/submit-url', (), False, '', False),
]:
add('gallery ' + name, method, route, 'Gallery: ' + name, params, body=body,
upload=upload, binary=binary, destructive=method == 'DELETE')
for name in ['models', 'readiness']:
add('dictation ' + name, 'GET', '/dictation/' + name, 'Inspect dictation ' + name)
add('dictation preferences show', 'GET', '/dictation/prefs', 'Read dictation preferences')
add('dictation preferences set', 'POST', '/dictation/prefs', 'Set dictation preferences from --file JSON', body=True)
add('stories render', 'POST', '/longform/render', 'Render a chapter/span plan from --file JSON', body=True, stream=True)
add('stories encode', 'POST', '/stories/encode', 'Encode WAV; options through --field format=mp3', upload='file', binary=True)
add('stories resume', 'POST', '/audiobook/resume/{id}', 'Resume a longform job', ['id'], stream=True)
add('audiobook import', 'POST', '/audiobook/import', 'Import a supported document', upload='file')
add('audiobook cover', 'POST', '/audiobook/cover', 'Upload cover artwork', upload='cover')
for name, route, stream in [('plan', '/audiobook/plan', False), ('preview', '/audiobook/preview', True),
('render', '/audiobook', True)]:
add('audiobook ' + name, 'POST', route, 'Audiobook ' + name + ' from --file JSON', body=True, stream=stream)
add('audiobook jobs', 'GET', '/audiobook/jobs', 'List audiobook jobs')
add('audiobook resume', 'POST', '/audiobook/resume/{id}', 'Resume an audiobook', ['id'], stream=True)
add('dub upload', 'POST', '/dub/upload', 'Upload video to create a dubbing job', upload='video')
add('dub ingest', 'POST', '/dub/ingest-url', 'Import a media URL from --file JSON', body=True)
add('dub transcribe', 'POST', '/dub/transcribe/{id}', 'Transcribe a dubbing job', ['id'])
add('dub subtitles import', 'POST', '/dub/import-srt/{id}', 'Import subtitles', ['id'], upload='file')
add('dub transcript get', 'GET', '/dub/segments-text/{id}', 'Read transcript segments', ['id'])
add('dub transcript set', 'POST', '/dub/sync-transcript/{id}', 'Save segments from --file JSON', ['id'], body=True)
add('dub transcript clean', 'POST', '/dub/cleanup-segments/{id}', 'Clean segments from --file JSON', ['id'], body=True)
add('dub translate', 'POST', '/dub/translate', 'Translate segments from --file JSON', body=True)
add('dub fit', 'POST', '/dub/agent-fit', 'Fit translated segments from --file JSON', body=True)
add('dub generate', 'POST', '/dub/generate/{id}', 'Generate dubbed speech from --file JSON', ['id'], body=True, stream=True)
add('dub preview', 'POST', '/dub/preview-segment/{id}', 'Preview a segment from --file JSON', ['id'], body=True)
add('dub tracks', 'GET', '/dub/tracks/{id}', 'List language tracks', ['id'])
add('dub quality', 'POST', '/dub/qc/{id}', 'Check dubbing quality', ['id'], body=True)
add('dub cancel', 'POST', '/dub/abort/{id}', 'Abort a dubbing job', ['id'])
add('dub history', 'GET', '/dub/history', 'List dubbing history')
add('dub history-delete', 'DELETE', '/dub/history/{id}', 'Delete a dubbing record', ['id'], destructive=True)
add('batch enqueue', 'POST', '/batch/enqueue', 'Queue a video; --field langs=es,fr', upload='video')
add('batch list', 'GET', '/batch/jobs', 'List batch jobs')
add('batch show', 'GET', '/batch/jobs/{id}', 'Inspect a batch job', ['id'])
for action in ['cancel', 'retry']:
add('batch ' + action, 'POST', '/batch/jobs/{id}/' + action, 'Batch ' + action, ['id'])
add('batch delete', 'DELETE', '/batch/jobs/{id}', 'Delete a batch record', ['id'], destructive=True)
add('batch download', 'GET', '/batch/download/{id}/{language}', 'Download a batch result', ['id', 'language'], binary=True)
add('jobs list', 'GET', '/jobs', 'List shared jobs')
add('jobs show', 'GET', '/jobs/{id}', 'Inspect a shared job', ['id'])
add('jobs events', 'GET', '/jobs/{id}/events', 'Read persisted job events', ['id'])
add('jobs cancel', 'POST', '/tasks/cancel/{id}', 'Cancel a task by task ID', ['id'])
add('jobs longform list', 'GET', '/longform/jobs', 'List longform jobs')
add('jobs longform delete', 'DELETE', '/longform/jobs/{id}', 'Delete a longform run', ['id'], destructive=True)
add('history list', 'GET', '/history', 'List generated takes')
add('history download', 'GET', '/audio/{id}', 'Download a take by audio filename', ['id'], binary=True)
add('history quality', 'GET', '/audio/{id}/quality', 'Read audio quality', ['id'])
add('history delete', 'DELETE', '/history/{id}', 'Delete a take', ['id'], destructive=True)
add('history clear', 'DELETE', '/history', 'Clear generation history', destructive=True)
add('projects list', 'GET', '/projects', 'List projects')
add('projects show', 'GET', '/projects/{id}', 'Read a project', ['id'])
add('projects create', 'POST', '/projects', 'Create a project from --file JSON', body=True)
add('projects update', 'PUT', '/projects/{id}', 'Update a project from --file JSON', ['id'], body=True)
add('projects delete', 'DELETE', '/projects/{id}', 'Delete a project', ['id'], destructive=True)
add('projects export', 'POST', '/project-bundles/export', 'Export a project handoff from --file JSON', body=True)
add('projects import', 'POST', '/project-bundles/import', 'Import a project handoff', upload='@raw')
add('projects glossary list', 'GET', '/glossary/{id}', 'Read a project glossary', ['id'])
add('projects glossary add', 'POST', '/glossary/{id}', 'Add a glossary entry from --file JSON', ['id'], body=True)
add('projects glossary update', 'PUT', '/glossary/{id}/{term}', 'Update a glossary entry', ['id', 'term'], body=True)
add('projects glossary delete', 'DELETE', '/glossary/{id}/{term}', 'Delete a glossary entry', ['id', 'term'], destructive=True)
add('projects glossary extract', 'POST', '/glossary/{id}/auto-extract', 'Extract glossary terms', ['id'], body=True)
add('audio clean', 'POST', '/clean-audio', 'Clean reference audio', upload='audio', binary=True)
add('audio normalize', 'POST', '/tools/normalize-speech', 'Normalize speech audio', upload='audio', binary=True)
add('audio convert-voice', 'POST', '/convert', 'Convert a voice; options via --field', upload='audio', binary=True)
add('audio direction', 'POST', '/tools/direction', 'Parse direction from --file JSON', body=True)
add('audio rate-fit', 'POST', '/tools/rate-fit', 'Fit speech timing from --file JSON', body=True)
add('audio effects', 'GET', '/tools/effects', 'List audio effects')
add('audio plugins', 'GET', '/tools/plugins', 'Inspect plugin capabilities')
add('audio watermark status', 'GET', '/watermark/status', 'Inspect watermark support')
add('audio watermark detect', 'POST', '/watermark/detect', 'Detect an audio watermark', upload='file')
add('audio watermark settings', 'POST', '/watermark/settings', 'Update watermark settings', body=True)
add('pronunciation list', 'GET', '/pronunciation', 'List pronunciation rules')
add('pronunciation add', 'POST', '/pronunciation', 'Add a rule from --file JSON', body=True)
add('pronunciation update', 'PUT', '/pronunciation/{id}', 'Update a rule', ['id'], body=True)
add('pronunciation delete', 'DELETE', '/pronunciation/{id}', 'Delete a rule', ['id'], destructive=True)
add('pronunciation test', 'POST', '/pronunciation/test', 'Test substitutions from --file JSON', body=True)
add('pronunciation export', 'GET', '/pronunciation/export', 'Export pronunciation JSON')
add('pronunciation import', 'POST', '/pronunciation/import', 'Import pronunciation JSON', body=True)
add('engines health', 'GET', '/engines/{id}/health', 'Inspect engine health', ['id'])
add('engines selftest', 'POST', '/engines/{id}/selftest', 'Run an engine self-test', ['id'])
add('engines disk-usage', 'GET', '/engines/{id}/disk-usage', 'Inspect engine disk use', ['id'])
add('engines quants list', 'GET', '/engines/omnivoice-gguf/quants', 'List GGUF quantizations')
for action in ['select', 'download']:
add('engines quants ' + action, 'POST', '/engines/omnivoice-gguf/quants/' + action,
'GGUF quantization ' + action + ' from --file JSON', body=True)
add('models recommend', 'GET', '/setup/recommendations', 'Recommend models for this host')
add('models access', 'GET', '/models/access/status', 'Inspect model access; --query repo_id=<id>')
add('models install-status', 'GET', '/models/install/status', 'Inspect download jobs')
add('models loaded', 'GET', '/model/loaded', 'List resident models')
add('models unload', 'POST', '/model/unload/{id}', 'Unload a resident model', ['id'])
add('models delete', 'DELETE', '/models/{id}', 'Delete model files by catalogue ID', ['id'], destructive=True)
add('models license show', 'GET', '/models/licenses/details/{id}', 'Read model terms', ['id'])
add('models license revoke', 'POST', '/models/licenses/revoke', 'Revoke acceptance from --file JSON', body=True, destructive=True)
add('settings providers list', 'GET', '/api/settings/llm-providers', 'List LLM providers')
add('settings providers configure', 'PUT', '/api/settings/llm-providers/{id}', 'Configure a provider', ['id'], body=True)
add('settings providers select', 'POST', '/api/settings/llm-providers/active', 'Select provider from --file JSON', body=True)
add('settings providers test', 'POST', '/api/settings/llm-providers/{id}/test', 'Test provider connectivity', ['id'])
add('settings skills list', 'GET', '/api/settings/llm-skills', 'List LLM skills')
add('settings skills set', 'PUT', '/api/settings/llm-skills/{id}', 'Configure a skill', ['id'], body=True)
add('settings hf-token status', 'GET', '/api/settings/hf-token/state', 'Inspect HF credential state')
add('settings hf-token clear', 'DELETE', '/api/settings/hf-token', 'Remove HF credential', destructive=True)
add('settings storage show', 'GET', '/api/settings/storage', 'Inspect storage use')
add('settings storage clear-temp', 'POST', '/api/settings/storage/temp/clear', 'Clear temporary files', destructive=True)
for name, route in [('status', '/system/network/state'), ('enable', '/system/network/enable'),
('disable', '/system/network/disable'), ('tailscale status', '/system/tailscale/status'),
('tailscale enable', '/system/tailscale/enable'), ('tailscale disable', '/system/tailscale/disable')]:
add('sharing ' + name, 'GET' if name.endswith('status') else 'POST', route, 'Sharing: ' + name)
add('integrations api schema', 'GET', '/openapi.json', 'Download the running API schema')
add('integrations mcp bindings list', 'GET', '/api/mcp/bindings', 'List agent voice bindings')
add('integrations mcp bindings delete', 'DELETE', '/api/mcp/bindings/{id}', 'Delete an agent binding', ['id'], destructive=True)
for name, route in [('options', '/calls/options'), ('readiness', '/calls/readiness'), ('list', '/calls')]:
add('calls ' + name, 'GET', route, 'Calls: ' + name)
add('calls start', 'POST', '/calls', 'Start a call from --file JSON', body=True)
add('calls configure', 'PUT', '/calls/settings', 'Configure calls', body=True)
for name, method, suffix in [('show', 'GET', ''), ('events', 'GET', '/events'),
('say', 'POST', '/say'), ('takeover', 'POST', '/takeover'),
('hangup', 'POST', '/hangup'), ('delete', 'DELETE', ''),
('recording', 'GET', '/recording')]:
add('calls ' + name, method, '/calls/{id}' + suffix, 'Calls: ' + name, ['id'],
body=name == 'say', binary=name == 'recording', destructive=name == 'delete', stream=name == 'events')
for name, route in [('system', '/system/info'), ('preflight', '/setup/preflight'),
('logs', '/system/logs'), ('errors', '/system/errors/recent'),
('crashes', '/system/last-run-crash'), ('usage', '/stats/usage'),
('notifications', '/system/notifications'), ('media-tools', '/media-tools/status')]:
add('diagnostics ' + name, 'GET', route, 'Diagnostics: ' + name)
add('diagnostics bundle', 'POST', '/system/diagnostic-bundle', 'Create a diagnostic bundle')
add('diagnostics flush-memory', 'POST', '/system/flush-memory', 'Release backend memory')
+187
View File
@@ -0,0 +1,187 @@
"""Readable terminal output for any command result, chosen by the data's shape.
No command needs its own formatting code: text prints as is, a result with a
``message`` prints the message, flat objects print as aligned fields, lists of
objects print as tables, an object wrapping one list prints the table plus its
summary fields, and nested objects print as indented sections. ``--json`` skips
all of this and prints the data unchanged.
When stdout is not a terminal, tables print as tab-separated rows without a
header or truncation, so ``voicestudio voices list | cut -f2`` works.
"""
from datetime import datetime
import shutil
# Friendlier names for fields whose raw name reads like an implementation detail.
LABELS = {'method': 'Installed as', 'executable': 'Location', 'arch': 'Architecture',
'automatic': 'Updates from the app', 'instructions': 'How to update'}
ACRONYMS = {'url': 'URL', 'id': 'ID', 'api': 'API', 'hf': 'HF', 'mcp': 'MCP', 'gpu': 'GPU',
'cpu': 'CPU', 'asr': 'ASR', 'tts': 'TTS', 'llm': 'LLM', 'vram': 'VRAM', 'ram': 'RAM'}
# Identifying fields lead a table; everything else follows in the order the data gives.
PRIORITY = ['id', 'name', 'title', 'label', 'status', 'state', 'language', 'lang', 'engine',
'backend_id', 'model_id', 'repo_id', 'type', 'kind', 'family', 'installed', 'active',
'size_bytes', 'duration', 'created_at', 'updated_at']
# A unit suffix in a field name moves to its value: disk_free_gb=71.8 -> "Disk free: 71.8 GB".
UNITS = {'_gb': 'GB', '_mb': 'MB', '_kb': 'KB', '_ms': 'ms', '_seconds': 's', '_secs': 's', '_s': 's',
'_pct': '%', '_percent': '%'}
MAX_CELL = 40
INDENT = ' '
def is_scalar(value):
return value is None or isinstance(value, (str, int, float, bool))
def label(key):
if key in LABELS:
return LABELS[key]
key = str(key)
for suffix in UNITS:
if key.endswith(suffix) and key != suffix:
key = key[:-len(suffix)] # the unit moves to the value
break
else:
if key.endswith('_bytes') and key != '_bytes':
key = key[:-6] # the value is already shown as a size
words = [ACRONYMS.get(word.lower(), word) for word in str(key).replace('_', ' ').replace('-', ' ').split()]
text = ' '.join(words)
return text[:1].upper() + text[1:]
def _size(number):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if abs(number) < 1024 or unit == 'TB':
return f'{number:.0f} {unit}' if unit == 'B' else f'{number:.1f} {unit}'
number /= 1024
def value_text(key, value):
"""One value as text; meaning comes from the field name, never the command."""
if value is True:
return 'yes'
if value is False:
return 'no'
if value is None or value == '':
return '—'
name = str(key).lower()
if isinstance(value, (int, float)):
if name.endswith('_at') or name in {'timestamp', 'created', 'updated', 'modified', 'mtime'}:
seconds = value / 1000 if value > 1e12 else value
if 1e8 < seconds < 1e10: # a plausible epoch, not a counter
return datetime.fromtimestamp(seconds).strftime('%Y-%m-%d %H:%M')
if name.endswith('_bytes') or name in {'bytes', 'size'}:
return _size(value)
for suffix, unit in UNITS.items():
if name.endswith(suffix) and name != suffix:
number = f'{value:.2f}'.rstrip('0').rstrip('.') if isinstance(value, float) else str(value)
return number + ('' if unit == '%' else ' ') + unit
if isinstance(value, float):
return f'{value:.2f}'.rstrip('0').rstrip('.')
return str(value)
if isinstance(value, list):
if all(is_scalar(item) for item in value) and len(', '.join(map(str, value))) <= MAX_CELL:
return ', '.join(value_text(key, item) for item in value) or '—'
return f'{len(value)} item' + ('' if len(value) == 1 else 's')
if isinstance(value, dict):
return f'{len(value)} field' + ('' if len(value) == 1 else 's')
return str(value).replace('\n', ' ')
def _clip(text, limit):
return text if len(text) <= limit else text[:max(1, limit - 1)] + '…'
def _columns(rows):
seen = []
for row in rows:
for key in row:
if key not in seen:
seen.append(key)
scalar = [key for key in seen if any(is_scalar(row.get(key)) and row.get(key) is not None for row in rows)]
nested = [key for key in seen if key not in scalar and not str(key).startswith('_')]
ranked = [key for key in PRIORITY if key in scalar]
return ranked + [key for key in scalar if key not in ranked] + nested
def table(rows, *, tty, width):
if not rows:
return 'No results.' if tty else ''
columns = _columns(rows)
cells = [[value_text(key, row.get(key)) for key in columns] for row in rows]
if not tty:
# Scripts get every column untruncated: empty stays empty, nested stays JSON.
import json
def raw(key, value):
if value is None or value == '':
return ''
if isinstance(value, (list, dict)):
return json.dumps(value, ensure_ascii=False, separators=(',', ':'))
return value_text(key, value)
return '\n'.join('\t'.join(raw(key, row.get(key)).replace('\t', ' ').replace('\n', ' ')
for key in columns) for row in rows)
headers = [label(key).upper() for key in columns]
widths = [min(MAX_CELL, max(len(headers[i]), *(len(line[i]) for line in cells))) for i in range(len(columns))]
# Keep the leading (most identifying) columns that fit the terminal.
keep = len(columns)
while keep > 1 and sum(widths[:keep]) + 2 * (keep - 1) > width:
keep -= 1
if keep == 1:
widths[0] = max(4, min(widths[0], width))
lines = [headers[:keep], *(line[:keep] for line in cells)]
return '\n'.join(' '.join(_clip(text, widths[i]).ljust(widths[i]) for i, text in enumerate(line)).rstrip()
for line in lines)
def _fields(mapping, *, tty, width, depth):
"""Aligned scalar fields first, then each nested field as an indented section."""
scalars = {key: value for key, value in mapping.items()
if not str(key).startswith('_') and (is_scalar(value) or (
isinstance(value, list) and all(is_scalar(item) for item in value)
and len(value_text(key, value)) <= MAX_CELL))}
blocks = []
if scalars:
pad = max(len(label(key)) for key in scalars) + 1
blocks.append('\n'.join(f'{label(key) + ":":<{pad}} {value_text(key, value)}'
for key, value in scalars.items()))
for key, value in mapping.items():
if key in scalars or str(key).startswith('_'):
continue
body = render(value, tty=tty, width=width - len(INDENT), depth=depth + 1)
blocks.append(label(key) + ':\n' + '\n'.join(INDENT + line if line else line for line in body.splitlines()))
return '\n\n'.join(blocks) if depth == 0 else '\n'.join(blocks)
def render(result, *, tty=None, width=None, depth=0):
if tty is None:
import sys
tty = sys.stdout.isatty()
if width is None:
width = shutil.get_terminal_size((100, 24)).columns
if isinstance(result, str):
return result
if is_scalar(result):
return value_text('', result)
if isinstance(result, list):
if all(isinstance(item, dict) for item in result):
return table(result, tty=tty, width=width)
if all(is_scalar(item) for item in result):
return '\n'.join(value_text('', item) for item in result) or ('No results.' if tty else '')
return '\n'.join(('- ' if tty else '') + render(item, tty=tty, width=width, depth=depth + 1)
for item in result)
if isinstance(result, dict):
if isinstance(result.get('message'), str):
return result['message']
if not result or (depth == 0 and result == {'ok': True}):
return 'Done.' if depth == 0 else '—'
lists = [key for key, value in result.items() if isinstance(value, list) and value
and all(isinstance(item, dict) for item in value)]
others = {key: value for key, value in result.items() if key not in lists}
# A list wrapped with summary fields ({"models": [...], "total": 12}) is the list.
if depth == 0 and len(lists) == 1 and all(is_scalar(value) for value in others.values()):
body = table(result[lists[0]], tty=tty, width=width)
if not tty or not others:
return body
return body + '\n\n' + _fields(others, tty=tty, width=width, depth=depth)
return _fields(result, tty=tty, width=width, depth=depth)
return str(result)
+186
View File
@@ -0,0 +1,186 @@
"""Reach the desktop app's local backend, starting the app in the background.
The CLI never launches the Python backend itself. When no backend answers, it
starts the installed desktop app without a window; the app's own supervisor
starts the backend with the same environment and port selection as the GUI,
publishes the address in ``backend.json``, and stops after an idle period.
Opening the app later shows a window in that same process.
"""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from .config import loopback
from .desktop import BACKGROUND_FLAG, STOP_FLAG, desktop_process
from .errors import CLIError
from .transport import Client
# Questions about live state must not create a backend just to answer "nothing".
OBSERVE = frozenset('''batch cancel|batch delete|batch download|batch list|batch show|batch retry|
calls delete|calls events|calls hangup|calls list|calls say|calls show|calls takeover|
diagnostics flush-memory|diagnostics notifications|diagnostics system|dub cancel|
engines install-status|jobs cancel|models install-cancel|models install-status|
models loaded|models unload|sharing disable|sharing status|sharing tailscale disable|
sharing tailscale status|status|connection test'''.replace('\n', '').split('|'))
DISCOVERY_FILE = 'backend.json'
def user_data():
if override := os.environ.get('VOICESTUDIO_USER_DATA'):
return Path(override).expanduser()
if sys.platform == 'darwin':
return Path.home() / 'Library/Application Support/VoiceStudio'
if sys.platform == 'win32':
return Path(os.environ.get('APPDATA', Path.home() / 'AppData/Roaming')) / 'VoiceStudio'
return Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'VoiceStudio'
def discovery():
"""The running app's published backend record, or None."""
try:
record = json.loads((user_data() / DISCOVERY_FILE).read_text(encoding='utf-8'))
except (OSError, ValueError):
return None
if not isinstance(record, dict) or record.get('schema') != 1 or not isinstance(record.get('url'), str):
return None
from urllib.parse import urlsplit
try:
parsed = urlsplit(record['url'])
parsed.port
except ValueError:
return None
if not record.get('remote') and (parsed.scheme != 'http' or not loopback(parsed.hostname)):
return None # A local record must never redirect requests off this machine.
return record
def healthy(url):
try:
Client(url, '', 1).health()
return True
except CLIError:
return False
def running_backend(default_url):
"""The URL of a live local backend: the app's published one, else the default."""
record = discovery()
if record and record.get('remote'):
raise CLIError('remote_backend',
f'VoiceStudio is connected to the remote backend {record["url"]}. Use it with '
f'"voicestudio connection set {record["url"]}" and "voicestudio connection auth set --stdin".')
for url in ([record['url']] if record else []) + [default_url]:
if healthy(url):
return url, record if record and record['url'] == url else None
return None, record
def _check_stage(record):
stage = record.get('stage') if record else None
if stage == 'setup_required':
raise CLIError('runtime_not_ready', 'VoiceStudio has not finished setup. Open VoiceStudio, complete '
'setup, then run this command again.')
if stage in {'failed', 'port_in_use'}:
raise CLIError('backend_failed', 'VoiceStudio could not start its backend. Open VoiceStudio to see '
'why and repair it, then run this command again.')
def startup_budget():
try:
value = float(os.environ.get('OMNIVOICE_STARTUP_BUDGET_S', ''))
except ValueError:
value = 0
# Electron's low-spec budget doubles its default; never give up before it.
return value if value > 0 else 600
def start_backend(default_url, *, quiet=False):
"""Start the desktop app in the background and wait for its backend."""
before = discovery()
started = time.monotonic()
try:
child = desktop_process([BACKGROUND_FLAG], detached=True)
except CLIError as exc:
if exc.code != 'desktop_not_found':
raise
raise CLIError('backend_stopped', 'VoiceStudio is not running and the desktop app was not found. '
'Install VoiceStudio, set VOICESTUDIO_DESKTOP_APP, or pass --url for another '
'backend.') from None
if not quiet:
print('Starting VoiceStudio in the background…', file=sys.stderr, flush=True)
deadline = started + startup_budget()
while time.monotonic() < deadline:
url, record = running_backend(default_url)
if url:
return url
code = child.poll()
# A record left from before this launch may describe a process that is
# gone; trust it once it changed, or once an existing instance took over.
if record and (record != before or code == 0):
_check_stage(record)
if code not in (None, 0):
raise CLIError('backend_failed', f'VoiceStudio exited during startup (status {code}). Open '
'VoiceStudio to see why.')
time.sleep(.5)
raise CLIError('runtime_timeout', 'VoiceStudio did not finish starting its backend in time. Open '
'VoiceStudio to see its progress, or run "voicestudio status".')
def stop_backend(default_url):
record = discovery()
url = record['url'] if record and not record.get('remote') else None
if not url or not healthy(url):
if healthy(default_url):
raise CLIError('not_app_owned', f'VoiceStudio at {default_url} cannot be stopped from the terminal: it '
'was started by an older VoiceStudio app, a source checkout or Docker. Quit it where it '
'was started (update VoiceStudio to stop it from the terminal next time).')
return {'stopped': False, 'message': 'VoiceStudio is not running.'}
if record.get('window'):
raise CLIError('app_open', 'VoiceStudio is open in a window. Quit it from the app to stop it.')
try:
desktop_process([STOP_FLAG]).wait(timeout=30)
except subprocess.TimeoutExpired:
pass
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if not healthy(url):
return {'stopped': True, 'message': 'VoiceStudio stopped.'}
time.sleep(.5)
raise CLIError('stop_timeout', 'VoiceStudio did not stop within 30 seconds; quit it from the app.')
class LocalClient(Client):
"""The default target: this machine's desktop app, started when needed."""
def __init__(self, url, key, timeout, command, *, quiet=False):
super().__init__(url, key, timeout)
self.command = command
self.quiet = quiet
self.remote = None
def _resolve(self):
url, _record = running_backend(self.url)
if not url:
if self.command in OBSERVE:
raise CLIError('backend_stopped', 'VoiceStudio is not running, so nothing is active. Open '
'VoiceStudio, or run any other command to start it in the background.')
url = start_backend(self.url, quiet=self.quiet)
if url != self.url:
# A saved credential is bound to its origin; only the environment key may follow.
self.key = os.environ.get('OMNIVOICE_API_KEY', '').strip()
self.url = url
self.remote = Client(url, self.key, self.timeout)
def open(self, method, path, **kwargs):
if self.remote is None:
self._resolve()
return self.remote.open(method, path, **kwargs)
def health(self):
if self.remote is None:
self._resolve()
return self.remote.health()
+184
View File
@@ -0,0 +1,184 @@
"""Streaming HTTP transport with origin-bound credentials and atomic output."""
from contextlib import contextmanager
import http.client
import json
import mimetypes
import os
from pathlib import Path
import secrets
import socket
import ssl
import tempfile
from urllib import request, error
from urllib.parse import urlencode, urlsplit
from .config import loopback, normalize_url
from .errors import CLIError, scrub
CHUNK = 64 * 1024
MAX_JSON = 16 * 1024 * 1024
def response_error(status, headers, raw, key=''):
"""One error contract for live HTTP and local application responses."""
raw = raw.decode('utf-8', errors='replace')
detail = None
try:
detail = json.loads(raw)
detail = detail.get('detail', detail.get('error', detail)) if isinstance(detail, dict) else detail
if isinstance(detail, dict):
detail = detail.get('message', detail.get('detail', detail))
message = detail if isinstance(detail, str) else json.dumps(detail, ensure_ascii=False)
except ValueError:
message = raw or f'Request failed with status {status}'
codes = {401: 'authentication_error', 403: 'permission_denied', 404: 'not_found',
409: 'conflict', 422: 'validation_error', 429: 'rate_limited'}
return CLIError(codes.get(status, 'backend_error'), f'HTTP {status}: {scrub(str(message), [key])}',
status=status, retry_after=headers.get('Retry-After'), details=detail)
class NoRedirect(request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise CLIError('redirect_refused', 'Backend redirected the request; configure its final URL explicitly')
class Client:
def __init__(self, url: str, key: str = '', timeout: float = 600):
self.url, self.key, self.timeout = normalize_url(url), key, timeout
self.identified = False
if key and urlsplit(url).scheme != 'https' and not loopback(urlsplit(url).hostname):
raise CLIError('credential_transport', 'Remote credentials require HTTPS')
handlers = [NoRedirect()]
if loopback(urlsplit(url).hostname):
handlers.append(request.ProxyHandler({}))
self.opener = request.build_opener(*handlers)
@contextmanager
def open(self, method: str, path: str, *, payload=None, form=None, files=None, query=None, raw_file=None):
if not path.startswith('/') or path.startswith('//') or '..' in path.split('/'):
raise CLIError('invalid_response', 'Refused unsafe backend resource path')
if path != '/health' and not self.identified:
self.health()
target = self.url + path + (('?' + urlencode(query, doseq=True)) if query else '')
headers = {'Accept': '*/*', 'User-Agent': 'VoiceStudio-CLI'}
if self.key:
headers['Authorization'] = f'Bearer {self.key}'
body = None
stream = None
if raw_file is not None:
stream = Path(raw_file).open('rb')
body = stream
headers.update({'Content-Type': 'application/octet-stream',
'Content-Length': str(os.fstat(stream.fileno()).st_size)})
elif files or form is not None:
stream, content_type, length = multipart(form or {}, files or {})
body = stream
headers.update({'Content-Type': content_type, 'Content-Length': str(length)})
elif payload is not None:
body = json.dumps(payload, allow_nan=False).encode()
headers['Content-Type'] = 'application/json'
try:
with self.opener.open(request.Request(target, data=body, method=method, headers=headers),
timeout=self.timeout) as response:
yield response
except error.HTTPError as exc:
raise response_error(exc.code, exc.headers, exc.read(64 * 1024), self.key) from None
except (error.URLError, TimeoutError, socket.timeout, ssl.SSLError) as exc:
raise CLIError('connection_error',
f'Cannot connect to {self.url}. Open VoiceStudio or configure --url. '
f'{scrub(str(exc), [self.key])}') from None
except (http.client.HTTPException, ConnectionError) as exc:
raise CLIError('incomplete_response', f'Backend connection interrupted: {exc}') from None
finally:
if stream is not None:
stream.close()
def json(self, method: str, path: str, **kwargs):
with self.open(method, path, **kwargs) as response:
if response.status == 204:
return {'ok': True}
if 'json' not in response.headers.get('Content-Type', ''):
raise CLIError('invalid_response', 'Expected JSON from the backend')
data = response.read(MAX_JSON + 1)
if len(data) > MAX_JSON:
raise CLIError('invalid_response', 'Backend JSON response exceeded 16 MiB')
try:
return json.loads(data)
except (ValueError, UnicodeError):
raise CLIError('invalid_response', 'Backend returned invalid JSON') from None
def health(self):
with self.open('GET', '/health') as response:
marker = response.headers.get('X-OmniVoice-Backend')
try:
value = json.loads(response.read(64 * 1024))
except (ValueError, UnicodeError):
raise CLIError('wrong_service', 'The selected endpoint is not a VoiceStudio backend') from None
if not marker or not isinstance(value, dict) or value.get('status') != 'ok' or not isinstance(value.get('version'), str):
raise CLIError('wrong_service', 'The selected endpoint is not a healthy VoiceStudio backend')
self.identified = True
return value
def multipart(fields: dict, files: dict):
"""Spool multipart bodies to disk, bounding memory for large videos."""
boundary = 'voicestudio-' + secrets.token_hex(16)
stream = tempfile.TemporaryFile()
try:
for name, value in fields.items():
if value is None:
continue
stream.write(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode())
text = json.dumps(value, ensure_ascii=False) if not isinstance(value, str) else value
stream.write(text.encode('utf-8') + b'\r\n')
for name, source in files.items():
path = Path(source)
filename = path.name.replace('"', '_').replace('\r', '_').replace('\n', '_').replace('\\', '_')
media = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
stream.write((f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"; '
f'filename="{filename}"\r\nContent-Type: {media}\r\n\r\n').encode())
with path.open('rb') as audio:
while chunk := audio.read(CHUNK):
stream.write(chunk)
stream.write(b'\r\n')
stream.write(f'--{boundary}--\r\n'.encode())
length = stream.tell()
stream.seek(0)
return stream, f'multipart/form-data; boundary={boundary}', length
except BaseException:
stream.close()
raise
def download(response, destination: str, *, overwrite: bool = False) -> dict:
import sys
if destination == '-':
if sys.stdout.isatty():
raise CLIError('usage_error', 'Refusing binary output to a terminal; use --output <file>', exit_code=2)
while chunk := response.read(CHUNK):
sys.stdout.buffer.write(chunk)
return {'output': '-'}
path = Path(destination).expanduser()
if path.exists() and not overwrite:
raise CLIError('output_exists', f'Output already exists: {path}. Use --overwrite to replace it.')
fd, name = tempfile.mkstemp(prefix='.' + path.name + '-', suffix='.part', dir=path.parent)
received = 0
try:
with os.fdopen(fd, 'wb') as stream:
while chunk := response.read(CHUNK):
stream.write(chunk)
received += len(chunk)
expected = response.headers.get('Content-Length')
if expected is not None and received != int(expected):
raise CLIError('incomplete_response', 'Download ended before all bytes arrived')
if overwrite:
os.replace(name, path)
else:
# Exclusive creation prevents races from overwriting another process's result.
try:
os.link(name, path)
except FileExistsError:
raise CLIError('output_exists', f'Output already exists: {path}') from None
return {'output': str(path), 'bytes': received}
finally:
Path(name).unlink(missing_ok=True)
+32
View File
@@ -0,0 +1,32 @@
"""VoiceStudio application releases; installing an update belongs to the app's own updater."""
from .application import installed_application
from .errors import CLIError
def install_info(app=None):
app = app or installed_application()
instructions = {
'source': 'Update and rebuild VoiceStudio from its source checkout.',
'store': ('Update VoiceStudio through Snap.' if app.distribution == 'snap-store' else
'Update VoiceStudio through the Mac App Store.'),
'directory': 'Install an application package to enable managed updates.',
}
automatic = app.method in {'appimage', 'dmg', 'nsis', 'deb'}
fallback = ('Run voicestudio update, or use Settings → Updates in the app.' if automatic
else 'Update VoiceStudio using its application installer.')
return app.info() | {'automatic': automatic, 'instructions': instructions.get(app.method, fallback)}
def open_app_updater(info):
"""Hand the update to the app, which checks, downloads, verifies and installs it.
The CLI makes no network requests of its own: the app's updater is the one
sanctioned update check, and it uses the channel chosen in Settings → Updates.
"""
if not info['automatic']:
raise CLIError('update_unsupported', info['instructions'])
from .desktop import CHECK_UPDATES_FLAG, desktop_process
desktop_process([CHECK_UPDATES_FLAG], detached=True)
return {'current': info['version'], 'opened': True,
'message': f'VoiceStudio {info["version"]} opened Settings → Updates to check for an update. '
'Updates download and install from there.'}
+9
View File
@@ -62,6 +62,15 @@ The [shell installer](script.md) (`curl -fsSL https://voicestudio.sh/install | s
downloads the latest AppImage, verifies it against the release's
`SHA256SUMS.txt`, and installs it as `~/.local/bin/VoiceStudio`.
Current builds include the unified terminal command. Debian packages expose
`voicestudio` through `/usr/bin` and the shell installer through `~/.local/bin`.
A downloaded AppImage links `~/.local/bin/voicestudio` on first launch; choose
**Settings → General → Terminal command → Add to terminal** if your shell does not
already search `~/.local/bin`. Open a new terminal afterwards. `voicestudio` opens
the app, and commands start it in the background when it is not running; no
separate Python installation is needed. Existing custom launchers are not
replaced; see [Terminal command](script.md#terminal-command).
**.deb:**
```bash
+8
View File
@@ -45,6 +45,14 @@ Chip/Processor**) from the
[Releases page](https://github.com/debpalash/VoiceStudio/releases/latest),
double-click to mount it, and drag **VoiceStudio.app** into `/Applications`.
Current builds link the bundled `voicestudio` command into `~/.local/bin` on
the first launch of the installed app (or during shell-script installation). To
add that folder to your shell, choose **Settings → General → Terminal command →
Add to terminal**, then open a new terminal: `voicestudio` opens the app,
`voicestudio --help` shows the CLI, and commands start the app in the background
when it is not running. Python and uv are not required. Existing custom launchers
are preserved; see the [CLI migration instructions](script.md#terminal-command).
| Mac | DMG to download |
|-----|-----------------|
| Apple Silicon (any M-series chip) | `VoiceStudio-<version>-mac-arm64.dmg` |
+125 -2
View File
@@ -64,7 +64,13 @@ On macOS the installer also clears the `com.apple.quarantine` flag and, when
signed ad hoc, #2763), re-signs the bundle ad hoc so Gatekeeper does not report
"damaged". A valid or notarized signature is never touched. On an Intel Mac it
prints that the local backend needs Apple Silicon.
Linux installs `~/.local/bin/VoiceStudio`; include `~/.local/bin` in your PATH.
Linux installs the AppImage as `~/.local/bin/VoiceStudio`. Current builds expose
the package's unified `voicestudio` command through `~/.local/bin` on macOS and
Linux and configure PATH for Bash, Zsh, POSIX and Fish shells.
No separate Python installation is required. An existing custom launcher is
preserved: conflicting ownership stops installation before replacing the app;
see [Terminal command](#terminal-command). A command already
owned by the Python CLI package is retained.
Current Electron source builds also read archived setup configuration for custom
data/model folders and portable storage; explicit launch environment overrides
still win. The backend retains its existing durable Settings precedence. No files
@@ -76,6 +82,119 @@ may not read data created by newer versions; back up important projects first.
For isolated shell-installer testing, `VOICESTUDIO_INSTALL_DIR` selects an
installation directory; it must be an absolute, existing, writable directory. Invalid overrides fail without falling back elsewhere.
## Terminal command
`voicestudio` opens the desktop app. `voicestudio --help` shows the command tree;
`version`, `--version` and `-v` report the installed application's version offline,
from its bundle metadata.
Results print as readable text: lists as tables that fit the terminal, details as
aligned fields and indented sections. Piped to another program, tables become
complete tab-separated rows without a header (`voicestudio voices list | cut -f2`).
Add `--json` for the raw result as machine-readable output on stdout
(errors then go to stderr as JSON with a stable `code`). Exit codes: `0` success,
`1` failure, `2` invalid usage, `3` from `status` when VoiceStudio is not running.
`settings get` with no name shows every setting.
Tab completion covers commands, options and fixed values. Enable it once in your
shell's startup file:
| Shell | Add this line to |
|---|---|
| bash | `eval "$(voicestudio completion bash)"` in `~/.bashrc` |
| zsh | `eval "$(voicestudio completion zsh)"` in `~/.zshrc` |
| fish | `voicestudio completion fish \| source` in `~/.config/fish/config.fish` |
| PowerShell | `voicestudio completion powershell \| Out-String \| Invoke-Expression` in `$PROFILE` |
Some commands were renamed for consistency; the former names still work but are
no longer listed: `voices inspect` → `voices show-file`, `voices reference get` →
`voices reference download`, `dub transcript get` → `dub transcript show`,
`dub history-delete` → `dub history delete`, `settings hf-token status` →
`settings hf-token show`, `models install-status` / `install-cancel` → `models progress` /
`models cancel`, `engines install-status` → `engines progress`, `gallery save-voice` →
`gallery use`, `update check` → `update`, `update info` →
`version --verbose`. Audiobooks and stories now share `audiobook`: `audiobook jobs` →
`audiobook resumable`, `jobs longform list` / `delete` → `audiobook finished` /
`audiobook delete`, `stories render` → `audiobook render-story`, `stories resume` →
`audiobook resume`, and `stories encode` → `audio encode`.
Commands print readable text. Add `--json` for scripts: results go to stdout as
JSON and errors to stderr as `{"error": {"code": …, "message": …}}`, with stable
codes. `voicestudio status` exits 0 when VoiceStudio is running and 3 when it is
not (with `{"running": false}` under `--json`); usage errors exit 2 and other
failures 1. `voicestudio settings get` with no name shows every setting.
Every other command talks to the app's backend over HTTP. If VoiceStudio is not
running, a command that creates or changes something (`speak`, `voices list`,
`dub`, `settings set`, …) starts the app **in the background, without a window**,
waits for its backend and then runs; the first such command prints
`Starting VoiceStudio in the background…` on stderr. The app starts its backend
exactly as it does when you open it, so engines, settings and the port are the
same. While it runs in the background it shows its tray (menu bar) icon.
- Opening VoiceStudio from the menu, dock, tray or `voicestudio` shows a window in
that same app; nothing restarts. Closing the window returns it to the background.
- After 10 minutes with no window, no requests and no running work (dubs, batches,
downloads, installs, calls), the background app quits. Set
`VOICESTUDIO_IDLE_SHUTDOWN_S` to change the period.
- `voicestudio stop` quits it now. It never closes a window you have open, and it
does not stop a backend started some other way (a source checkout or Docker).
- `status`, connectivity tests and questions about live state (loaded models,
running jobs, sharing, calls) report that VoiceStudio is stopped instead of
starting it.
- If setup is not finished or the backend cannot start, the command says so and
asks you to open VoiceStudio, instead of waiting.
The app publishes its backend address in `backend.json` in its user-data folder,
so commands also find it on a fallback port. An explicit `--url`, `VOICESTUDIO_URL`
or saved connection URL selects an externally managed endpoint instead: those
commands never start the app. Credentials remain bound to their origin. When the
app itself is connected to a remote backend, commands ask you to select it with
`voicestudio connection set`.
Commands never install Python packages or models implicitly. `VOICESTUDIO_USER_DATA`
selects an Electron user-data directory and is passed to the app it starts;
`VOICESTUDIO_DESKTOP_APP` selects a nonstandard desktop location. On Linux,
starting the app in the background needs a graphical session; over SSH or on a
server, run a backend yourself and pass `--url`.
On macOS and Linux direct downloads, the app links `~/.local/bin/voicestudio` when
it starts. It changes your shell profiles only when you choose
**Settings → General → Terminal command → Add to terminal**, or when you use the
shell installer. Windows installers add the command to PATH themselves.
For older AppImages, the first metadata read extracts the application's manifest.
Subsequent reads use a local cache tied to the image's file identity, size and
timestamps; changing or replacing the image invalidates it.
To add the terminal command to an existing desktop installation from a checkout,
using Python 3.11+ and uv:
```bash
PYTHONPATH=cli python3 -m voicestudio_cli.install ./cli
```
In PowerShell:
```powershell
$env:PYTHONPATH = 'cli'
python -m voicestudio_cli.install ./cli
```
If the command already exists, installation stops. `--replace-launcher` explicitly
backs up a shell launcher or records a symlink target for desktop dispatch;
installation failure restores the previous command. Native executables are not
replaced. `--no-modify-path` disables shell configuration changes.
`version --verbose` reports how the app is installed and how it updates, offline.
`update` opens VoiceStudio at **Settings → Updates**, where the app's own updater
checks GitHub Releases on its saved channel and downloads, verifies and installs
an update, the same as from the app. The terminal command itself never contacts
the internet; choose the update channel in **Settings →
Updates**. Store-managed installations remain owned by their store and
source installations require rebuilding. Installing the terminal command with uv
or pip does not make either tool responsible for updating the application.
## Uninstall
Quit VoiceStudio, then run:
@@ -86,6 +205,9 @@ curl -fsSL https://voicestudio.sh/install | sh -s -- --uninstall
On macOS this removes the Electron app from `/Applications` and `~/Applications`;
on Linux it removes the script-installed `~/.local/bin/VoiceStudio` AppImage.
It also removes its own command symlink, leaving independently installed CLI
packages and custom launchers alone. Shared PATH entries remain available to
other tools.
`VOICESTUDIO_INSTALL_DIR` restricts removal to a custom installation directory.
On macOS the app is unregistered and moved into a uniquely named folder in Trash;
it is never kept as a hidden application under `/Applications`, where Launchpad
@@ -108,7 +230,8 @@ does not guess custom storage locations or delete shared model caches.
## Building main
Install Git, Node.js 22 or newer, Bun (the version pinned in root
`package.json`), and stable Rust/Cargo before running `--main`.
`package.json`), stable Rust/Cargo, and uv before running `--main`. Packaging
uses uv to build the bundled CLI with a pinned PyInstaller tool and Python 3.11.
On macOS, install Xcode Command Line Tools (`xcode-select --install`); use a
native arm64 terminal on Apple Silicon. On Debian/Ubuntu, install the native
dependencies used by the Electron build:
+7
View File
@@ -44,6 +44,13 @@ The setup wizard installs for the current user by default (no administrator
rights needed) and lets you choose the installation folder. Compare the download with the
release's `SHA256SUMS.txt` before running it.
Current installers add the bundled CLI's directory to PATH for their installation
scope and remove that entry on uninstall. Open a new terminal afterwards:
`voicestudio` opens the desktop app; `voicestudio --help` shows terminal commands.
The CLI includes its own Python runtime and works before backend setup. Commands
that need the backend start VoiceStudio in the background when it is not running.
See [Terminal command](script.md#terminal-command).
During an update, the installer closes processes running inside the selected
installation folder. Processes in similarly named sibling folders and the
installer itself are excluded. If an older installer leaves a running copy
+137
View File
@@ -0,0 +1,137 @@
// Build the public command from the Python package; users need no system Python.
import { execFileSync } from 'node:child_process';
import {
chmodSync,
cpSync,
mkdtempSync,
readdirSync,
readFileSync,
renameSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Arch } from 'builder-util';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
export const CLI_BUILD_REQUIREMENT = 'pyinstaller==6.22.3';
export function cliBuildArguments(work, platform = process.platform) {
// Match the backend's supported x64 interpreter on Windows ARM too.
const python = platform === 'win32' ? 'cpython-3.11-windows-x86_64-none' : '3.11';
return [
'tool',
'run',
'--python',
python,
'--from',
CLI_BUILD_REQUIREMENT,
'--with',
join(root, 'cli'),
'python',
join(root, 'scripts/freeze_cli.py'),
'--noconfirm',
'--clean',
'--onedir',
'--console',
'--name',
'voicestudio',
'--collect-data',
'voicestudio_cli',
'--copy-metadata',
'voicestudio-cli',
'--distpath',
join(work, 'dist'),
'--workpath',
join(work, 'work'),
'--specpath',
work,
join(root, 'cli/frozen_main.py'),
];
}
export function wirePackagedCli(context, bundle) {
const platform = context.electronPlatformName;
const resources = context.packager.getResourcesDir(context.appOutDir);
const destination = join(resources, 'cli');
cpSync(bundle, destination, { recursive: true });
let desktop;
if (platform === 'linux') {
desktop = join(context.appOutDir, 'voicestudio-desktop');
const publicEntry = join(context.appOutDir, context.packager.executableName);
renameSync(publicEntry, desktop);
writeFileSync(
publicEntry,
'#!/bin/sh\nexec "$(dirname "$(readlink -f "$0")")/resources/cli/voicestudio" "$@"\n',
);
chmodSync(publicEntry, 0o755);
} else if (platform === 'darwin') {
desktop = join(
context.appOutDir,
`${context.packager.appInfo.productFilename}.app`,
'Contents/MacOS',
context.packager.appInfo.productFilename,
);
} else {
desktop = join(context.appOutDir, `${context.packager.appInfo.productFilename}.exe`);
cpSync(join(root, 'electron/packaging/cli-path.ps1'), join(destination, 'path.ps1'));
}
writeFileSync(
join(destination, 'desktop.json'),
JSON.stringify(
{
executable: relative(destination, desktop),
version: context.packager.appInfo.version,
application: relative(
destination,
platform === 'darwin'
? join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`)
: desktop,
),
method: platform === 'darwin' ? 'dmg' : platform === 'win32' ? 'nsis' : 'directory',
arch: Arch[context.arch] ?? process.arch,
distribution: context.packager.config?.extraMetadata?.voicestudioDistribution ?? 'direct',
},
null,
2,
) + '\n',
);
return join(destination, `voicestudio${platform === 'win32' ? '.exe' : ''}`);
}
export async function packageCli(context) {
if (
context.electronPlatformName !== process.platform ||
(Arch[context.arch] !== process.arch && process.platform !== 'win32')
) {
throw new Error('Build the CLI on a runner matching the desktop target OS and architecture.');
}
const work = mkdtempSync(join(tmpdir(), 'voicestudio-cli-build-'));
try {
execFileSync(process.env.VOICESTUDIO_BUILD_UV || 'uv', cliBuildArguments(work), {
cwd: root,
stdio: 'inherit',
windowsHide: true,
});
const command = wirePackagedCli(context, join(work, 'dist/voicestudio'));
if (context.electronPlatformName === 'win32') {
const signFiles = async (directory) => {
for (const item of readdirSync(directory, { withFileTypes: true })) {
const file = join(directory, item.name);
if (item.isDirectory()) await signFiles(file);
else if (/\.(exe|dll|pyd)$/i.test(item.name)) await context.packager.signIf(file);
}
};
await signFiles(dirname(command));
}
const version = JSON.parse(execFileSync(command, ['version', '--json'], { encoding: 'utf8' }));
const expected = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version;
if (version.version !== expected)
throw new Error('Bundled command reports a different application version.');
execFileSync(command, ['--help'], { stdio: 'pipe' });
} finally {
rmSync(work, { recursive: true, force: true });
}
}
+6 -3
View File
@@ -8,6 +8,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { packageNativeHelper } from './native-helper-build.mjs';
import { packageCli } from './cli-bundle.mjs';
import { finalizeOmnivoiceTts, omnivoiceTtsResources, signMac } from './omnivoice-tts-bundle.mjs';
import { repairSnapArtifacts } from './snap-template-payload.mjs';
import { signMasRuntime } from './mas-runtime-bundle.mjs';
@@ -90,6 +91,7 @@ export function distributionPackaging(target = DISTRIBUTION_TARGET) {
}
return {
linuxTargets: ['AppImage', 'deb'],
linuxExecutableName: 'voicestudio',
publish: {
provider: 'generic',
url: updateUrl,
@@ -211,6 +213,7 @@ export default {
],
asar: true,
afterPack: async (context) => {
await packageCli(context);
await packageNativeHelper(context);
finalizeOmnivoiceTts(context);
},
@@ -226,6 +229,7 @@ export default {
target: ['nsis'],
},
nsis: {
include: 'packaging/cli-installer.nsh',
oneClick: false,
allowToChangeInstallationDirectory: true,
perMachine: false,
@@ -242,9 +246,7 @@ export default {
// before the bundle seal (electron/omnivoice-tts-bundle.mjs).
...(isMacAppStore
? { sign: signMasRuntime }
: bundledOmnivoiceTtsResources.length
? { sign: signMac }
: {}),
: { sign: signMac }),
notarize: notarizeMac,
extendInfo: {
NSMicrophoneUsageDescription: readFileSync(resolve(here, 'build/Info.plist'), 'utf8')
@@ -271,6 +273,7 @@ export default {
...(packaging.linuxExecutableName ? { executableName: packaging.linuxExecutableName } : {}),
category: 'Audio',
},
deb: { appArmorProfile: 'packaging/cli-apparmor-profile.tpl' },
...(packaging.snapcraft ? { snapcraft: packaging.snapcraft } : {}),
publish: packaging.publish,
};
+9
View File
@@ -170,6 +170,15 @@ export function codesignArgs(opts, file) {
* manifest the bundle seal now covers).
*/
export async function signMac(opts, packager) {
const cliDir = join(opts.app, 'Contents', 'Resources', 'cli');
const cliFiles = (dir) => !existsSync(dir) ? [] : readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name);
return entry.isDirectory() ? cliFiles(path) : entry.isFile() && isMachO(path) ? [path] : [];
});
// PyInstaller's interpreter and extension modules need the app's signing identity too.
if (opts.identity) {
for (const file of cliFiles(cliDir)) execFileSync('codesign', codesignArgs(opts, file), { stdio: 'inherit' });
}
const binDir = join(opts.app, 'Contents', 'Resources', OMNIVOICE_TTS_RESOURCE_DIR);
let ignore = opts.ignore;
if (opts.identity && existsSync(join(binDir, OMNIVOICE_TTS_MANIFEST))) {
@@ -0,0 +1,8 @@
abi <abi/4.0>,
include <tunables/global>
# The public command launches this private Electron executable.
profile "${executable}" "/opt/${sanitizedProductName}/voicestudio-desktop" flags=(unconfined) {
userns,
include if exists <local/${executable}>
}
+20
View File
@@ -0,0 +1,20 @@
!macro customInstall
StrCpy $0 "User"
${If} $installMode == "all"
StrCpy $0 "Machine"
${EndIf}
nsExec::ExecToLog '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$INSTDIR\resources\cli\path.ps1" -Action Install -Scope $0'
Pop $0
${If} $0 != 0
MessageBox MB_OK|MB_ICONEXCLAMATION "VoiceStudio was installed, but its terminal command could not be added to PATH. Add $INSTDIR\resources\cli to PATH manually."
${EndIf}
!macroend
!macro customUnInstall
StrCpy $0 "User"
${If} $installMode == "all"
StrCpy $0 "Machine"
${EndIf}
nsExec::ExecToLog '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$INSTDIR\resources\cli\path.ps1" -Action Uninstall -Scope $0'
Pop $0
!macroend
+22
View File
@@ -0,0 +1,22 @@
# Called by NSIS; add/remove only the command directory owned by this installation.
param([ValidateSet('Install', 'Uninstall')][string]$Action,
[ValidateSet('User', 'Machine')][string]$Scope = 'User')
$ErrorActionPreference = 'Stop'
$commandDir = [IO.Path]::GetFullPath($PSScriptRoot)
$current = [Environment]::GetEnvironmentVariable('Path', $Scope)
$entries = @($current -split ';' | Where-Object { $_ -and $_.TrimEnd('\') -ine $commandDir.TrimEnd('\') })
if ($Action -eq 'Install') { $entries = @($commandDir) + $entries }
[Environment]::SetEnvironmentVariable('Path', ($entries -join ';'), $Scope)
# Notify Explorer so newly opened terminals inherit the updated PATH.
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class VoiceStudioEnvironment {
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr SendMessageTimeout(IntPtr window, uint message,
UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);
}
'@
$result = [UIntPtr]::Zero
[void][VoiceStudioEnvironment]::SendMessageTimeout([IntPtr]0xffff, 0x1a,
[UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
+32
View File
@@ -139,6 +139,38 @@ it('reports a resumable runtime when startup finds an interrupted install marker
await supervisor.shutdown();
});
it('waits for a terminal-owned backend during startup without spawning or staging', async () => {
vi.useFakeTimers();
vi.stubEnv('VOICESTUDIO_SKIP_BACKEND', '');
let ready = false;
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(JSON.stringify({ status: ready ? 'ok' : 'starting', version: 'test' }), {
status: ready ? 200 : 503,
headers: { 'x-omnivoice-backend': 'test' },
}),
),
);
const supervisor = new BackendSupervisor();
try {
await supervisor.start();
expect(supervisor.status.stage).toBe('attaching');
expect(mocks.spawn).not.toHaveBeenCalled();
expect(mocks.stage).not.toHaveBeenCalled();
ready = true;
await vi.advanceTimersByTimeAsync(1000);
expect(supervisor.status.stage).toBe('ready');
expect(supervisor.status.managed).toBe(false);
await supervisor.shutdown();
expect(mocks.spawn).not.toHaveBeenCalled();
} finally {
await supervisor.shutdown();
vi.useRealTimers();
}
});
it('publishes packaged startup preflight failures instead of rejecting startup', async () => {
vi.stubGlobal(
'fetch',
+9
View File
@@ -1052,6 +1052,15 @@ export class BackendSupervisor extends EventEmitter<{
return;
}
// A terminal or another shell can own a backend whose early-bind
// health endpoint is still starting. Wait for that owner instead of
// staging its sources or launching a competing process.
if (await this.probe(this.baseUrl, true)) {
if (gen !== this.generation) return;
void this.waitUntilReady(gen, startupBudgetMs());
return;
}
// A previous fallback is only useful while its backend still answers.
// Once it is gone, retry the configured endpoint before spawning anew.
if (this.localPort !== this.configuredPort) {
+168
View File
@@ -0,0 +1,168 @@
// @vitest-environment node
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, test, vi } from 'vitest';
import type { BackendStage } from '../preload/index.d';
import {
clearDiscovery,
DEFAULT_IDLE_SHUTDOWN_S,
DISCOVERY_FILE,
IdleShutdown,
idleShutdownMs,
parseLaunchIntent,
relaunchArguments,
writeDiscovery,
type BackendActivity,
} from './headless';
const MINUTE = 60_000;
function harness(initial: { stage?: BackendStage; activity?: BackendActivity | null } = {}) {
let now = 0;
const state = {
window: false,
stage: initial.stage ?? ('ready' as BackendStage),
activity:
initial.activity === undefined
? ({ inflight: 0, busy: [], idle_seconds: 0 } as BackendActivity | null)
: initial.activity,
};
const onIdle = vi.fn();
const idle = new IdleShutdown({
idleMs: 10 * MINUTE,
hasWindow: () => state.window,
stage: () => state.stage,
readActivity: async () => state.activity,
onIdle,
now: () => now,
});
const advance = (ms: number) => {
now += ms;
if (state.activity) state.activity.idle_seconds += ms / 1000;
};
return { idle, state, onIdle, advance };
}
test('stops a quiet headless app after the idle period, once', async () => {
const { idle, onIdle, advance } = harness();
advance(9 * MINUTE);
expect(await idle.tick()).toBe(false);
advance(MINUTE);
expect(await idle.tick()).toBe(true);
expect(await idle.tick()).toBe(true);
expect(onIdle).toHaveBeenCalledTimes(1);
});
test('an open window keeps the app and restarts the idle period when it closes', async () => {
const { idle, state, onIdle, advance } = harness();
state.window = true;
advance(30 * MINUTE);
expect(await idle.tick()).toBe(false);
state.window = false;
advance(9 * MINUTE);
expect(await idle.tick()).toBe(false);
advance(MINUTE);
expect(await idle.tick()).toBe(true);
expect(onIdle).toHaveBeenCalledOnce();
});
test('running work and open requests are never idle, however long they take', async () => {
const { idle, state, onIdle, advance } = harness();
state.activity = { inflight: 0, busy: ['jobs'], idle_seconds: 0 };
for (let i = 0; i < 12; i++) {
advance(10 * MINUTE);
state.activity.idle_seconds = 0;
expect(await idle.tick()).toBe(false);
}
state.activity = { inflight: 1, busy: [], idle_seconds: 0 };
advance(20 * MINUTE);
expect(await idle.tick()).toBe(false);
expect(onIdle).not.toHaveBeenCalled();
});
test('the backend clock wins when a terminal request arrived recently', async () => {
const { idle, state, advance } = harness();
advance(15 * MINUTE);
state.activity = { inflight: 0, busy: [], idle_seconds: 60 };
expect(await idle.tick()).toBe(false);
});
test('unknown activity on a live backend, and any startup, keep the app alive', async () => {
const unknown = harness({ activity: null });
unknown.advance(60 * MINUTE);
expect(await unknown.idle.tick()).toBe(false);
unknown.state.stage = 'unresponsive';
unknown.advance(60 * MINUTE);
expect(await unknown.idle.tick()).toBe(false);
for (const stage of ['attaching', 'starting', 'installing'] as const) {
const starting = harness({ stage, activity: null });
starting.advance(60 * MINUTE);
expect(await starting.idle.tick()).toBe(false);
}
});
test('a failed backend is judged by the clock, so a broken start does not linger', async () => {
const { idle, onIdle, advance } = harness({ stage: 'failed', activity: null });
advance(10 * MINUTE);
expect(await idle.tick()).toBe(true);
expect(onIdle).toHaveBeenCalledOnce();
});
test('the idle period is configurable and rejects nonsense', () => {
expect(idleShutdownMs('30')).toBe(30_000);
for (const raw of [undefined, '', '0', '-5', 'soon'])
expect(idleShutdownMs(raw)).toBe(DEFAULT_IDLE_SHUTDOWN_S * 1000);
});
test('launch intent survives a relaunch without Chromium switches', () => {
const argv = [
'/opt/VoiceStudio/voicestudio-desktop',
'--voicestudio-background',
'--original-process-start-time=1',
];
const intent = parseLaunchIntent(argv);
expect(intent).toEqual({ headless: true, stop: false, checkUpdates: false });
expect(relaunchArguments(intent)).toEqual(['--voicestudio-background']);
expect(relaunchArguments(parseLaunchIntent(['x', '--voicestudio-check-updates']))).toEqual([
'--voicestudio-check-updates',
]);
expect(relaunchArguments(parseLaunchIntent(['x']))).toEqual([]);
expect(
relaunchArguments(parseLaunchIntent(['x', '--voicestudio-stop', '--voicestudio-background'])),
).toEqual([]);
});
const directories: string[] = [];
afterEach(() => {
for (const directory of directories.splice(0))
rmSync(directory, { recursive: true, force: true });
});
test('discovery is replaced atomically and cleared only by its owner', () => {
const directory = mkdtempSync(join(tmpdir(), 'vs-discovery-'));
directories.push(directory);
const record = {
schema: 1 as const,
stage: 'ready' as const,
url: 'http://127.0.0.1:4900',
pid: 100,
version: '1.0.0',
headless: true,
window: false,
remote: false,
};
writeDiscovery(directory, record);
writeDiscovery(directory, { ...record, window: true });
expect(JSON.parse(readFileSync(join(directory, DISCOVERY_FILE), 'utf8'))).toEqual({
...record,
window: true,
});
clearDiscovery(directory, 200);
expect(JSON.parse(readFileSync(join(directory, DISCOVERY_FILE), 'utf8')).pid).toBe(100);
clearDiscovery(directory, 100);
expect(() => readFileSync(join(directory, DISCOVERY_FILE))).toThrow();
writeFileSync(join(directory, DISCOVERY_FILE), 'not json');
clearDiscovery(directory, 100);
expect(readFileSync(join(directory, DISCOVERY_FILE), 'utf8')).toBe('not json');
});
+165
View File
@@ -0,0 +1,165 @@
/**
* Headless desktop ownership for terminal commands.
*
* The terminal command never launches the Python backend itself: it starts
* this app without a window (`--voicestudio-background`; Chromium owns `--headless`), so the same BackendSupervisor,
* environment and port selection serve both the CLI and the GUI. A later GUI
* launch reaches the running instance through Electron's single-instance lock
* and only opens a window in it.
*/
import { renameSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { BackendStage } from '../preload/index.d';
export const HEADLESS_FLAG = '--voicestudio-background';
export const STOP_FLAG = '--voicestudio-stop';
export const CHECK_UPDATES_FLAG = '--voicestudio-check-updates';
export type LaunchIntent = { headless: boolean; stop: boolean; checkUpdates: boolean };
export function parseLaunchIntent(argv: readonly string[]): LaunchIntent {
return {
headless: argv.includes(HEADLESS_FLAG),
stop: argv.includes(STOP_FLAG),
checkUpdates: argv.includes(CHECK_UPDATES_FLAG),
};
}
/**
* Arguments for relaunching after a shutdown raced a new launch. Only intent
* flags survive: Chromium adds its own switches to a second instance's argv,
* and a Linux relaunch passes through the public command's argument parser.
*/
export function relaunchArguments(intent: LaunchIntent): string[] {
if (intent.stop) return [];
return [
...(intent.headless ? [HEADLESS_FLAG] : []),
...(intent.checkUpdates ? [CHECK_UPDATES_FLAG] : []),
];
}
export type BackendActivity = { inflight: number; busy: string[]; idle_seconds: number };
/** Stages where the backend is (re)starting or installing: never idle. */
const STARTING: ReadonlySet<BackendStage> = new Set(['attaching', 'starting', 'installing']);
export const DEFAULT_IDLE_SHUTDOWN_S = 600;
export function idleShutdownMs(raw = process.env.VOICESTUDIO_IDLE_SHUTDOWN_S): number {
const seconds = Number(raw);
return (Number.isFinite(seconds) && seconds > 0 ? seconds : DEFAULT_IDLE_SHUTDOWN_S) * 1000;
}
export type IdleShutdownOptions = {
idleMs: number;
pollMs?: number;
hasWindow: () => boolean;
stage: () => BackendStage;
/** `null` when the activity endpoint could not be read. */
readActivity: () => Promise<BackendActivity | null>;
onIdle: () => void;
now?: () => number;
};
/**
* Stops a terminal-started app once nothing has used it for `idleMs`.
*
* Conservative by design: an open window, a starting backend, open requests,
* running jobs, or a ready backend whose activity cannot be read all keep it
* alive. Only a backend that is gone or failed is judged by the clock alone.
*/
export class IdleShutdown {
private readonly now: () => number;
private lastUse: number;
private timer: ReturnType<typeof setInterval> | null = null;
private fired = false;
constructor(private readonly options: IdleShutdownOptions) {
this.now = options.now ?? Date.now;
this.lastUse = this.now();
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.tick(), this.options.pollMs ?? 15_000);
this.timer.unref?.();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
/** A new terminal request or a window counts as use. */
touch(): void {
this.lastUse = this.now();
}
async tick(): Promise<boolean> {
if (this.fired) return true;
const { hasWindow, stage, readActivity, idleMs } = this.options;
if (hasWindow() || STARTING.has(stage())) {
this.touch();
return false;
}
const activity = await readActivity();
if (hasWindow()) {
this.touch();
return false;
}
let idleFor = this.now() - this.lastUse;
if (activity) {
if (activity.inflight > 0 || activity.busy.length > 0) {
this.touch();
return false;
}
idleFor = Math.min(idleFor, activity.idle_seconds * 1000);
} else if (stage() === 'ready' || stage() === 'unresponsive') {
// A long job can block the event loop; unknown is never idle.
this.touch();
return false;
}
if (idleFor < idleMs) return false;
this.fired = true;
this.stop();
this.options.onIdle();
return true;
}
}
export const DISCOVERY_FILE = 'backend.json';
export type DiscoveryRecord = {
schema: 1;
/** Lets a waiting terminal command fail fast on setup or startup errors. */
stage: BackendStage;
url: string;
pid: number;
version: string;
/** Started for a terminal command; closing its window returns to headless. */
headless: boolean;
/** A window is open, so `voicestudio stop` must leave the app to its user. */
window: boolean;
/** The app uses a remote backend; the CLI must not send it unauthenticated requests. */
remote: boolean;
};
/** Publish where this app's local backend listens; the CLI reads it. */
export function writeDiscovery(directory: string, record: DiscoveryRecord): void {
const target = join(directory, DISCOVERY_FILE);
const temporary = `${target}.${record.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(record) + '\n', { mode: 0o600 });
renameSync(temporary, target);
}
/** Remove the record only while it is still this process's. */
export function clearDiscovery(directory: string, pid: number): void {
const target = join(directory, DISCOVERY_FILE);
try {
const current = JSON.parse(readFileSync(target, 'utf8')) as Partial<DiscoveryRecord>;
if (current.pid !== pid) return;
} catch {
return;
}
rmSync(target, { force: true });
}
+193 -13
View File
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
import { app, BrowserWindow, ipcMain, Menu, nativeImage, session, shell, Tray } from 'electron';
import { electronApp, is, optimizer } from '@electron-toolkit/utils';
import { BackendSupervisor, backendRoot } from './backend';
import { registerIpc, wireWindowMaximizeEvents } from './ipc';
import { assertTrustedMainFrame, registerIpc, wireWindowMaximizeEvents } from './ipc';
import { APP_ORIGIN, installAppProtocol, registerAppScheme } from './protocol';
import { electronProxyPort, startDevBackendProxy } from './dev-backend-proxy';
import { DesktopUpdater, registerUpdateIpc } from './updater';
@@ -22,11 +22,28 @@ import {
MainErrorJournal,
observeMainProcessTask,
} from './main-error-journal';
import { activateLiveWindow, isLiveWindow } from './window-safety';
import { activateLiveWindow, isLiveWindow, sendToLiveWindow } from './window-safety';
import { startAccount } from './account';
import { installAppIdentity, installMacApplicationMenu } from './app-identity';
import { APP_ID, PRODUCT_NAME } from '../../../config/app-config.mjs';
import { restoreSecurityScopedDirectories } from './security-scoped-files';
import { homedir } from 'node:os';
import {
addTerminalCommandToPath,
linkTerminalCommand,
terminalCommandStatus,
type TerminalCommandOptions,
} from './terminal-command';
import {
clearDiscovery,
IdleShutdown,
idleShutdownMs,
parseLaunchIntent,
relaunchArguments,
writeDiscovery,
type BackendActivity,
type LaunchIntent,
} from './headless';
// Packaged GUI launches can inherit a short-lived terminal pipe. When that
// launcher exits, diagnostic console writes emit EPIPE asynchronously and can
@@ -65,6 +82,16 @@ let closeAccount: (() => void) | null = null;
let closeDirectoryScopes: (() => void) | null = null;
let quitPreparation: Promise<void> | null = null;
// A terminal command starts the app without a window (`--voicestudio-background`); the
// window then opens on demand in this same process (see ./headless.ts).
const launchIntent = parseLaunchIntent(process.argv);
const headlessOwner = launchIntent.headless && !launchIntent.checkUpdates;
let idleShutdown: IdleShutdown | null = null;
let relaunchIntent: LaunchIntent | null = null;
let checkForUpdates: (() => void) | null = null;
let publishedDiscovery = '';
const DISCOVERY_DIR = app.getPath('userData');
const PERSISTENCE_FLUSH_REQUEST = 'app:flush-persistence';
const PERSISTENCE_FLUSHED = 'app:persistence-flushed';
@@ -94,7 +121,70 @@ async function flushRendererPersistence(): Promise<void> {
});
}
/** Tell terminal commands where this app's backend listens. */
function publishDiscovery(): void {
const backend = supervisor;
if (!backend || quitPreparation) return;
const record = {
schema: 1 as const,
stage: backend.status.stage,
url: backend.baseUrl,
pid: process.pid,
version: __APP_VERSION__,
headless: headlessOwner,
window: isLiveWindow(mainWindow),
remote: backend.connection.remote,
};
const serialized = JSON.stringify(record);
if (serialized === publishedDiscovery) return;
try {
writeDiscovery(DISCOVERY_DIR, record);
publishedDiscovery = serialized;
} catch (error) {
console.warn('[headless] Could not publish the backend address:', error);
}
}
async function readBackendActivity(backend: BackendSupervisor): Promise<BackendActivity | null> {
// A remote backend is not ours to keep alive; only the clock decides.
if (backend.connection.remote) return { inflight: 0, busy: [], idle_seconds: Infinity };
try {
const response = await fetch(`${backend.baseUrl}/system/activity`, {
headers: backend.requestHeaders(),
signal: AbortSignal.timeout(5000),
});
if (!response.ok) return null;
const body = (await response.json()) as Partial<BackendActivity>;
return typeof body.inflight === 'number' &&
Array.isArray(body.busy) &&
typeof body.idle_seconds === 'number'
? (body as BackendActivity)
: null;
} catch {
return null;
}
}
function terminalCommandOptions(): TerminalCommandOptions {
return {
platform: process.platform,
home: homedir(),
resources: process.resourcesPath,
appImage: process.env.APPIMAGE,
snap: process.env.SNAP,
path: process.env.PATH,
};
}
async function tearDownNativeResources(): Promise<void> {
idleShutdown?.stop();
idleShutdown = null;
publishedDiscovery = '';
try {
clearDiscovery(DISCOVERY_DIR, process.pid);
} catch {
/* a stale record is harmless: terminal commands verify the backend */
}
closeWatch?.();
closeWatch = null;
closeCapture?.();
@@ -122,6 +212,12 @@ function beginOrderlyQuit(flushPersistence = true): Promise<void> {
const timeout = new Promise<void>((resolve) => setTimeout(resolve, 5000));
await Promise.race([teardown, timeout]);
quitting = true;
if (relaunchIntent) {
// A launch arrived while this instance was stopping: start it afresh.
// An AppImage's mount disappears with this process, so relaunch the image.
const args = relaunchArguments(relaunchIntent);
app.relaunch(process.env.APPIMAGE ? { execPath: process.env.APPIMAGE, args } : { args });
}
app.quit();
})();
return quitPreparation;
@@ -133,6 +229,15 @@ function brandIconPath(file: string): string {
: join(backendRoot(), 'electron', 'build', 'icons', file);
}
ipcMain.handle('terminal:status', (event) => {
assertTrustedMainFrame(event, mainWindow);
return terminalCommandStatus(terminalCommandOptions());
});
ipcMain.handle('terminal:add-to-path', (event) => {
assertTrustedMainFrame(event, mainWindow);
return addTerminalCommandToPath(terminalCommandOptions());
});
ipcMain.handle(
'app:is-fullscreen',
(event) => BrowserWindow.fromWebContents(event.sender)?.isFullScreen() ?? false,
@@ -170,7 +275,8 @@ function createWindow(): BrowserWindow {
win.on('close', (event) => {
if (quitting) return;
event.preventDefault();
if (process.platform === 'darwin') {
// A terminal-started app returns to headless; its idle timer then decides.
if (process.platform === 'darwin' || headlessOwner) {
observeMainProcessTask(
flushRendererPersistence().finally(() => {
if (!win.isDestroyed()) win.destroy();
@@ -184,6 +290,12 @@ function createWindow(): BrowserWindow {
});
win.on('closed', () => {
if (mainWindow === win) mainWindow = null;
if (headlessOwner) {
if (process.platform === 'darwin') app.dock?.hide();
idleShutdown?.touch();
publishDiscovery();
return;
}
if (process.platform !== 'darwin' && !quitting) app.quit();
});
wireWindowMaximizeEvents(win);
@@ -221,6 +333,47 @@ function createWindow(): BrowserWindow {
return win;
}
/** Open (or focus) the window in this process, e.g. for a launch from the menu. */
function showWindow(navigateTo?: string): void {
if (quitPreparation) return;
if (!isLiveWindow(mainWindow)) mainWindow = createWindow();
if (process.platform === 'darwin') void app.dock?.show();
activateLiveWindow(mainWindow);
idleShutdown?.touch();
publishDiscovery();
const win = mainWindow;
if (navigateTo && win) {
const navigate = () => sendToLiveWindow(win, 'app:navigate', navigateTo);
if (win.webContents.isLoading()) win.webContents.once('did-finish-load', navigate);
else navigate();
}
}
/** Act on a later launch of the app, delivered by the single-instance lock. */
function handleLaunch(intent: LaunchIntent): void {
if (quitPreparation) {
if (!intent.stop) relaunchIntent = intent;
return;
}
if (intent.stop) {
// `voicestudio stop` never closes a window the user is working in.
if (!isLiveWindow(mainWindow))
observeMainProcessTask(beginOrderlyQuit(false), mainErrors, 'Terminal stop');
return;
}
if (intent.checkUpdates) {
showWindow('/settings/updates');
checkForUpdates?.();
return;
}
if (intent.headless) {
// Another terminal command: already running, so this only counts as use.
idleShutdown?.touch();
return;
}
showWindow();
}
function isOwnUrl(url: string): boolean {
const dev = process.env.ELECTRON_RENDERER_URL;
return isTrustedRenderer(url, dev);
@@ -243,15 +396,28 @@ async function openOutside(url: string): Promise<void> {
if (process.env.VOICESTUDIO_ALLOW_MULTIPLE_INSTANCES !== '1' && !app.requestSingleInstanceLock()) {
app.quit();
} else if (launchIntent.stop) {
// `--stop` with nothing running: there is nothing to stop or start.
app.exit(0);
} else {
app.on('second-instance', () => {
activateLiveWindow(mainWindow);
let initialized: Promise<void> = Promise.resolve();
app.on('second-instance', (_event, argv) => {
const intent = parseLaunchIntent(argv);
void initialized.then(() => handleLaunch(intent));
});
void app
initialized = app
.whenReady()
.then(async () => {
electronApp.setAppUserModelId(APP_ID);
if (app.isPackaged) {
try {
linkTerminalCommand(terminalCommandOptions());
} catch (error) {
console.warn('[terminal-command] Could not link the terminal command:', error);
}
}
if (headlessOwner && process.platform === 'darwin') app.dock?.hide();
if (process.platform === 'darwin') installMacApplicationMenu(app, Menu, __APP_VERSION__);
installRendererPermissions(session.defaultSession, process.env.ELECTRON_RENDERER_URL);
app.on('browser-window-created', (_event, window) => optimizer.watchWindowShortcuts(window));
@@ -263,6 +429,7 @@ if (process.env.VOICESTUDIO_ALLOW_MULTIPLE_INSTANCES !== '1' && !app.requestSing
backend.subscribe((s) => {
const detail = s.message ? ` — ${s.message}` : '';
console.log(`[supervisor] stage=${s.stage} managed=${s.managed} port=${s.port}${detail}`);
publishDiscovery();
});
installAppProtocol(
() => backend.baseUrl,
@@ -326,12 +493,15 @@ if (process.env.VOICESTUDIO_ALLOW_MULTIPLE_INSTANCES !== '1' && !app.requestSing
() => observeMainProcessTask(updater.check(true), mainErrors, 'Periodic update check'),
6 * 60 * 60 * 1_000,
);
checkForUpdates = () =>
observeMainProcessTask(updater.check(false), mainErrors, 'Terminal update check');
closeUpdates = () => {
clearTimeout(startupUpdateCheck);
clearInterval(periodicUpdateCheck);
closeUpdateIpc();
};
mainWindow = createWindow();
if (!headlessOwner) mainWindow = createWindow();
if (launchIntent.checkUpdates) handleLaunch(launchIntent);
closeWatch = installWatchFolders(
() => mainWindow,
() => backend.baseUrl,
@@ -342,14 +512,24 @@ if (process.env.VOICESTUDIO_ALLOW_MULTIPLE_INSTANCES !== '1' && !app.requestSing
tray = new Tray(createTrayIcon(brandIconPath('32x32.png')));
tray.setToolTip(PRODUCT_NAME);
closeCapture = installNativeCapture(PRELOAD_PATH, tray, () => mainWindow);
tray.on('click', () => {
if (!isLiveWindow(mainWindow)) mainWindow = createWindow();
activateLiveWindow(mainWindow);
});
tray.on('click', () => showWindow());
observeMainProcessTask(backend.start(), mainErrors, 'Backend startup');
if (headlessOwner) {
idleShutdown = new IdleShutdown({
idleMs: idleShutdownMs(),
hasWindow: () => isLiveWindow(mainWindow),
stage: () => backend.status.stage,
readActivity: () => readBackendActivity(backend),
onIdle: () => {
console.log('[headless] No terminal use for the idle period; stopping.');
observeMainProcessTask(beginOrderlyQuit(false), mainErrors, 'Idle shutdown');
},
});
idleShutdown.start();
}
app.on('activate', () => {
if (!isLiveWindow(mainWindow)) mainWindow = createWindow();
if (!isLiveWindow(mainWindow)) showWindow();
});
})
.catch((error) => {
@@ -361,7 +541,7 @@ if (process.env.VOICESTUDIO_ALLOW_MULTIPLE_INSTANCES !== '1' && !app.requestSing
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
if (process.platform !== 'darwin' && !headlessOwner) app.quit();
});
// The first pass gives renderer persistence a bounded chance to settle, then
+119
View File
@@ -0,0 +1,119 @@
// @vitest-environment node
import {
existsSync,
mkdtempSync,
mkdirSync,
writeFileSync,
readFileSync,
readlinkSync,
symlinkSync,
rmSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, test } from 'vitest';
import {
addTerminalCommandToPath,
linkTerminalCommand,
terminalCommandStatus,
} from './terminal-command';
const roots: string[] = [];
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
function fixture() {
const home = mkdtempSync(join(tmpdir(), 'vs-path-'));
roots.push(home);
const resources = join(home, 'VoiceStudio.app/Contents/Resources');
mkdirSync(join(resources, 'cli'), { recursive: true });
writeFileSync(join(resources, 'cli/voicestudio'), 'fixture');
return { home, resources, path: '/usr/bin', platform: 'darwin' as const };
}
test('startup links the bundled CLI without touching shell profiles', () => {
const f = fixture();
writeFileSync(join(f.home, '.zshrc'), '# existing preferences\n');
expect(linkTerminalCommand(f)).toBe('linked');
expect(readlinkSync(join(f.home, '.local/bin/voicestudio'))).toBe(
join(f.resources, 'cli/voicestudio'),
);
expect(readFileSync(join(f.home, '.zshrc'), 'utf8')).toBe('# existing preferences\n');
expect(existsSync(join(f.home, '.profile'))).toBe(false);
expect(terminalCommandStatus(f)).toMatchObject({ supported: true, linked: true, onPath: false });
});
test('adding to PATH is explicit, idempotent and keeps profile content', () => {
const f = fixture();
writeFileSync(join(f.home, '.zshrc'), '# existing preferences\n');
expect(addTerminalCommandToPath(f)).toMatchObject({ linked: true, onPath: true });
addTerminalCommandToPath(f);
const zsh = readFileSync(join(f.home, '.zshrc'), 'utf8');
expect(zsh).toContain('# existing preferences\n');
expect(zsh.match(/# VoiceStudio terminal command/g)).toHaveLength(1);
expect(readFileSync(join(f.home, '.profile'), 'utf8')).toContain('.local/bin');
// Shells the user does not have get no new configuration files.
expect(existsSync(join(f.home, '.bashrc'))).toBe(false);
expect(existsSync(join(f.home, '.config/fish'))).toBe(false);
});
test('macOS gets a zsh profile even when the user has none', () => {
const f = fixture();
addTerminalCommandToPath(f);
expect(readFileSync(join(f.home, '.zshrc'), 'utf8')).toContain('.local/bin');
const linux = fixture();
const appImage = join(linux.home, 'VoiceStudio.AppImage');
writeFileSync(appImage, 'fixture');
mkdirSync(join(linux.home, '.config/fish'), { recursive: true });
addTerminalCommandToPath({ ...linux, platform: 'linux', appImage });
expect(existsSync(join(linux.home, '.zshrc'))).toBe(false);
expect(readFileSync(join(linux.home, '.config/fish/conf.d/voicestudio.fish'), 'utf8')).toContain(
'fish_add_path',
);
});
test('preserves custom wrappers and commands belonging to uv or another installation', () => {
const f = fixture();
mkdirSync(join(f.home, '.local/bin'), { recursive: true });
const command = join(f.home, '.local/bin/voicestudio');
writeFileSync(command, 'existing wrapper');
expect(linkTerminalCommand(f)).toBe('existing');
expect(addTerminalCommandToPath(f).linked).toBe(false);
expect(readFileSync(command, 'utf8')).toBe('existing wrapper');
expect(existsSync(join(f.home, '.profile'))).toBe(false);
rmSync(command);
symlinkSync('/missing/other-installation', command);
expect(linkTerminalCommand(f)).toBe('existing');
expect(readlinkSync(command)).toBe('/missing/other-installation');
});
test('repairs its own link after the AppImage moved, never a live one', () => {
const f = fixture();
const appImage = join(f.home, 'Apps/VoiceStudio-0.5.9-linux-x64.AppImage');
mkdirSync(join(f.home, 'Apps'));
writeFileSync(appImage, 'fixture');
mkdirSync(join(f.home, '.local/bin'), { recursive: true });
const command = join(f.home, '.local/bin/voicestudio');
symlinkSync(join(f.home, 'Downloads/VoiceStudio-0.5.8-linux-x64.AppImage'), command);
expect(linkTerminalCommand({ ...f, platform: 'linux', appImage })).toBe('linked');
expect(readlinkSync(command)).toBe(appImage);
const other = join(f.home, 'Other/VoiceStudio.AppImage');
mkdirSync(join(f.home, 'Other'));
writeFileSync(other, 'fixture');
expect(linkTerminalCommand({ ...f, platform: 'linux', appImage: other })).toBe('existing');
expect(readlinkSync(command)).toBe(appImage);
});
test('AppImage links the persistent image, rather than its temporary mount', () => {
const f = fixture();
const appImage = join(f.home, 'VoiceStudio.AppImage');
writeFileSync(appImage, 'fixture');
expect(linkTerminalCommand({ ...f, platform: 'linux', appImage })).toBe('linked');
expect(readlinkSync(join(f.home, '.local/bin/voicestudio'))).toBe(appImage);
expect(linkTerminalCommand({ ...f, platform: 'linux', snap: '/snap/voicestudio/current' })).toBe(
'unavailable',
);
expect(linkTerminalCommand({ ...f, platform: 'win32' })).toBe('unavailable');
expect(linkTerminalCommand({ ...f, platform: 'linux' })).toBe('unavailable');
expect(terminalCommandStatus({ ...f, platform: 'win32' }).supported).toBe(false);
});
+141
View File
@@ -0,0 +1,141 @@
import {
appendFileSync,
existsSync,
lstatSync,
mkdirSync,
readFileSync,
readlinkSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { basename, join } from 'node:path';
export type TerminalCommandOptions = {
platform: NodeJS.Platform;
home: string;
resources: string;
appImage?: string;
snap?: string;
path?: string;
};
export type TerminalCommandStatus = {
/** This installation can publish `~/.local/bin/voicestudio` itself. */
supported: boolean;
/** The command in `~/.local/bin` runs this installation. */
linked: boolean;
/** New shells find `~/.local/bin`, already or through VoiceStudio's profile lines. */
onPath: boolean;
command: string;
};
const PROFILE_MARKER = '# VoiceStudio terminal command\n';
const PROFILE_LINES =
'\n' +
PROFILE_MARKER +
'case ":$PATH:" in\n *":$HOME/.local/bin:"*) ;;\n' +
' *) export PATH="$HOME/.local/bin:$PATH" ;;\nesac\n';
const PROFILES = ['.profile', '.bashrc', '.zshrc'];
function commandTarget(options: TerminalCommandOptions): string | null {
// Windows installers own PATH; Snap exposes its own command; a translocated
// or mounted app disappears, so a link to it would dangle.
if (
options.platform === 'win32' ||
options.snap ||
options.resources.includes('/AppTranslocation/') ||
options.resources.startsWith('/Volumes/')
)
return null;
const target =
options.platform === 'darwin' ? join(options.resources, 'cli/voicestudio') : options.appImage;
return target && existsSync(target) ? target : null;
}
function commandPath(home: string): string {
return join(home, '.local/bin', 'voicestudio');
}
/** A dangling link left by a moved or replaced VoiceStudio, never someone else's command. */
function isStaleOwnLink(command: string): boolean {
const target = readlinkSync(command);
if (existsSync(target)) return false;
return (
target.endsWith('/Contents/Resources/cli/voicestudio') ||
/^VoiceStudio.*\.AppImage$/i.test(basename(target))
);
}
/**
* DMG/AppImage users get the same command as installer users, without sudo.
* Runs at startup and only manages the link; shell profiles change only on an
* explicit request (`addTerminalCommandToPath`).
*/
export function linkTerminalCommand(
options: TerminalCommandOptions,
): 'linked' | 'existing' | 'unavailable' {
const target = commandTarget(options);
if (!target) return 'unavailable';
const command = commandPath(options.home);
mkdirSync(join(options.home, '.local/bin'), { recursive: true });
try {
const stat = lstatSync(command);
if (stat.isSymbolicLink() && readlinkSync(command) === target) return 'linked';
// Never replace uv's command, a user's launcher or another installation.
if (!stat.isSymbolicLink() || !isStaleOwnLink(command)) return 'existing';
unlinkSync(command);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
symlinkSync(target, command);
return 'linked';
}
export function terminalCommandStatus(options: TerminalCommandOptions): TerminalCommandStatus {
const target = commandTarget(options);
const command = commandPath(options.home);
let linked = false;
try {
linked = Boolean(target) && readlinkSync(command) === target;
} catch {
linked = false;
}
const directory = join(options.home, '.local/bin');
const configured = PROFILES.some((file) => {
try {
return readFileSync(join(options.home, file), 'utf8').includes(PROFILE_MARKER);
} catch {
return false;
}
});
return {
supported: Boolean(target),
linked,
onPath: configured || (options.path ?? '').split(':').includes(directory),
command,
};
}
/** The user's explicit "add to my terminal" action: idempotent profile lines. */
export function addTerminalCommandToPath(options: TerminalCommandOptions): TerminalCommandStatus {
if (linkTerminalCommand(options) !== 'linked') return terminalCommandStatus(options);
for (const file of PROFILES) {
const profile = join(options.home, file);
const exists = existsSync(profile);
// Do not create a profile for a shell the user does not use, except the
// POSIX login profile and, on macOS, zsh's (its default shell skips .profile).
if (!exists && file !== '.profile' && !(options.platform === 'darwin' && file === '.zshrc'))
continue;
if (!exists || !readFileSync(profile, 'utf8').includes(PROFILE_MARKER))
appendFileSync(profile, PROFILE_LINES);
}
const fishDirectory = join(options.home, '.config/fish');
if (existsSync(fishDirectory)) {
mkdirSync(join(fishDirectory, 'conf.d'), { recursive: true });
const fishProfile = join(fishDirectory, 'conf.d/voicestudio.fish');
if (!existsSync(fishProfile))
writeFileSync(fishProfile, 'fish_add_path --path "$HOME/.local/bin"\n');
}
return terminalCommandStatus(options);
}
+13
View File
@@ -6,6 +6,13 @@ import type { HostSnapshotLike } from '../shared/utils/hostSnapshot';
* (src/preload/index.ts) and the renderer. Both tsconfigs include it.
*/
export interface TerminalCommandStatus {
supported: boolean;
linked: boolean;
onPath: boolean;
command: string;
}
export type BackendStage =
| 'setup_required'
| 'installing'
@@ -406,6 +413,12 @@ export interface VoiceStudioBridge {
enqueue(request: WatchUpload): Promise<void>;
stop(token: string): Promise<void>;
};
/** The `voicestudio` terminal command (macOS and Linux direct downloads). */
terminal: {
status(): Promise<TerminalCommandStatus>;
/** Explicit user action: add ~/.local/bin to the user's shell profiles. */
addToPath(): Promise<TerminalCommandStatus>;
};
app: {
/** From the root package.json via __APP_VERSION__ / extraMetadata. */
version: string;
+4
View File
@@ -63,6 +63,10 @@ const bridge: VoiceStudioBridge = {
enqueue: (request) => ipcRenderer.invoke('watch:enqueue', request),
stop: (token) => ipcRenderer.invoke('watch:stop', token),
},
terminal: {
status: () => ipcRenderer.invoke('terminal:status'),
addToPath: () => ipcRenderer.invoke('terminal:add-to-path'),
},
app: {
version: __APP_VERSION__,
platform: process.platform,
@@ -25,6 +25,7 @@ import { setWorkspace, useWorkspace } from '@/lib/store/workspace';
import i18n, { APP_LANGUAGE_ITEMS, APP_LANGUAGES, setAppLanguage, type AppLocale } from '@/i18n';
import { PalettePicker } from './palette-picker';
import { SettingsRow, SettingsSection } from './settings-layout';
import { TerminalCommandSettings } from './terminal-command-settings';
/** Settings → Appearance. */
export function AppearanceSettings() {
@@ -197,6 +198,7 @@ export function GeneralSettings() {
))}
</div>
</SettingsRow>
<TerminalCommandSettings />
</>
</SettingsSection>
);
@@ -0,0 +1,66 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
bridge: null as null | { terminal?: { status: unknown; addToPath: unknown } },
status: vi.fn(),
addToPath: vi.fn(),
success: vi.fn(),
error: vi.fn(),
}));
vi.mock('@/components/bridge', () => ({ getBridge: () => mock.bridge }));
vi.mock('sonner', () => ({ toast: { success: mock.success, error: mock.error } }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
import { TerminalCommandSettings } from './terminal-command-settings';
const command = '/home/user/.local/bin/voicestudio';
const status = (patch: object) => ({
supported: true,
linked: true,
onPath: false,
command,
...patch,
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
function withBridge() {
mock.bridge = { terminal: { status: mock.status, addToPath: mock.addToPath } };
}
it('changes shell profiles only when the user asks', async () => {
withBridge();
mock.status.mockResolvedValue(status({}));
mock.addToPath.mockResolvedValue(status({ onPath: true }));
render(<TerminalCommandSettings />);
const add = await screen.findByRole('button', { name: 'settings.terminal_command' });
expect(mock.addToPath).not.toHaveBeenCalled();
fireEvent.click(add);
await screen.findByText('settings.terminal_command_ready');
expect(mock.addToPath).toHaveBeenCalledOnce();
expect(mock.success).toHaveBeenCalledWith('settings.terminal_command_added');
});
it('explains a command owned by another installation instead of offering to replace it', async () => {
withBridge();
mock.status.mockResolvedValue(status({ linked: false }));
render(<TerminalCommandSettings />);
await screen.findByText('settings.terminal_command_conflict');
expect(screen.getByRole('button', { name: 'settings.terminal_command' })).toBeDisabled();
});
it('is hidden where installers or stores own the command', async () => {
withBridge();
mock.status.mockResolvedValue(status({ supported: false }));
const { container } = render(<TerminalCommandSettings />);
await waitFor(() => expect(mock.status).toHaveBeenCalled());
expect(container).toBeEmptyDOMElement();
mock.bridge = null;
cleanup();
expect(render(<TerminalCommandSettings />).container).toBeEmptyDOMElement();
});
@@ -0,0 +1,80 @@
import { CheckIcon, TerminalIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { getBridge } from '@/components/bridge';
import { describeError } from '@/lib/api/client';
import type { TerminalCommandStatus } from '../../../../preload/index.d';
import { SettingsRow } from './settings-layout';
/**
* Offers the `voicestudio` terminal command to DMG/AppImage users. The app
* links the command at startup but edits shell profiles only on this explicit
* request; Windows installers, packages and Snap own their own PATH setup.
*/
export function TerminalCommandSettings() {
const { t } = useTranslation();
const terminal = getBridge()?.terminal;
const [status, setStatus] = useState<TerminalCommandStatus | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
const bridge = getBridge()?.terminal;
if (!bridge) return;
let live = true;
bridge
.status()
.then((next) => live && setStatus(next))
.catch(() => live && setStatus(null));
return () => {
live = false;
};
}, []);
if (!terminal || !status?.supported) return null;
const add = async () => {
setBusy(true);
try {
const next = await terminal.addToPath();
setStatus(next);
if (next.onPath) toast.success(t('settings.terminal_command_added'));
else toast.error(t('settings.terminal_command_conflict', { path: next.command }));
} catch (error) {
toast.error(describeError(error));
} finally {
setBusy(false);
}
};
return (
<SettingsRow
id="terminal-command-label"
title={t('settings.terminal_command')}
description={
status.linked
? t('settings.terminal_command_desc')
: t('settings.terminal_command_conflict', { path: status.command })
}
>
{status.linked && status.onPath ? (
<span className="inline-flex items-center gap-1.5 text-sm text-muted-foreground">
<CheckIcon className="size-4 text-emerald-500" />
{t('settings.terminal_command_ready')}
</span>
) : (
<Button
size="sm"
variant="outline"
disabled={busy || !status.linked}
aria-labelledby="terminal-command-label"
onClick={() => void add()}
>
<TerminalIcon />
{t('settings.terminal_command_add')}
</Button>
)}
</SettingsRow>
);
}
@@ -1505,6 +1505,12 @@
"remote_backend_confirm_unverified": "لم يجتاز عنوان URL الخلفي هذا اختبار الاتصال. حفظه وإعادة تحميله على أي حال؟ إذا كان الأمر خاطئًا، فلن يتمكن التطبيق من الوصول إلى أي واجهة خلفية حتى تقوم بتغييره مرة أخرى هنا.",
"review_mode": "وضع المراجعة",
"review_mode_desc": "توقف مؤقتًا بين مراحل التدفق حتى تتمكن من مراجعة مخرجات ASR/الترجمة.",
"terminal_command": "أمر الطرفية",
"terminal_command_desc": "شغّل voicestudio في الطرفية لاستخدام ميزات VoiceStudio؛ ومن دون وسائط يفتح التطبيق.",
"terminal_command_add": "إضافة إلى الطرفية",
"terminal_command_ready": "متاح في نوافذ الطرفية الجديدة",
"terminal_command_added": "تمت الإضافة. افتح نافذة طرفية جديدة لاستخدام voicestudio.",
"terminal_command_conflict": "{{path}} يخص تثبيتًا آخر، لذا تركه VoiceStudio دون تغيير.",
"review_mode_on": "مراجعة",
"review_mode_off": "سريع النيران",
"translate_agent": "صالح الوكيل",
@@ -1477,6 +1477,12 @@
"remote_backend_key_placeholder": "API-Schlüssel des anderen Computers",
"review_mode": "Überprüfungsmodus",
"review_mode_desc": "Machen Sie eine Pause zwischen den Pipeline-Stufen, damit Sie die ASR-/Übersetzungsausgabe überprüfen können.",
"terminal_command": "Terminalbefehl",
"terminal_command_desc": "Führe voicestudio im Terminal aus, um VoiceStudio-Funktionen zu nutzen; ohne Argumente öffnet es die App.",
"terminal_command_add": "Zum Terminal hinzufügen",
"terminal_command_ready": "In neuen Terminals verfügbar",
"terminal_command_added": "Hinzugefügt. Öffne ein neues Terminalfenster, um voicestudio zu verwenden.",
"terminal_command_conflict": "{{path}} gehört zu einer anderen Installation, daher hat VoiceStudio es nicht verändert.",
"review_mode_on": "Rezension",
"review_mode_off": "Schnellfeuer",
"translate_agent": "Agententauglich",
@@ -1645,6 +1645,12 @@
"language_desc": "Choose which language the interface uses.",
"review_mode": "Review mode",
"review_mode_desc": "Pause between pipeline stages so you can review ASR / translation output.",
"terminal_command": "Terminal command",
"terminal_command_desc": "Run voicestudio in a terminal to use VoiceStudio's features; with no arguments it opens the app.",
"terminal_command_add": "Add to terminal",
"terminal_command_ready": "Available in new terminals",
"terminal_command_added": "Added. Open a new terminal window to use voicestudio.",
"terminal_command_conflict": "{{path}} belongs to another installation, so VoiceStudio left it unchanged.",
"review_mode_on": "Pause for review",
"review_mode_off": "Run straight through",
"translate_agent": "Agent fit",
@@ -1479,6 +1479,12 @@
"audio_tools_ytdlp_update_failed": "La actualización de yt-dlp falló:{{message}}",
"review_mode": "Modo de revisión",
"review_mode_desc": "Haga una pausa entre las etapas del proceso para que pueda revisar el resultado de ASR/traducción.",
"terminal_command": "Comando de terminal",
"terminal_command_desc": "Ejecuta voicestudio en una terminal para usar las funciones de VoiceStudio; sin argumentos abre la aplicación.",
"terminal_command_add": "Añadir a la terminal",
"terminal_command_ready": "Disponible en terminales nuevas",
"terminal_command_added": "Añadido. Abre una nueva ventana de terminal para usar voicestudio.",
"terminal_command_conflict": "{{path}} pertenece a otra instalación, así que VoiceStudio no lo modificó.",
"review_mode_on": "Revisión",
"review_mode_off": "Fuego rápido",
"translate_agent": "Agente apto",
@@ -1479,6 +1479,12 @@
"remote_backend_key_placeholder": "Clé API définie sur l'autre ordinateur",
"review_mode": "Mode révision",
"review_mode_desc": "Faites une pause entre les étapes du pipeline afin de pouvoir examiner le résultat ASR/traduction.",
"terminal_command": "Commande de terminal",
"terminal_command_desc": "Lancez voicestudio dans un terminal pour utiliser les fonctions de VoiceStudio ; sans argument, il ouvre l'application.",
"terminal_command_add": "Ajouter au terminal",
"terminal_command_ready": "Disponible dans les nouveaux terminaux",
"terminal_command_added": "Ajouté. Ouvrez une nouvelle fenêtre de terminal pour utiliser voicestudio.",
"terminal_command_conflict": "{{path}} appartient à une autre installation : VoiceStudio ne l'a pas modifié.",
"review_mode_on": "Examen",
"review_mode_off": "Tir rapide",
"translate_agent": "Ajustement des agents",
@@ -1645,6 +1645,12 @@
"language_desc": "Escolla o idioma que utiliza a interface.",
"review_mode": "Modo de revisión",
"review_mode_desc": "Fai unha pausa entre as etapas do pipeline para que poidas revisar a saída de ASR/tradución.",
"terminal_command": "Orde de terminal",
"terminal_command_desc": "Executa voicestudio nun terminal para usar as funcións de VoiceStudio; sen argumentos abre a aplicación.",
"terminal_command_add": "Engadir ao terminal",
"terminal_command_ready": "Dispoñible en terminais novos",
"terminal_command_added": "Engadido. Abre unha nova xanela de terminal para usar voicestudio.",
"terminal_command_conflict": "{{path}} pertence a outra instalación, así que VoiceStudio non o modificou.",
"review_mode_on": "Pausa para revisar",
"review_mode_off": "Corre directo",
"translate_agent": "Axente apto",
@@ -1477,6 +1477,12 @@
"remote_backend_confirm_unverified": "इस बैकएंड URL ने कनेक्शन परीक्षण पास नहीं किया है. इसे सहेजें और फिर भी पुनः लोड करें? यदि यह गलत है, तो जब तक आप इसे यहां वापस नहीं बदलते तब तक ऐप किसी भी बैकएंड तक नहीं पहुंच सकता।",
"review_mode": "समीक्षा मोड",
"review_mode_desc": "पाइपलाइन चरणों के बीच रुकें ताकि आप एएसआर/अनुवाद आउटपुट की समीक्षा कर सकें।",
"terminal_command": "टर्मिनल कमांड",
"terminal_command_desc": "VoiceStudio की सुविधाएँ इस्तेमाल करने के लिए टर्मिनल में voicestudio चलाएँ; बिना आर्ग्युमेंट के यह ऐप खोलता है।",
"terminal_command_add": "टर्मिनल में जोड़ें",
"terminal_command_ready": "नए टर्मिनल में उपलब्ध",
"terminal_command_added": "जोड़ दिया गया। voicestudio इस्तेमाल करने के लिए नई टर्मिनल विंडो खोलें।",
"terminal_command_conflict": "{{path}} किसी दूसरे इंस्टॉलेशन का है, इसलिए VoiceStudio ने इसे नहीं बदला।",
"review_mode_on": "समीक्षा",
"review_mode_off": "तेजी से आग",
"translate_agent": "एजेंट फिट",
@@ -1477,6 +1477,12 @@
"audio_tools_open": "Buka alat Audio",
"review_mode": "Modus tinjauan",
"review_mode_desc": "Jeda di antara tahapan alur sehingga Anda dapat meninjau ASR/output terjemahan.",
"terminal_command": "Perintah terminal",
"terminal_command_desc": "Jalankan voicestudio di terminal untuk memakai fitur VoiceStudio; tanpa argumen, perintah ini membuka aplikasi.",
"terminal_command_add": "Tambahkan ke terminal",
"terminal_command_ready": "Tersedia di terminal baru",
"terminal_command_added": "Ditambahkan. Buka jendela terminal baru untuk memakai voicestudio.",
"terminal_command_conflict": "{{path}} milik instalasi lain, jadi VoiceStudio tidak mengubahnya.",
"review_mode_on": "Ulasan",
"review_mode_off": "Tembakan cepat",
"translate_agent": "Agen cocok",
@@ -1479,6 +1479,12 @@
"remote_backend_confirm_unverified": "Questo URL di backend non ha superato un test di connessione. Salvarlo e ricaricarlo comunque? Se è sbagliato, l'app non potrà raggiungere alcun backend finché non lo cambi di nuovo qui.",
"review_mode": "Modalità revisione",
"review_mode_desc": "Fai una pausa tra le fasi della pipeline in modo da poter rivedere l'output ASR/traduzione.",
"terminal_command": "Comando da terminale",
"terminal_command_desc": "Esegui voicestudio in un terminale per usare le funzioni di VoiceStudio; senza argomenti apre l'app.",
"terminal_command_add": "Aggiungi al terminale",
"terminal_command_ready": "Disponibile nei nuovi terminali",
"terminal_command_added": "Aggiunto. Apri una nuova finestra del terminale per usare voicestudio.",
"terminal_command_conflict": "{{path}} appartiene a un'altra installazione, quindi VoiceStudio non l'ha modificato.",
"review_mode_on": "Recensione",
"review_mode_off": "Fuoco rapido",
"translate_agent": "Agente in forma",
@@ -1477,6 +1477,12 @@
"remote_backend_confirm_title": "未検証のバックエンドを使用しますか?",
"review_mode": "レビューモード",
"review_mode_desc": "パイプライン ステージ間で一時停止して、ASR/翻訳出力を確認できるようにします。",
"terminal_command": "ターミナルコマンド",
"terminal_command_desc": "ターミナルで voicestudio を実行すると VoiceStudio の機能を使えます。引数なしで実行するとアプリが開きます。",
"terminal_command_add": "ターミナルに追加",
"terminal_command_ready": "新しいターミナルで利用可能",
"terminal_command_added": "追加しました。voicestudio を使うには新しいターミナルウィンドウを開いてください。",
"terminal_command_conflict": "{{path}} は別のインストールのものなので、VoiceStudio は変更しませんでした。",
"review_mode_on": "レビュー",
"review_mode_off": "連射",
"translate_agent": "エージェント調整",
@@ -1335,6 +1335,12 @@
"language_desc": "인터페이스 언어 선택",
"review_mode": "검토 모드",
"review_mode_desc": "ASR/번역 출력을 검토할 수 있도록 파이프라인 단계 사이에 일시 중지합니다.",
"terminal_command": "터미널 명령",
"terminal_command_desc": "터미널에서 voicestudio를 실행하면 VoiceStudio 기능을 사용할 수 있으며, 인수 없이 실행하면 앱이 열립니다.",
"terminal_command_add": "터미널에 추가",
"terminal_command_ready": "새 터미널에서 사용 가능",
"terminal_command_added": "추가했습니다. voicestudio를 사용하려면 새 터미널 창을 여세요.",
"terminal_command_conflict": "{{path}}은(는) 다른 설치에 속해 있어 VoiceStudio가 변경하지 않았습니다.",
"review_mode_on": "검토",
"translate_agent": "에이전트 적합성",
"llmp_cli_help": "설치된 CLI와 로그인 정보를 에이전트 복구와 같은 실행기로 사용합니다. CLI 기본값을 쓰려면 모델을 비워 두세요. 응답이 느릴 수 있으며 요금은 CLI 계정에 적용됩니다.",
@@ -1477,6 +1477,12 @@
"llmskills_glossary_extract_desc": "Stelt projectwoordenlijsttermen voor (namen, plaatsen, terugkerende terminologie) uit de bronsegmenten. Uit: woordenlijsttermen handmatig toevoegen.",
"review_mode": "Review-modus",
"review_mode_desc": "Pauzeer tussen pijplijnfasen, zodat u de ASR-/vertaaluitvoer kunt bekijken.",
"terminal_command": "Terminalopdracht",
"terminal_command_desc": "Voer voicestudio uit in een terminal om de functies van VoiceStudio te gebruiken; zonder argumenten opent het de app.",
"terminal_command_add": "Aan terminal toevoegen",
"terminal_command_ready": "Beschikbaar in nieuwe terminals",
"terminal_command_added": "Toegevoegd. Open een nieuw terminalvenster om voicestudio te gebruiken.",
"terminal_command_conflict": "{{path}} hoort bij een andere installatie, dus VoiceStudio heeft het niet gewijzigd.",
"review_mode_on": "Beoordeling",
"review_mode_off": "Snelvuur",
"translate_agent": "Agent geschikt",
@@ -1491,6 +1491,12 @@
"remote_backend_probe_fail": "Przegrany -{{detail}}",
"review_mode": "Tryb recenzji",
"review_mode_desc": "Wstrzymaj się między etapami potoku, aby móc przejrzeć wyniki ASR/tłumaczenia.",
"terminal_command": "Polecenie terminala",
"terminal_command_desc": "Uruchom voicestudio w terminalu, aby korzystać z funkcji VoiceStudio; bez argumentów otwiera aplikację.",
"terminal_command_add": "Dodaj do terminala",
"terminal_command_ready": "Dostępne w nowych terminalach",
"terminal_command_added": "Dodano. Otwórz nowe okno terminala, aby używać voicestudio.",
"terminal_command_conflict": "{{path}} należy do innej instalacji, więc VoiceStudio go nie zmienił.",
"review_mode_on": "Recenzja",
"review_mode_off": "Szybkostrzelny",
"translate_agent": "Agent pasuje",
@@ -1479,6 +1479,12 @@
"remote_backend_url": "URL de back-end",
"review_mode": "Modo de revisão",
"review_mode_desc": "Faça uma pausa entre os estágios do pipeline para poder revisar a saída de ASR/tradução.",
"terminal_command": "Comando de terminal",
"terminal_command_desc": "Execute voicestudio num terminal para usar os recursos do VoiceStudio; sem argumentos, abre o aplicativo.",
"terminal_command_add": "Adicionar ao terminal",
"terminal_command_ready": "Disponível em novos terminais",
"terminal_command_added": "Adicionado. Abra uma nova janela de terminal para usar voicestudio.",
"terminal_command_conflict": "{{path}} pertence a outra instalação, então o VoiceStudio não o alterou.",
"review_mode_on": "Revisão",
"review_mode_off": "Fogo rápido",
"translate_agent": "Ajuste do agente",
@@ -1491,6 +1491,12 @@
"remote_backend_invalid_url": "Введите действительный URL-адрес, начинающийся с http:// или https:// (например,http://gpu-box:3900).",
"review_mode": "Режим просмотра",
"review_mode_desc": "Делайте паузу между этапами конвейера, чтобы просмотреть результаты ASR/перевода.",
"terminal_command": "Команда терминала",
"terminal_command_desc": "Запускайте voicestudio в терминале, чтобы пользоваться функциями VoiceStudio; без аргументов команда открывает приложение.",
"terminal_command_add": "Добавить в терминал",
"terminal_command_ready": "Доступна в новых терминалах",
"terminal_command_added": "Добавлено. Откройте новое окно терминала, чтобы использовать voicestudio.",
"terminal_command_conflict": "{{path}} принадлежит другой установке, поэтому VoiceStudio его не изменил.",
"review_mode_on": "Обзор",
"review_mode_off": "Скорострельный",
"translate_agent": "Агент подходит",
@@ -1477,6 +1477,12 @@
"remote_backend_confirm_unverified": "Denna backend-URL har inte klarat ett anslutningstest. Spara den och ladda om ändå? Om det är fel kan appen inte nå någon backend förrän du ändrar tillbaka den här.",
"review_mode": "Granskningsläge",
"review_mode_desc": "Pausa mellan stegen i pipeline så att du kan granska ASR/översättningsutdata.",
"terminal_command": "Terminalkommando",
"terminal_command_desc": "Kör voicestudio i en terminal för att använda VoiceStudios funktioner; utan argument öppnas appen.",
"terminal_command_add": "Lägg till i terminalen",
"terminal_command_ready": "Tillgängligt i nya terminaler",
"terminal_command_added": "Tillagt. Öppna ett nytt terminalfönster för att använda voicestudio.",
"terminal_command_conflict": "{{path}} tillhör en annan installation, så VoiceStudio lämnade det oförändrat.",
"review_mode_on": "Granska",
"review_mode_off": "Snabb eld",
"translate_agent": "Agent passar",
@@ -1477,6 +1477,12 @@
"remote_backend_confirm_title": "ใช้แบ็กเอนด์ที่ไม่ได้รับการยืนยันใช่ไหม",
"review_mode": "โหมดทบทวน",
"review_mode_desc": "หยุดชั่วคราวระหว่างขั้นตอนไปป์ไลน์เพื่อให้คุณสามารถตรวจสอบ ASR / เอาต์พุตการแปลได้",
"terminal_command": "คำสั่งเทอร์มินัล",
"terminal_command_desc": "เรียกใช้ voicestudio ในเทอร์มินัลเพื่อใช้ฟีเจอร์ของ VoiceStudio หากไม่ใส่อาร์กิวเมนต์จะเปิดแอป",
"terminal_command_add": "เพิ่มลงในเทอร์มินัล",
"terminal_command_ready": "ใช้ได้ในเทอร์มินัลใหม่",
"terminal_command_added": "เพิ่มแล้ว เปิดหน้าต่างเทอร์มินัลใหม่เพื่อใช้ voicestudio",
"terminal_command_conflict": "{{path}} เป็นของการติดตั้งอื่น VoiceStudio จึงไม่ได้เปลี่ยนแปลง",
"review_mode_on": "รีวิว",
"review_mode_off": "ยิงเร็ว",
"translate_agent": "ปรับความพอดีด้วยเอเจนต์",
@@ -1477,6 +1477,12 @@
"remote_backend_hint": "Diğer makinedeki arka ucu <1> ile başlatınOMNIVOICE_API_KEY</1> ayarlayın, kuyruk ağınız üzerinden ona ulaşın ve bu uygulamayı ona doğrultun.",
"review_mode": "İnceleme modu",
"review_mode_desc": "ASR / çeviri çıktısını gözden geçirebilmek için ardışık düzen aşamaları arasında duraklayın.",
"terminal_command": "Terminal komutu",
"terminal_command_desc": "VoiceStudio özelliklerini kullanmak için terminalde voicestudio çalıştırın; argümansız çalıştırıldığında uygulamayı açar.",
"terminal_command_add": "Terminale ekle",
"terminal_command_ready": "Yeni terminallerde kullanılabilir",
"terminal_command_added": "Eklendi. voicestudio kullanmak için yeni bir terminal penceresi açın.",
"terminal_command_conflict": "{{path}} başka bir kuruluma ait, bu yüzden VoiceStudio onu değiştirmedi.",
"review_mode_on": "İncele",
"review_mode_off": "Hızlı ateş",
"translate_agent": "Ajanla uyarlama",
@@ -1491,6 +1491,12 @@
"audio_tools_ytdlp_updated": "yt-dlp{{version}}встановлено — перезапустіть серверну частину, щоб застосувати.",
"review_mode": "Режим перегляду",
"review_mode_desc": "Зробіть паузу між етапами конвеєра, щоб ви могли переглядати ASR / результат перекладу.",
"terminal_command": "Команда терміналу",
"terminal_command_desc": "Запускайте voicestudio у терміналі, щоб користуватися функціями VoiceStudio; без аргументів команда відкриває застосунок.",
"terminal_command_add": "Додати до терміналу",
"terminal_command_ready": "Доступна в нових терміналах",
"terminal_command_added": "Додано. Відкрийте нове вікно терміналу, щоб використовувати voicestudio.",
"terminal_command_conflict": "{{path}} належить іншому встановленню, тому VoiceStudio його не змінив.",
"review_mode_on": "огляд",
"review_mode_off": "Скорострільна",
"translate_agent": "Агент підходить",
@@ -1477,6 +1477,12 @@
"audio_tools_desc": "Công cụ truyền thông (FFmpeg, FFprobe) và trình tải xuống video (yt-dlp) mà ứng dụng quản lý cho bạn.",
"review_mode": "Chế độ xem lại",
"review_mode_desc": "Tạm dừng giữa các giai đoạn quy trình để bạn có thể xem lại đầu ra ASR/bản dịch.",
"terminal_command": "Lệnh terminal",
"terminal_command_desc": "Chạy voicestudio trong terminal để dùng các tính năng của VoiceStudio; không có tham số thì lệnh sẽ mở ứng dụng.",
"terminal_command_add": "Thêm vào terminal",
"terminal_command_ready": "Có sẵn trong terminal mới",
"terminal_command_added": "Đã thêm. Mở cửa sổ terminal mới để dùng voicestudio.",
"terminal_command_conflict": "{{path}} thuộc về một bản cài đặt khác nên VoiceStudio không thay đổi nó.",
"review_mode_on": "Xem lại",
"review_mode_off": "Bắn nhanh",
"translate_agent": "Điều chỉnh bằng tác nhân",
@@ -1466,6 +1466,12 @@
"asr_compat_test_hint": "先保存当前设置,然后在不发送音频的情况下检查服务器。",
"language": "语言",
"review_mode_desc": "在管道阶段之间暂停,以便您可以查看 ASR/翻译输出。",
"terminal_command": "终端命令",
"terminal_command_desc": "在终端中运行 voicestudio 即可使用 VoiceStudio 的功能;不带参数运行会打开应用。",
"terminal_command_add": "添加到终端",
"terminal_command_ready": "可在新终端中使用",
"terminal_command_added": "已添加。打开新的终端窗口即可使用 voicestudio。",
"terminal_command_conflict": "{{path}} 属于另一个安装,因此 VoiceStudio 未作更改。",
"review_mode_on": "审阅",
"translate_agent": "智能体适配",
"llmp_cli_help": "通过与代理修复相同的运行器使用已安装的 CLI 及其登录。模型留空将使用 CLI 默认值。响应可能较慢,费用按 CLI 账户计收。",
@@ -1477,6 +1477,12 @@
"audio_tools_manual_hint": "更喜歡您的套件管理器?自行安裝 FFmpeg(macOS:brew install ffmpeg · Debian/Ubuntu:sudo apt install ffmpeg · Windows:winget install ffmpeg)並按使用系統副本。該應用程式從未在系統範圍內安裝任何內容。",
"review_mode": "複習模式",
"review_mode_desc": "在管道階段之間暫停,以便您可以查看 ASR/翻譯輸出。",
"terminal_command": "終端機指令",
"terminal_command_desc": "在終端機中執行 voicestudio 即可使用 VoiceStudio 的功能;不帶參數執行會開啟應用程式。",
"terminal_command_add": "加入終端機",
"terminal_command_ready": "可在新的終端機中使用",
"terminal_command_added": "已加入。開啟新的終端機視窗即可使用 voicestudio。",
"terminal_command_conflict": "{{path}} 屬於另一個安裝,因此 VoiceStudio 未作變更。",
"review_mode_on": "評論",
"review_mode_off": "速射",
"translate_agent": "代理適配",
+158
View File
@@ -0,0 +1,158 @@
// Explicit native build check; uses fixture apps, never the user's desktop/backend.
import assert from 'node:assert/strict';
import {
cpSync,
mkdtempSync,
mkdirSync,
writeFileSync,
readFileSync,
renameSync,
rmSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { createRequire } from 'node:module';
import { execFile, spawnSync } from 'node:child_process';
import { createServer } from 'node:http';
import { promisify } from 'node:util';
import { Arch } from 'builder-util';
import { packageCli } from '../cli-bundle.mjs';
const root = mkdtempSync(join(tmpdir(), 'vs-cli-native-'));
const actualElectron = process.argv.includes('--electron');
if (actualElectron && process.platform !== 'linux')
throw new Error('--electron currently requires Linux');
try {
const resources =
process.platform === 'darwin'
? join(root, 'VoiceStudio.app/Contents/Resources')
: join(root, 'resources');
mkdirSync(resources, { recursive: true });
const desktop =
process.platform === 'darwin'
? join(root, 'VoiceStudio.app/Contents/MacOS/VoiceStudio')
: join(root, process.platform === 'win32' ? 'VoiceStudio.exe' : 'voicestudio');
mkdirSync(join(desktop, '..'), { recursive: true });
if (actualElectron) {
const require = createRequire(import.meta.url);
cpSync(dirname(require('electron')), root, { recursive: true });
renameSync(join(root, 'electron'), desktop);
mkdirSync(join(resources, 'app'));
writeFileSync(
join(resources, 'app/package.json'),
JSON.stringify({ name: 'voicestudio-cli-smoke', main: 'index.cjs' }),
);
writeFileSync(
join(resources, 'app/index.cjs'),
`
const { app, BrowserWindow } = require('electron');
const { writeFileSync } = require('node:fs');
app.setPath('userData', process.env.VS_CLI_SMOKE_PROFILE);
app.whenReady().then(async () => {
const window = new BrowserWindow({ show: false });
await window.loadURL('about:blank');
writeFileSync(process.env.VS_CLI_SMOKE_RECORD, JSON.stringify({ setting: process.env.VS_CLI_SMOKE_SETTING }));
window.destroy();
app.quit();
});
`,
);
} else if (process.platform !== 'win32') {
writeFileSync(desktop, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
}
await packageCli({
appOutDir: root,
electronPlatformName: process.platform,
arch: Arch[process.arch],
packager: {
executableName: 'voicestudio',
appInfo: {
productFilename: 'VoiceStudio',
version: JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version,
},
getResourcesDir: () => resources,
signIf: async () => {},
},
});
const command = join(
resources,
'cli',
'voicestudio' + (process.platform === 'win32' ? '.exe' : ''),
);
const run = (args, env = {}) =>
spawnSync(command, args, {
encoding: 'utf8',
cwd: tmpdir(),
env: {
...process.env,
VOICESTUDIO_CONFIG: join(root, 'config.json'),
OMNIVOICE_API_KEY: '',
...env,
},
timeout: 15000,
});
for (const args of [
['--version'],
['voices', '--help'],
['models', '--help'],
['update', 'info'],
]) {
const result = run(args);
assert.equal(result.status, 0, result.stderr);
}
const typo = run(['udpate', '--json']);
assert.equal(typo.status, 2);
assert.equal(JSON.parse(typo.stderr).error.code, 'usage_error');
const noDesktop = run([], { VOICESTUDIO_DESKTOP_APP: join(root, 'missing') });
assert.equal(noDesktop.status, 1);
assert.match(noDesktop.stderr, /Can't find the VoiceStudio app/);
if (process.platform === 'linux') {
const launch = actualElectron
? run(['--no-sandbox'], {
VS_CLI_SMOKE_PROFILE: join(root, 'profile'),
VS_CLI_SMOKE_RECORD: join(root, 'launch.json'),
HOME: join(root, 'home'),
XDG_CONFIG_HOME: join(root, 'home/.config'),
XDG_CACHE_HOME: join(root, 'home/.cache'),
VS_CLI_SMOKE_SETTING: 'value with spaces',
})
: run([]);
assert.equal(launch.status, 0, launch.stderr);
if (actualElectron)
assert.deepEqual(JSON.parse(readFileSync(join(root, 'launch.json'))), {
setting: 'value with spaces',
});
}
const requests = [];
const server = createServer((request, response) => {
requests.push(request.url);
response.setHeader('Content-Type', 'application/json');
response.setHeader('X-OmniVoice-Backend', 'fixture');
response.end(
JSON.stringify(request.url === '/health' ? { status: 'ok', version: 'fixture' } : []),
);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const result = await promisify(execFile)(
command,
['--url', `http://127.0.0.1:${server.address().port}`, 'projects', 'list', '--json'],
{
cwd: tmpdir(),
timeout: 15000,
env: {
...process.env,
VOICESTUDIO_CONFIG: join(root, 'config.json'),
OMNIVOICE_API_KEY: '',
},
},
);
assert.deepEqual(JSON.parse(result.stdout), []);
assert.deepEqual(requests, ['/health', '/projects']);
} finally {
await new Promise((resolve) => server.close(resolve));
}
console.log('PASS: packaged CLI commands, desktop launch and HTTP contracts');
} finally {
rmSync(root, { recursive: true, force: true });
}
+72
View File
@@ -0,0 +1,72 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { cliBuildArguments, wirePackagedCli } from '../cli-bundle.mjs';
test('builds the CLI package with an embedded interpreter and package data', () => {
const args = cliBuildArguments('/fixture');
assert(args.includes('--onedir'));
assert(args.includes('--console'));
assert(args.includes('--copy-metadata'));
assert(args.includes('voicestudio-cli'));
assert(args.includes('voicestudio_cli'));
assert(cliBuildArguments('/fixture', 'win32').includes('cpython-3.11-windows-x86_64-none'));
});
for (const platform of ['linux', 'darwin', 'win32']) {
test(`packages a private desktop target and a public CLI (${platform})`, (t) => {
const root = mkdtempSync(join(tmpdir(), 'vs-cli-layout-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const appOutDir = join(root, 'installed app');
const resources =
platform === 'darwin'
? join(appOutDir, 'VoiceStudio.app/Contents/Resources')
: join(appOutDir, 'resources');
mkdirSync(resources, { recursive: true });
const bundle = join(root, 'bundle');
mkdirSync(join(bundle, '_internal'), { recursive: true });
writeFileSync(join(bundle, '_internal/contracts.json'), '{}');
const cliName = platform === 'win32' ? 'voicestudio.exe' : 'voicestudio';
writeFileSync(join(bundle, cliName), '#!/bin/sh\nprintf "CLI:%s\\n" "$*"\n', { mode: 0o755 });
const desktop =
platform === 'darwin'
? join(appOutDir, 'VoiceStudio.app/Contents/MacOS/VoiceStudio')
: join(appOutDir, platform === 'win32' ? 'VoiceStudio.exe' : 'voicestudio');
mkdirSync(join(desktop, '..'), { recursive: true });
writeFileSync(desktop, 'original desktop');
const context = {
appOutDir,
electronPlatformName: platform,
packager: {
executableName: 'voicestudio',
appInfo: { productFilename: 'VoiceStudio', version: '9.8.7' },
getResourcesDir: () => resources,
},
};
const cli = wirePackagedCli(context, bundle);
assert.equal(cli, join(resources, 'cli', cliName));
assert(existsSync(join(resources, 'cli/_internal/contracts.json')));
const manifest = JSON.parse(readFileSync(join(resources, 'cli/desktop.json')));
if (platform === 'linux') {
assert.equal(manifest.executable, '../../voicestudio-desktop');
assert.equal(
readFileSync(join(appOutDir, 'voicestudio-desktop'), 'utf8'),
'original desktop',
);
if (process.platform === 'linux') {
const result = spawnSync(desktop, ['voices', '--help'], { encoding: 'utf8' });
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stdout, 'CLI:voices --help\n');
}
} else {
assert.equal(readFileSync(desktop, 'utf8'), 'original desktop');
assert.equal(
manifest.executable.replaceAll('\\', '/'),
platform === 'darwin' ? '../../MacOS/VoiceStudio' : '../../VoiceStudio.exe',
);
}
});
}
@@ -13,7 +13,7 @@ const executablePath = process.env.VOICESTUDIO_PACKAGED_EXE
? 'electron/release/win-unpacked/VoiceStudio.exe'
: process.platform === 'darwin'
? 'electron/release/mac/VoiceStudio.app/Contents/MacOS/VoiceStudio'
: 'electron/release/linux-unpacked/voicestudio-electron',
: 'electron/release/linux-unpacked/voicestudio-desktop',
);
assert.ok(existsSync(executablePath), `Packaged executable does not exist: ${executablePath}`);
const profile = mkdtempSync(join(tmpdir(), 'voicestudio-translation-agent-'));
@@ -11,7 +11,7 @@ const executablePath =
? 'electron/release/win-unpacked/VoiceStudio.exe'
: process.platform === 'darwin'
? 'electron/release/mac/VoiceStudio.app/Contents/MacOS/VoiceStudio'
: 'electron/release/linux-unpacked/voicestudio-electron',
: 'electron/release/linux-unpacked/voicestudio-desktop',
);
const profile = mkdtempSync(join(tmpdir(), 'voicestudio-packaged-repair-'));
const app = await electron.launch({
@@ -17,7 +17,7 @@ const defaultExecutable =
? resolve('electron/release/win-unpacked/VoiceStudio.exe')
: process.platform === 'darwin'
? resolve('electron/release/mac/VoiceStudio.app/Contents/MacOS/VoiceStudio')
: resolve('electron/release/linux-unpacked/voicestudio-electron');
: resolve('electron/release/linux-unpacked/voicestudio-desktop');
const executablePath = process.env.VOICESTUDIO_PACKAGED_EXE
? resolve(process.env.VOICESTUDIO_PACKAGED_EXE)
: defaultExecutable;
+3 -3
View File
@@ -31,10 +31,10 @@ const defaultExecutableCandidates =
]
: targetArch === 'arm64'
? [
'electron/release/linux-arm64-unpacked/voicestudio-electron',
'electron/release/linux-unpacked/voicestudio-electron',
'electron/release/linux-arm64-unpacked/voicestudio-desktop',
'electron/release/linux-unpacked/voicestudio-desktop',
]
: ['electron/release/linux-unpacked/voicestudio-electron'];
: ['electron/release/linux-unpacked/voicestudio-desktop'];
const defaultExecutable =
defaultExecutableCandidates.find((candidate) => existsSync(resolve(repoRoot, candidate))) ??
defaultExecutableCandidates[0];
+8
View File
@@ -339,6 +339,14 @@ for (const platform of ['win', 'mac', 'linux']) {
}
}
if (artifactRequested) {
const cliCommand = resolve(artifactResources, 'cli',
'voicestudio' + (process.platform === 'win32' ? '.exe' : ''));
assert(existsSync(cliCommand), 'Packaged unified command with its own interpreter');
const cliVersion = spawnSync(cliCommand, ['version', '--json'], { encoding: 'utf8' });
assert.equal(cliVersion.status, 0, cliVersion.stderr);
assert.equal(JSON.parse(cliVersion.stdout).version, config.extraMetadata.version);
const cliHelp = spawnSync(cliCommand, ['--help'], { encoding: 'utf8' });
assert.equal(cliHelp.status, 0, cliHelp.stderr);
if (process.platform === 'linux') {
await verifyLinuxLibraries(resolve(artifactResources, 'native/voicestudio-desktop-bridge'));
}
+43 -2
View File
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readlinkSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
@@ -68,6 +68,7 @@ if [ "$1" = attach ]; then
while [ "$1" != -mountpoint ]; do shift; done
shift; mkdir -p "$1/VoiceStudio.app/Contents"
printf fixture > "$1/VoiceStudio.app/Contents/Info.plist"
${options.cli ? 'mkdir -p "$1/VoiceStudio.app/Contents/Resources/cli"; printf fixture > "$1/VoiceStudio.app/Contents/Resources/cli/voicestudio"; touch "$1/VoiceStudio.app/Contents/Resources/app.asar"; chmod +x "$1/VoiceStudio.app/Contents/Resources/cli/voicestudio"' : ':'}
fi
`,
);
@@ -124,7 +125,7 @@ if [ "$1 $2" = 'run electron-builder' ]; then printf '${payload}' > release/Voic
shim('readelf', 'exit 0\n');
shim('zsyncmake', 'exit 0\n');
shim('pgrep', options.linuxRunning
? `case "$*" in *voicestudio-electron*) exit 0;; *) exit 1;; esac\n`
? `case "$*" in *voicestudio-*) exit 0;; *) exit 1;; esac\n`
: options.running ? 'exit 0\n' : 'exit 1\n');
shim('lsregister', 'printf "%s\\n" "$*" >> "$TEST_ROOT/registration"\n' + (options.registrationFails ? 'exit 1\n' : ''));
const settings = join(home, 'settings');
@@ -158,6 +159,46 @@ if [ "$1 $2" = 'run electron-builder' ]; then printf '${payload}' > release/Voic
};
}
for (const mac of [false, true]) {
test(`installs, upgrades and removes only its owned command (${mac ? 'macOS' : 'Linux'})`, (t) => {
const f = fixture(t, { mac, cli: true });
writeFileSync(join(f.home, '.bashrc'), '# my settings\n');
const command = join(f.home, '.local/bin/voicestudio');
assert.equal(f.run().status, 0);
const target = mac ? join(f.home, 'Applications/VoiceStudio.app/Contents/Resources/cli/voicestudio')
: join(f.home, '.local/bin/VoiceStudio');
assert.equal(readlinkSync(command), target);
assert.equal(f.run().status, 0);
const profile = readFileSync(join(f.home, '.bashrc'), 'utf8');
assert(profile.startsWith('# my settings\n'));
assert.equal(profile.match(/# VoiceStudio terminal command/g).length, 1);
assert.equal(f.run(['--uninstall']).status, 0);
assert.equal(existsSync(command), false);
});
}
test('command collisions preserve the existing app and launcher', (t) => {
const f = fixture(t);
const command = join(f.home, '.local/bin/voicestudio');
const app = join(f.home, '.local/bin/VoiceStudio');
writeFileSync(app, 'old app');
writeFileSync(command, '#!/bin/sh\nexport CLI_TEST_SETTING=sample\nexec old-app\n');
const result = f.run();
assert.notEqual(result.status, 0);
assert.match(result.stderr, /Existing command/);
assert.equal(readFileSync(app, 'utf8'), 'old app');
assert.match(readFileSync(command, 'utf8'), /CLI_TEST_SETTING=sample/);
});
test('desktop installation preserves a command already owned by the CLI package', (t) => {
const f = fixture(t);
const command = join(f.home, '.local/bin/voicestudio');
const cli = '#!/usr/bin/python3\nfrom voicestudio_cli.__main__ import main\nmain()\n';
writeFileSync(command, cli);
assert.equal(f.run().status, 0);
assert.equal(readFileSync(command, 'utf8'), cli);
});
// Releases up to v0.5.7-beta.3 named their packages VoiceStudio-Electron-*.
for (const [name, args, version, brand] of [
['latest', [], '1.2.3', 'VoiceStudio'],
+1 -1
View File
@@ -12,7 +12,7 @@ test('names direct downloads VoiceStudio-<version>-<os>-<arch> without an Electr
test('keeps direct Linux packaging and its updater unchanged', () => {
const packaging = distributionPackaging('direct');
assert.deepEqual(packaging.linuxTargets, ['AppImage', 'deb']);
assert.equal(packaging.linuxExecutableName, undefined);
assert.equal(packaging.linuxExecutableName, 'voicestudio');
assert.equal(packaging.snapcraft, undefined);
assert.deepEqual(packaging.publish, {
provider: 'generic',
+52
View File
@@ -0,0 +1,52 @@
"""Exercise command replacement with real uv in temporary tool/config directories."""
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
def main():
if os.name == 'nt':
raise SystemExit('This check exercises migration of a POSIX desktop wrapper.')
root = Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='voicestudio-cli-migrate-') as directory:
work = Path(directory)
bin_dir = work / 'bin'
bin_dir.mkdir()
record = work / 'launched.json'
fixture = work / 'desktop.py'
fixture.write_text('import json, os\nfrom pathlib import Path\n' +
f'Path({str(record)!r}).write_text(json.dumps({{"setting": os.getenv("CLI_TEST_SETTING")}}))\n')
app = work / 'metadata-app'
(app / 'resources/app').mkdir(parents=True)
(app / 'resources/app/package.json').write_text(json.dumps({'version': '9.8.7'}))
executable = app / 'voicestudio-desktop'
executable.write_bytes(b'fixture application')
executable.chmod(0o755)
wrapper = bin_dir / 'voicestudio'
original = '#!/bin/sh\nexport CLI_TEST_SETTING="value with spaces"\nexec ' + shlex.join([sys.executable, str(fixture)]) + '\n'
wrapper.write_text(original)
wrapper.chmod(0o755)
env = {**os.environ, 'UV_TOOL_DIR': str(work / 'tools'), 'UV_TOOL_BIN_DIR': str(bin_dir),
'VOICESTUDIO_CONFIG': str(work / 'config/config.json'), 'PYTHONPATH': str(root / 'cli')}
env.pop('VOICESTUDIO_DESKTOP_APP', None)
subprocess.run([sys.executable, '-m', 'voicestudio_cli.install', str(root / 'cli'),
'--replace-launcher', '--no-modify-path'], check=True, env=env, cwd=work)
env.pop('PYTHONPATH')
result = subprocess.run([str(wrapper), '--version'], check=True, capture_output=True, text=True,
env=env | {'VOICESTUDIO_DESKTOP_APP': str(executable)}, cwd=work)
assert result.stdout.strip() == 'VoiceStudio 9.8.7'
subprocess.run([str(wrapper)], check=True, env=env, cwd=work)
assert json.loads(record.read_text()) == {'setting': 'value with spaces'}
backup = work / 'config/desktop-launcher'
assert backup.read_text() == original
subprocess.run(['uv', 'tool', 'uninstall', 'voicestudio-cli'], check=True, env=env, cwd=work)
assert backup.read_text() == original
print('PASS: command installation, launcher dispatch and environment preservation')
if __name__ == '__main__':
main()
+74
View File
@@ -0,0 +1,74 @@
"""Install a built wheel in a throwaway environment and exercise its entry point."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import venv
import zipfile
ROOT = Path(__file__).resolve().parent.parent
def main():
wheel = Path(sys.argv[1]).resolve()
canonical = json.loads((ROOT / 'package.json').read_text())['version']
with zipfile.ZipFile(wheel) as archive:
metadata = archive.read(next(n for n in archive.namelist() if n.endswith('.dist-info/METADATA'))).decode()
assert 'Requires-Dist:' not in metadata, 'CLI must not install inference dependencies'
assert 'voicestudio_cli/contracts.json' in archive.namelist()
class Health(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
data = json.dumps({'status': 'ok', 'version': canonical}).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('X-OmniVoice-Backend', canonical)
self.send_header('Content-Length', str(len(data)))
self.end_headers(); self.wfile.write(data)
server = ThreadingHTTPServer(('127.0.0.1', 0), Health)
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
try:
with tempfile.TemporaryDirectory(prefix='voicestudio-cli-smoke-') as directory:
env_path = Path(directory) / 'venv'
venv.create(env_path, with_pip=True)
binary_dir = env_path / ('Scripts' if os.name == 'nt' else 'bin')
python = binary_dir / ('python.exe' if os.name == 'nt' else 'python')
subprocess.run([str(python), '-m', 'pip', 'install', '--no-index', '--no-deps', str(wheel)], check=True)
executable = binary_dir / ('voicestudio.exe' if os.name == 'nt' else 'voicestudio')
env = {**os.environ, 'VOICESTUDIO_CONFIG': str(Path(directory) / 'config.json'),
'VOICESTUDIO_URL': f'http://127.0.0.1:{server.server_port}'}
app = Path(directory) / 'application'
(app / 'resources/app').mkdir(parents=True)
(app / 'resources/app/package.json').write_text(json.dumps({'version': '9.8.7'}))
desktop = app / ('VoiceStudio.exe' if os.name == 'nt' else 'voicestudio-desktop')
desktop.write_bytes(b'fixture application')
desktop.chmod(0o755)
env['VOICESTUDIO_DESKTOP_APP'] = str(desktop)
for key in ['PYTHONPATH', 'OMNIVOICE_API_KEY']:
env.pop(key, None)
policy = subprocess.run([str(python), '-c',
'from voicestudio_cli.runtime import POLICY; '
'from voicestudio_cli.__main__ import build_parser; '
'_, nodes = build_parser(); '
'assert set(POLICY) == {" ".join(path) for path, parser in nodes.items() if "handler" in parser._defaults}'],
cwd=directory, env=env, capture_output=True, text=True, timeout=30)
assert policy.returncode == 0, policy.stderr
for args in [['version'], ['--version'], ['-v'], ['voices', 'reference', '--help'], ['status', '--json']]:
result = subprocess.run([str(executable), *args], cwd=directory, env=env,
capture_output=True, text=True, timeout=30)
assert result.returncode == 0, result.stderr
assert ('9.8.7' if args[0] in {'version', '--version', '-v'} else canonical) in result.stdout or '--help' in args, result.stdout
finally:
server.shutdown(); server.server_close(); thread.join()
print('PASS: installed wheel, entry point, offline help/version and HTTP health')
if __name__ == '__main__':
main()
+45
View File
@@ -0,0 +1,45 @@
"""Export the CLI request contract from the already generated backend OpenAPI.
Run after scripts/export_openapi.py when backend request contracts change.
"""
import json
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / 'cli'))
from voicestudio_cli.registry import COMMANDS
def build_contract():
schema = json.loads((ROOT / 'mobile/contract/openapi.json').read_text())
result = {}
def shape(path):
return re.sub(r'\{[^}]+\}', '{}', path)
for command in COMMANDS:
if command.route.startswith('/audio/') and command.name == 'history download':
continue # Starlette's static mount is intentionally absent from OpenAPI.
if command.route == '/openapi.json':
continue
path = next(p for p in schema['paths'] if shape(p) == shape(command.route))
operation = schema['paths'][path][command.method.lower()]
content = operation.get('requestBody', {}).get('content', {})
encoding = next(iter(content), '')
body = content.get(encoding, {}).get('schema', {})
if '$ref' in body:
body = schema['components']['schemas'][body['$ref'].rsplit('/', 1)[-1]]
result[command.name] = {
'encoding': encoding,
'required': body.get('required', []),
'fields': list(body.get('properties', {})),
'query': [p['name'] for p in operation.get('parameters', []) if p['in'] == 'query'],
'required_query': [p['name'] for p in operation.get('parameters', [])
if p['in'] == 'query' and p.get('required')],
}
return result
if __name__ == '__main__':
target = ROOT / 'cli/voicestudio_cli/contracts.json'
target.write_text(json.dumps(build_contract(), indent=2, sort_keys=True) + '\n')
+33
View File
@@ -0,0 +1,33 @@
"""Build the standalone CLI and carry interpreter/bootloader notices with it."""
from importlib import metadata
from pathlib import Path
import shutil
import sys
import sysconfig
from PyInstaller.__main__ import run
def main():
arguments = sys.argv[1:]
work = Path(arguments[arguments.index('--specpath') + 1])
notices = work / 'notices'
notices.mkdir()
candidates = [Path(sysconfig.get_path('stdlib')) / 'LICENSE.txt', Path(sys.base_prefix) / 'LICENSE.txt']
license_file = next((path for path in candidates if path.is_file()), None)
if license_file is None:
raise RuntimeError('Python runtime license is missing; refusing to bundle it without its notice.')
shutil.copy2(license_file, notices / 'Python-LICENSE.txt')
dist = metadata.distribution('pyinstaller')
license_files = [file for file in dist.files or [] if '.dist-info/licenses/' in str(file).replace('\\', '/')]
if not license_files:
raise RuntimeError('PyInstaller bootloader license is missing.')
for file in license_files:
target = notices / 'PyInstaller' / Path(str(file).split('licenses/', 1)[-1])
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(dist.locate_file(file), target)
run([*arguments, '--add-data', f'{notices}:licenses'])
if __name__ == '__main__':
main()
+1 -1
View File
@@ -61,7 +61,7 @@ $work = Join-Path ([IO.Path]::GetTempPath()) ('voicestudio-install-' + [Guid]::N
New-Item -ItemType Directory -Path $work | Out-Null
try {
if ($mode -eq 'main') {
foreach ($tool in @('git', 'node', 'bun', 'cargo')) {
foreach ($tool in @('git', 'node', 'bun', 'cargo', 'uv')) {
if (-not (Get-Command $tool -ErrorAction SilentlyContinue)) { throw "Main builds require $tool; see docs/install/script.md." }
}
Run-Checked node @('-e', 'if (Number(process.versions.node.split(".")[0]) < 22) process.exit(1)')
+54 -3
View File
@@ -19,7 +19,7 @@ VoiceStudio Electron installer (macOS / Linux)
--help Show this help
Release installs require curl and a SHA-256 tool. Main builds also require
Git, Node.js 22+, Bun, Rust/Cargo, and native build dependencies (see README).
Git, Node.js 22+, Bun, Rust/Cargo, uv, and native build dependencies (see README).
The installer preserves settings, models, and projects. Quit VoiceStudio first.
Versions without Electron artifacts are not supported; Tauri is archived.
HELP
@@ -63,7 +63,7 @@ if [ -n "${VOICESTUDIO_INSTALL_DIR:-}" ]; then
[ -d "$VOICESTUDIO_INSTALL_DIR" ] && [ -w "$VOICESTUDIO_INSTALL_DIR" ] || die 'Custom install directory must exist and be writable.'
fi
require_closed() {
if have pgrep && { pgrep -f '/VoiceStudio[.]app/Contents/MacOS/VoiceStudio([[:space:]]|$)' >/dev/null 2>&1 || pgrep -x VoiceStudio >/dev/null 2>&1 || pgrep -f '(^|/)voicestudio-electron([[:space:]]|$)' >/dev/null 2>&1; }; then
if have pgrep && { pgrep -f '/VoiceStudio[.]app/Contents/MacOS/VoiceStudio([[:space:]]|$)' >/dev/null 2>&1 || pgrep -x VoiceStudio >/dev/null 2>&1 || pgrep -f '(^|/)voicestudio-(electron|desktop)([[:space:]]|$)' >/dev/null 2>&1; }; then
die 'Quit VoiceStudio completely (macOS: Command-Q), then run this command again. No app files were changed.'
fi
}
@@ -92,6 +92,13 @@ if [ "$UNINSTALL" = 1 ]; then
recovery=$(mktemp -d "$(dirname "$target")/.voicestudio-uninstalled.XXXXXXXX")
fi
mv "$target" "$recovery/" || die "Could not remove $target; check permissions."
command_path="$HOME/.local/bin/voicestudio"
if [ -L "$command_path" ]; then
command_target=$(readlink "$command_path")
if [ "$command_target" = "$target" ] || [ "$command_target" = "$target/Contents/Resources/cli/voicestudio" ]; then
rm "$command_path"
fi
fi
printf 'Uninstalled: %s\nRecoverable copy: %s\n' "$target" "$recovery"
}
printf 'Quit VoiceStudio before uninstalling.\n'
@@ -136,6 +143,42 @@ trap 'exit 130' INT
trap 'exit 143' TERM HUP
download() { curl --proto '=https' --proto-redir '=https' --connect-timeout 30 --max-time 1800 -fLsS --retry 3 "$1" -o "$2"; }
check_command_target() {
KEEP_COMMAND=0
command_path="$HOME/.local/bin/voicestudio"
if [ -e "$command_path" ] || [ -L "$command_path" ]; then
if [ -f "$command_path" ] && grep -q 'from voicestudio_cli.__main__ import main' "$command_path"; then
KEEP_COMMAND=1
return
fi
[ -L "$command_path" ] && [ "$(readlink "$command_path")" = "$1" ] ||
die "Existing command $command_path belongs to another installation. Preserve/migrate it with the CLI installer before installing here. No app files were changed."
fi
}
install_command() {
[ "${KEEP_COMMAND:-0}" != 1 ] || return 0
command_path="$HOME/.local/bin/voicestudio"
mkdir -p "$HOME/.local/bin"
# The installer owns only this symlink; the command implementation lives in the package.
ln -sf "$1" "$command_path"
for profile in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.zshrc"; do
if ! grep -q '^# VoiceStudio terminal command$' "$profile" 2>/dev/null; then
cat >> "$profile" <<'COMMAND_PATH'
# VoiceStudio terminal command
case ":$PATH:" in
*":$HOME/.local/bin:"*) ;;
*) export PATH="$HOME/.local/bin:$PATH" ;;
esac
COMMAND_PATH
fi
done
mkdir -p "$HOME/.config/fish/conf.d"
printf '%s\n' 'fish_add_path --path "$HOME/.local/bin"' > "$HOME/.config/fish/conf.d/voicestudio.fish"
printf 'Installed command: %s\n' "$command_path"
}
install_app() {
require_closed
if [ "$OS" = mac ]; then
@@ -146,6 +189,9 @@ install_app() {
# Copy and validate first, retaining the prior app until the copy succeeds.
ditto "$1" "$STAGED/VoiceStudio.app"
[ -f "$STAGED/VoiceStudio.app/Contents/Info.plist" ] || die 'Invalid application bundle.'
if [ -x "$STAGED/VoiceStudio.app/Contents/Resources/cli/voicestudio" ]; then
check_command_target "$DEST/Contents/Resources/cli/voicestudio"
fi
if [ -e "$DEST" ]; then
BACKUP="$STAGED/previous.app"
mv "$DEST" "$BACKUP"
@@ -163,14 +209,19 @@ install_app() {
|| printf 'Warning: could not repair the app signature; see docs/install/macos.md#gatekeeper-quarantine.\n' >&2
fi
lsregister -f "$DEST" || printf 'Warning: macOS registration failed; open the installed app directly.\n' >&2
if [ -x "$DEST/Contents/Resources/cli/voicestudio" ]; then
install_command "$DEST/Contents/Resources/cli/voicestudio"
fi
else
DEST_DIR=${VOICESTUDIO_INSTALL_DIR:-"$HOME/.local/bin"}
mkdir -p "$DEST_DIR"
DEST="$DEST_DIR/VoiceStudio"
check_command_target "$DEST"
STAGED=$(mktemp -d "$DEST_DIR/.voicestudio-install.XXXXXXXX")
cp "$1" "$STAGED/VoiceStudio"
chmod +x "$STAGED/VoiceStudio"
mv -f "$STAGED/VoiceStudio" "$DEST"
install_command "$DEST"
fi
printf 'Installed Electron: %s\n' "$DEST"
printf 'Open VoiceStudio to configure its local backend and choose models. Existing data is preserved.\n'
@@ -181,7 +232,7 @@ install_app() {
}
if [ "$MODE" = main ]; then
for tool in git node bun cargo; do have "$tool" || die "Main builds require $tool; see the source-build prerequisites in README."; done
for tool in git node bun cargo uv; do have "$tool" || die "Main builds require $tool; see the source-build prerequisites in README."; done
if [ "$OS" = linux ]; then
for tool in readelf zsyncmake; do have "$tool" || die "Linux main builds require $tool; install binutils and zsync (see docs/install/script.md)."; done
fi
+8
View File
@@ -121,6 +121,14 @@ app_targets=()
# ── Optional: the prebuilt app installed by `curl … | sh` (default mode) ────
if [ "$REMOVE_APP" -eq 1 ]; then
command_path="$HOME/.local/bin/voicestudio"
if [ -L "$command_path" ]; then
command_target="$(readlink "$command_path")"
case "$command_target" in
"$HOME/.local/bin/VoiceStudio"|"/Applications/VoiceStudio.app/Contents/Resources/cli/voicestudio"|"$HOME/Applications/VoiceStudio.app/Contents/Resources/cli/voicestudio")
app_targets+=("$command_path") ;;
esac
fi
case "$OS" in
Darwin)
for app_dir in "/Applications/VoiceStudio.app" "$HOME/Applications/VoiceStudio.app"; do
+31
View File
@@ -0,0 +1,31 @@
"""Subprocess test guard: CLI tests may contact loopback servers only."""
import ipaddress
import socket
original_connect = socket.socket.connect
original_getaddrinfo = socket.getaddrinfo
def allowed(host):
if host == 'localhost':
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def connect(self, address):
if self.family in {socket.AF_INET, socket.AF_INET6} and not allowed(address[0]):
raise OSError('External network access forbidden in CLI tests')
return original_connect(self, address)
def getaddrinfo(host, *args, **kwargs):
if not allowed(host):
raise OSError('External DNS access forbidden in CLI tests')
return original_getaddrinfo(host, *args, **kwargs)
socket.socket.connect = connect
socket.getaddrinfo = getaddrinfo
+166
View File
@@ -0,0 +1,166 @@
"""Installed app metadata is independent of the Python distribution version."""
import io
import json
import os
from pathlib import Path
import plistlib
import struct
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'cli'))
from voicestudio_cli import application
from voicestudio_cli.errors import CLIError
def asar(path, metadata):
payload = json.dumps(metadata).encode()
header = json.dumps({'files': {'package.json': {'offset': '0', 'size': len(payload)}}}).encode()
body = struct.pack('<II', len(header) + 4, len(header)) + header
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(struct.pack('<II', 4, len(body)) + body + payload)
class ApplicationTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
environment = patch.dict(os.environ, {'VOICESTUDIO_CONFIG': str(self.root / 'config.json')})
environment.start(); self.addCleanup(environment.stop)
def test_asar_version_and_distribution_are_read_offline(self):
exe = self.root / 'voicestudio-desktop'; exe.write_bytes(b'fixture')
asar(self.root / 'resources/app.asar', {'version': '1.2.3-beta.2', 'voicestudioDistribution': 'snap-store'})
with patch.object(application.desktop, 'resolve_desktop', return_value=[str(exe)]), \
patch.object(application.desktop, 'bundled_launcher', return_value=None):
info = application.installed_application()
self.assertEqual(info.version, '1.2.3-beta.2')
self.assertEqual(info.method, 'store')
def test_corrupt_app_metadata_does_not_fall_back_to_package_version(self):
exe = self.root / 'voicestudio-desktop'; exe.write_bytes(b'fixture')
(self.root / 'resources').mkdir()
(self.root / 'resources/app.asar').write_bytes(b'invalid archive')
with patch.object(application.desktop, 'resolve_desktop', return_value=[str(exe)]), \
patch.object(application.desktop, 'bundled_launcher', return_value=None):
with self.assertRaises(CLIError) as exc:
application.installed_application()
self.assertEqual(exc.exception.code, 'app_metadata_error')
def test_legacy_appimage_version_comes_from_its_contents(self):
image = self.root / 'VoiceStudio.AppImage'
image.write_bytes(b'\x7fELF\x02\x01\x01\x00AI\x02' + b'\0' * 53)
def extract(command, **kwargs):
self.assertEqual(command, [str(image), '--appimage-extract', 'resources/app.asar'])
asar(Path(kwargs['cwd']) / 'squashfs-root/resources/app.asar', {'version': '2.3.4'})
return type('Result', (), {'returncode': 0})()
with patch.object(application.subprocess, 'run', side_effect=extract):
info = application.inspect_application(image)
self.assertEqual(info.version, '2.3.4')
self.assertEqual(info.method, 'appimage')
def appimage(self):
path = self.root / 'VoiceStudio.AppImage'
path.write_bytes(b'\x7fELF\x02\x01\x01\x00AI\x02' + b'\0' * 53)
return path
def extractor(self, version):
def extract(command, **kwargs):
asar(Path(kwargs['cwd']) / 'squashfs-root/resources/app.asar', {'version': version})
return type('Result', (), {'returncode': 0})()
return extract
def test_unchanged_appimage_does_not_require_repeated_extraction(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')) as extract:
first = application.inspect_application(image)
with patch.object(application.subprocess, 'run', side_effect=AssertionError('must use cached metadata')):
second = application.inspect_application(image)
self.assertEqual(first, second)
extract.assert_called_once()
def test_replaced_appimage_invalidates_cache_even_with_same_size_and_mtime(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')):
application.inspect_application(image)
stat = image.stat()
replacement = self.root / 'replacement'
replacement.write_bytes(image.read_bytes())
os.utime(replacement, ns=(stat.st_atime_ns, stat.st_mtime_ns))
os.replace(replacement, image)
with patch.object(application.subprocess, 'run', side_effect=self.extractor('2.0.0')) as extract:
self.assertEqual(application.inspect_application(image).version, '2.0.0')
extract.assert_called_once()
def test_corrupt_cache_is_rebuilt(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')):
application.inspect_application(image)
for content in ['{invalid', '[]', '{"schema": 999}', '{"metadata": null}']:
cached = next((self.root / 'cache').glob('appimage-*.json'))
cached.write_text(content)
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')) as extract:
self.assertEqual(application.inspect_application(image).version, '1.2.3')
extract.assert_called_once()
def test_cache_write_failure_does_not_break_version(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')), \
patch.object(application.os, 'replace', side_effect=PermissionError('read-only cache')):
self.assertEqual(application.inspect_application(image).version, '1.2.3')
self.assertFalse(list((self.root / 'cache').glob('.appimage-*')))
def test_failed_extraction_is_not_cached(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', return_value=type('Result', (), {'returncode': 1})()):
with self.assertRaises(ValueError):
application.inspect_application(image)
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')) as extract:
self.assertEqual(application.inspect_application(image).version, '1.2.3')
extract.assert_called_once()
def test_removed_image_does_not_return_cached_version(self):
image = self.appimage()
with patch.object(application.subprocess, 'run', side_effect=self.extractor('1.2.3')):
application.inspect_application(image)
image.unlink()
with self.assertRaises(FileNotFoundError):
application.inspect_application(image)
def test_literal_shell_launcher_is_inspected_without_running_it(self):
exe = self.root / 'native app'; exe.write_bytes(b'fixture')
wrapper = self.root / 'launcher'
wrapper.write_text(f'#!/bin/sh\nexport APP_SETTING=sample\nexec "{exe}" "$@"\n')
with patch.object(application.subprocess, 'run', side_effect=AssertionError('must not run launcher')):
self.assertEqual(application.unwrap_launcher(wrapper), exe)
wrapper.write_text('#!/bin/sh\nexec "$(untrusted-command)"\n')
with self.assertRaises(ValueError):
application.unwrap_launcher(wrapper)
def test_macos_bundle_uses_installed_plist_version(self):
app = self.root / 'VoiceStudio.app'
(app / 'Contents').mkdir(parents=True)
(app / 'Contents/Info.plist').write_bytes(plistlib.dumps({'CFBundleShortVersionString': '3.2.1'}))
asar(app / 'Contents/Resources/app.asar', {'version': '3.2.1'})
self.assertEqual(application.inspect_application(app).version, '3.2.1')
def test_invalid_archive_sizes_are_rejected(self):
archive = self.root / 'app.asar'
for data in [b'', struct.pack('<II', 4, 2**31), struct.pack('<II', 4, 8) + b'\0'*8]:
archive.write_bytes(data)
with self.assertRaises((ValueError, KeyError, json.JSONDecodeError)):
application.asar_package(archive)
def test_bundled_application_metadata_controls_version(self):
manifest = self.root / 'desktop.json'
manifest.write_text(json.dumps({'version': '4.5.6', 'application': '../VoiceStudio.exe',
'method': 'nsis', 'arch': 'x64'}))
with patch.object(application.desktop, 'bundled_launcher', return_value=manifest):
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(application.app_version(), '4.5.6')
if __name__ == '__main__':
unittest.main()
+277
View File
@@ -0,0 +1,277 @@
"""The CLI reaches the desktop app's backend, or starts the app in the background."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import plistlib
import socket
import sys
import threading
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'cli'))
from voicestudio_cli import runtime, desktop
from voicestudio_cli.errors import CLIError
class Backend:
"""A VoiceStudio-shaped HTTP backend on an ephemeral loopback port."""
def __init__(self):
self.requests = []
owner = self
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_GET(self):
owner.requests.append((self.path, self.headers.get('Authorization')))
body = (b'{"status":"ok","version":"1.0.0"}' if self.path == '/health'
else b'[{"id":"p1","name":"Narrator"}]')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(body)))
self.send_header('X-OmniVoice-Backend', '1.0.0')
self.end_headers()
self.wfile.write(body)
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
self.url = f'http://127.0.0.1:{self.server.server_port}'
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def close(self):
self.server.shutdown()
self.server.server_close()
def unused_url():
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
return f'http://127.0.0.1:{sock.getsockname()[1]}'
class Desktop:
"""Stands in for the Electron app: records launches and acts like it."""
def __init__(self, on_launch=None, code=None):
self.launches = []
self.on_launch = on_launch
self.code = code
def __call__(self, arguments, *, detached=False):
self.launches.append((list(arguments), detached))
if self.on_launch:
self.on_launch(arguments)
code = self.code
class Child:
def poll(self):
return code
def wait(self, timeout=None):
return code or 0
return Child()
@pytest.fixture
def home(tmp_path, monkeypatch):
monkeypatch.setenv('VOICESTUDIO_USER_DATA', str(tmp_path / 'user-data'))
monkeypatch.setenv('VOICESTUDIO_CONFIG', str(tmp_path / 'cli.json'))
monkeypatch.setenv('OMNIVOICE_STARTUP_BUDGET_S', '5')
monkeypatch.delenv('VOICESTUDIO_URL', raising=False)
monkeypatch.delenv('OMNIVOICE_API_KEY', raising=False)
monkeypatch.setattr(runtime.time, 'sleep', lambda _s: None)
(tmp_path / 'user-data').mkdir()
backends = []
yield tmp_path, backends
for backend in backends:
backend.close()
def publish(tmp_path, url, **fields):
record = {'schema': 1, 'stage': 'ready', 'url': url, 'pid': 1, 'version': '1.0.0',
'headless': True, 'window': False, 'remote': False, **fields}
(tmp_path / 'user-data/backend.json').write_text(json.dumps(record))
def test_uses_the_published_fallback_port_without_launching(home, monkeypatch):
tmp_path, backends = home
backend = Backend(); backends.append(backend)
publish(tmp_path, backend.url)
launch = Desktop(); monkeypatch.setattr(runtime, 'desktop_process', launch)
client = runtime.LocalClient(unused_url(), '', 5, 'voices list')
assert client.json('GET', '/profiles') == [{'id': 'p1', 'name': 'Narrator'}]
assert launch.launches == []
def test_starts_the_desktop_app_in_the_background_and_waits_for_it(home, monkeypatch):
tmp_path, backends = home
def started(_arguments):
backend = Backend(); backends.append(backend)
publish(tmp_path, backend.url)
launch = Desktop(started); monkeypatch.setattr(runtime, 'desktop_process', launch)
client = runtime.LocalClient(unused_url(), '', 5, 'speak', quiet=True)
assert client.json('GET', '/profiles')[0]['id'] == 'p1'
assert launch.launches == [([desktop.BACKGROUND_FLAG], True)]
@pytest.mark.parametrize('command', ['status', 'models loaded', 'jobs cancel', 'connection test'])
def test_state_queries_never_start_the_app(home, monkeypatch, command):
launch = Desktop(); monkeypatch.setattr(runtime, 'desktop_process', launch)
with pytest.raises(CLIError) as error:
runtime.LocalClient(unused_url(), '', 5, command).health()
assert error.value.code == 'backend_stopped'
assert launch.launches == []
@pytest.mark.parametrize('stage, code', [('setup_required', 'runtime_not_ready'),
('failed', 'backend_failed'), ('port_in_use', 'backend_failed')])
def test_setup_and_startup_failures_are_reported_without_waiting(home, monkeypatch, stage, code):
tmp_path, _ = home
url = unused_url()
launch = Desktop(lambda _a: publish(tmp_path, url, stage=stage))
monkeypatch.setattr(runtime, 'desktop_process', launch)
with pytest.raises(CLIError) as error:
runtime.start_backend(unused_url(), quiet=True)
assert error.value.code == code
def test_a_stale_failure_record_from_a_previous_run_does_not_fail_a_new_start(home, monkeypatch):
tmp_path, backends = home
publish(tmp_path, unused_url(), stage='failed', pid=999)
def started(_arguments):
backend = Backend(); backends.append(backend)
publish(tmp_path, backend.url)
monkeypatch.setattr(runtime, 'desktop_process', Desktop(started))
assert runtime.start_backend(unused_url(), quiet=True).startswith('http://127.0.0.1:')
def test_app_that_exits_during_startup_is_an_error(home, monkeypatch):
monkeypatch.setattr(runtime, 'desktop_process', Desktop(code=1))
with pytest.raises(CLIError) as error:
runtime.start_backend(unused_url(), quiet=True)
assert error.value.code == 'backend_failed'
def test_remote_or_offsite_records_are_never_followed(home, monkeypatch):
tmp_path, _ = home
publish(tmp_path, 'https://studio.example.com', remote=True)
with pytest.raises(CLIError) as error:
runtime.running_backend(unused_url())
assert error.value.code == 'remote_backend'
publish(tmp_path, 'http://example.com:3900')
assert runtime.discovery() is None
def test_saved_credential_stays_with_its_origin(home, monkeypatch):
tmp_path, backends = home
backend = Backend(); backends.append(backend)
publish(tmp_path, backend.url)
client = runtime.LocalClient(unused_url(), 'saved-secret', 5, 'voices list')
client.json('GET', '/profiles')
assert ('/profiles', None) in backend.requests
def test_stop_leaves_an_open_window_and_external_backends_alone(home, monkeypatch):
tmp_path, backends = home
launch = Desktop(); monkeypatch.setattr(runtime, 'desktop_process', launch)
assert runtime.stop_backend(unused_url())['stopped'] is False
backend = Backend(); backends.append(backend)
with pytest.raises(CLIError) as error:
runtime.stop_backend(backend.url)
assert error.value.code == 'not_app_owned'
publish(tmp_path, backend.url, window=True)
with pytest.raises(CLIError) as error:
runtime.stop_backend(unused_url())
assert error.value.code == 'app_open'
assert launch.launches == []
def test_stop_asks_the_background_app_to_quit_and_waits(home, monkeypatch):
tmp_path, _ = home
backend = Backend()
publish(tmp_path, backend.url)
launch = Desktop(lambda _a: backend.close())
monkeypatch.setattr(runtime, 'desktop_process', launch)
assert runtime.stop_backend(unused_url()) == {'stopped': True, 'message': 'VoiceStudio stopped.'}
assert launch.launches == [([desktop.STOP_FLAG], False)]
def test_ownership_switches_reach_the_app_through_the_public_command():
for flag in [desktop.BACKGROUND_FLAG, desktop.STOP_FLAG, desktop.CHECK_UPDATES_FLAG]:
assert desktop.split_arguments([flag]) == ([], [flag])
def test_background_launch_targets_an_executable_that_receives_arguments(tmp_path, monkeypatch):
bundle = tmp_path / 'VoiceStudio.app'
(bundle / 'Contents/MacOS').mkdir(parents=True)
with (bundle / 'Contents/Info.plist').open('wb') as stream:
plistlib.dump({'CFBundleExecutable': 'VoiceStudio'}, stream)
assert desktop._direct_command(['/usr/bin/open', '-a', str(bundle), '--args']) == [
str(bundle / 'Contents/MacOS/VoiceStudio')]
monkeypatch.setattr(sys, 'frozen', True, raising=False)
monkeypatch.setenv('APPIMAGE', '/home/user/Apps/VoiceStudio.AppImage')
assert desktop._direct_command(['/tmp/.mount_x/voicestudio-desktop']) == [
'/home/user/Apps/VoiceStudio.AppImage']
def test_selected_user_data_is_passed_to_the_app(home, monkeypatch):
tmp_path, _ = home
seen = {}
class Popen:
def __init__(self, command, **options):
seen['command'] = command
seen['options'] = options
monkeypatch.setattr(desktop, 'resolve_desktop', lambda: ['/opt/VoiceStudio/voicestudio-desktop'])
monkeypatch.setattr(desktop.subprocess, 'Popen', Popen)
desktop.desktop_process([desktop.BACKGROUND_FLAG], detached=True)
assert seen['command'] == ['/opt/VoiceStudio/voicestudio-desktop', desktop.BACKGROUND_FLAG,
'--user-data-dir=' + str(tmp_path / 'user-data')]
assert seen['options'].get('start_new_session') or os.name == 'nt'
def test_default_connection_respects_the_selected_backend_port(home, monkeypatch):
from voicestudio_cli.config import connection
monkeypatch.setenv('OMNIVOICE_PORT', '14900')
assert connection(None)[0] == 'http://127.0.0.1:14900'
@pytest.mark.parametrize('port', ['-1', '65536', 'invalid', ''])
def test_invalid_backend_port_fails_before_execution(home, monkeypatch, port):
from voicestudio_cli.config import connection
monkeypatch.setenv('OMNIVOICE_PORT', port)
with pytest.raises(CLIError) as error:
connection(None)
assert error.value.code == 'config_error'
def test_explicit_endpoint_ignores_unused_local_port(home, monkeypatch):
from voicestudio_cli.config import connection
monkeypatch.setenv('OMNIVOICE_PORT', 'invalid')
assert connection('https://example.com')[0] == 'https://example.com'
def test_stop_never_targets_an_explicitly_selected_backend(home, monkeypatch, capsys):
from voicestudio_cli.__main__ import main
launch = Desktop(); monkeypatch.setattr(runtime, 'desktop_process', launch)
assert main(['stop', '--url', 'http://127.0.0.1:9', '--json']) == 2
assert json.loads(capsys.readouterr().err)['error']['code'] == 'usage_error'
assert launch.launches == []
def test_stopped_status_is_an_answer_with_exit_code_3(home, monkeypatch, capsys):
from voicestudio_cli.__main__ import main
launch = Desktop(); monkeypatch.setattr(runtime, 'desktop_process', launch)
monkeypatch.setenv('OMNIVOICE_PORT', unused_url().rsplit(':', 1)[1])
assert main(['status']) == 3
assert capsys.readouterr().out.strip() == 'VoiceStudio is not running.'
assert main(['status', '--json']) == 3
assert json.loads(capsys.readouterr().out) == {'running': False, 'message': 'VoiceStudio is not running.'}
assert launch.launches == []
+100
View File
@@ -0,0 +1,100 @@
"""Black-box CLI contracts; no backend, models or third-party packages required."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
class CommandTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
search_path = os.pathsep.join([str(ROOT / 'cli'), str(ROOT / 'tests/cli/network_guard')])
self.env = {**os.environ, 'PYTHONPATH': search_path,
'VOICESTUDIO_CONFIG': str(Path(self.temp.name) / 'config.json'),
'VOICESTUDIO_URL': 'http://127.0.0.1:1',
'HF_HUB_OFFLINE': '1', 'HF_HUB_CACHE': str(Path(self.temp.name) / 'empty-hf')}
self.env.pop('OMNIVOICE_API_KEY', None)
self.app_version = '9.8.7'
app = Path(self.temp.name) / 'app'
(app / 'resources/app').mkdir(parents=True)
(app / 'resources/app/package.json').write_text(json.dumps({'version': self.app_version}))
executable = app / ('VoiceStudio.exe' if os.name == 'nt' else 'voicestudio-desktop')
executable.write_bytes(b'fixture application')
executable.chmod(0o755)
self.env['VOICESTUDIO_DESKTOP_APP'] = str(executable)
def run_cli(self, *args, input=None):
return subprocess.run([sys.executable, '-m', 'voicestudio_cli', *args],
input=input, capture_output=True, env=self.env, timeout=10)
def test_version_aliases_are_offline_and_equal(self):
results = [self.run_cli(*args) for args in [('version',), ('--version',), ('-v',)]]
self.assertTrue(all(r.returncode == 0 for r in results))
self.assertEqual(len({r.stdout for r in results}), 1)
self.assertEqual(results[0].stdout, f'VoiceStudio {self.app_version}\n'.encode())
def test_nested_help(self):
for args in [('--help',), ('voices', '--help'),
('voices', 'reference', '--help'), ('voices', 'clone', '--help'),
('help', 'voices', 'clone'), ('--json', 'help', 'voices', 'reference')]:
with self.subTest(args=args):
r = self.run_cli(*args)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn(b'usage:', r.stdout)
def test_typo_is_not_executed(self):
r = self.run_cli('udpate')
self.assertEqual(r.returncode, 2)
self.assertIn(b'update', r.stderr)
self.assertEqual(r.stdout, b'')
def test_invalid_usage_json(self):
r = self.run_cli('voices', 'show', '--json')
self.assertEqual(r.returncode, 2)
self.assertEqual(json.loads(r.stderr)['error']['code'], 'usage_error')
def test_connection_refused_is_actionable(self):
r = self.run_cli('status', '--json', '--timeout', '0.1')
self.assertEqual(r.returncode, 1)
self.assertEqual(json.loads(r.stderr)['error']['code'], 'connection_error')
self.assertIn(b'Open VoiceStudio', r.stderr)
def test_removed_command_is_unknown(self):
r = self.run_cli('capabilities')
self.assertEqual(r.returncode, 2)
def test_unmanaged_application_updates_give_instructions(self):
r = self.run_cli('update', 'info', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(json.loads(r.stdout)['method'], 'nsis' if os.name == 'nt' else 'directory')
def test_version_and_help_ignore_corrupt_configuration(self):
Path(self.env['VOICESTUDIO_CONFIG']).write_text('{broken')
for args in [('version',), ('version', '--json'), ('--version',), ('voices', '--help'), ('update', 'info')]:
with self.subTest(args=args):
result = self.run_cli(*args)
self.assertEqual(result.returncode, 0, result.stderr)
def test_errors_read_as_sentences_with_one_suggestion(self):
r = self.run_cli('udpate')
self.assertEqual(r.stderr.decode().strip(),
"voicestudio: Unknown command 'udpate'. Did you mean 'update'? Run voicestudio --help.")
r = self.run_cli('settings', 'get', 'compute')
self.assertIn(b"'compute' is not a valid setting. Did you mean 'compute-device'?", r.stderr)
self.assertNotIn(b'?.', r.stderr)
def test_missing_app_is_explained_without_internal_detail(self):
self.env['VOICESTUDIO_DESKTOP_APP'] = str(Path(self.temp.name) / 'missing')
r = self.run_cli('version')
self.assertEqual(r.returncode, 1)
self.assertIn(b"Can't find the VoiceStudio app", r.stderr)
if __name__ == '__main__':
unittest.main()
+120
View File
@@ -0,0 +1,120 @@
"""Tab completion: candidates from the command index, real shell scripts."""
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'cli'))
from voicestudio_cli import completion
from voicestudio_cli.__main__ import RENAMED, build_parser
def names(words):
return [line.split('\t')[0] for line in completion.complete(words)]
def test_top_level_groups_and_commands_with_descriptions():
lines = completion.complete([''])
assert 'voices\tYour saved voices: create, change, share' in lines
assert {'speak', 'status', 'completion'} <= set(names(['']))
def test_completes_prefixes_nested_paths_choices_and_options():
assert names(['vo']) == ['voices']
assert 'reference' in names(['voices', 're'])
assert names(['voices', 'reference', '']) == ['download', 'set']
assert names(['settings', 'get', 'compute']) == ['compute-device']
assert names(['transcribe', 'a.wav', '--format', 's']) == ['srt']
assert '--audio' in names(['voices', 'clone', '--a'])
assert names(['--url', 'http://127.0.0.1:1', 'voices', 'sh']) == ['show', 'show-file']
def test_former_names_and_hidden_options_are_never_offered():
offered = set()
for path in {tuple(name.split()[:-1]) for name in RENAMED}:
offered |= {' '.join([*path, name]) for name in names([*path, ''])}
assert not offered & set(RENAMED)
assert names(['stories', '']) == []
assert names(['update', '']) == [] # update check is a former spelling
def test_values_the_user_types_fall_back_to_files():
assert names(['--url', '']) == []
assert names(['voices', 'clone', '--audio', '']) == []
def test_every_listed_command_is_a_real_command():
_, nodes = build_parser()
commands, groups = completion._index()
for path in [*commands, *groups]:
assert tuple(path.split()) in nodes, path
def test_completion_builds_only_the_command_being_typed(monkeypatch):
built = []
from voicestudio_cli import __main__ as cli
original = cli.build_parser
monkeypatch.setattr(cli, 'build_parser', lambda only=None: built.append(only) or original(only))
names(['voices', ''])
assert built == [] # command names come from the index
names(['voices', 'clone', '--'])
assert built == [('voices', 'clone')]
def test_a_tab_press_is_fast():
started = time.perf_counter()
for words in [[''], ['voices', 'clone', '--'], ['settings', 'get', '']]:
completion.complete(words)
assert time.perf_counter() - started < 1.5
def run_shell(shell, script, env):
return subprocess.run([shell, '-c', script], capture_output=True, text=True, timeout=30, env=env)
@pytest.fixture
def shell_env(tmp_path):
bin_dir = tmp_path / 'bin'
bin_dir.mkdir()
launcher = bin_dir / 'voicestudio'
launcher.write_text(f'#!/bin/sh\nexec "{sys.executable}" -m voicestudio_cli "$@"\n')
launcher.chmod(0o755)
return {**os.environ, 'PATH': f'{bin_dir}{os.pathsep}{os.environ["PATH"]}',
'PYTHONPATH': str(ROOT / 'cli'), 'HOME': str(tmp_path)}
@pytest.mark.skipif(os.name == 'nt' or not shutil.which('bash'), reason='bash is not installed')
def test_bash_script_completes_in_a_real_bash(shell_env):
result = run_shell('bash', 'eval "$(voicestudio completion bash)"; COMP_WORDS=(voicestudio voices re); '
'COMP_CWORD=2; _voicestudio; printf "%s\\n" "${COMPREPLY[@]}"', shell_env)
assert result.returncode == 0, result.stderr
assert result.stdout.split() == ['reference']
@pytest.mark.skipif(not shutil.which('zsh'), reason='zsh is not installed')
def test_zsh_script_loads_and_registers(shell_env):
result = run_shell('zsh', 'eval "$(voicestudio completion zsh)"; print -r -- ${_comps[voicestudio]}', shell_env)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == '_voicestudio'
@pytest.mark.skipif(not shutil.which('fish'), reason='fish is not installed')
def test_fish_script_completes_in_a_real_fish(shell_env):
result = run_shell('fish', 'voicestudio completion fish | source; complete -C "voicestudio voices re"', shell_env)
assert result.returncode == 0, result.stderr
assert result.stdout.startswith('reference')
@pytest.mark.skipif(not shutil.which('pwsh'), reason='PowerShell is not installed')
def test_powershell_script_registers(shell_env):
result = subprocess.run(['pwsh', '-NoProfile', '-Command',
'voicestudio completion powershell | Out-String | Invoke-Expression; '
'(TabExpansion2 "voicestudio voices re" 21).CompletionMatches.CompletionText'],
capture_output=True, text=True, timeout=60, env=shell_env)
assert result.returncode == 0, result.stderr
assert 'reference' in result.stdout.split()
+97
View File
@@ -0,0 +1,97 @@
import importlib.util
import json
from pathlib import Path
import re
import sys
import unittest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'cli'))
from voicestudio_cli.__main__ import SETTINGS, build_parser
from voicestudio_cli.registry import COMMANDS
class ContractTests(unittest.TestCase):
def test_request_contract_has_not_drifted(self):
spec = importlib.util.spec_from_file_location('cli_contract_export', ROOT / 'scripts/export_cli_contract.py')
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
self.assertEqual(module.build_contract(), json.loads((ROOT / 'cli/voicestudio_cli/contracts.json').read_text()))
def test_upload_fields_match_real_backend_openapi(self):
contracts = json.loads((ROOT / 'cli/voicestudio_cli/contracts.json').read_text())
for command in COMMANDS:
if command.upload and command.upload != '@raw':
with self.subTest(command=command.name):
self.assertIn(command.upload, contracts[command.name]['fields'])
def test_settings_write_fields_match_backend(self):
schema = json.loads((ROOT / 'mobile/contract/openapi.json').read_text())
for route, field in SETTINGS.values():
with self.subTest(route=route):
body = schema['paths']['/api/settings/' + route]['put']['requestBody']['content']['application/json']['schema']
body = schema['components']['schemas'][body['$ref'].rsplit('/', 1)[-1]]
self.assertIn(field, body['properties'])
def test_no_duplicate_registered_commands(self):
names = [command.name for command in COMMANDS]
self.assertEqual(len(set(names)), len(names))
def test_help_includes_inherited_options_and_transport_description(self):
_, nodes = build_parser()
for command in COMMANDS:
with self.subTest(command=command.name):
text = nodes[tuple(command.name.split())].format_help()
for flag in ['--url', '--json', '--help', '--timeout']:
self.assertIn(flag, text)
def test_every_command_and_group_is_described_for_people(self):
_, nodes = build_parser()
for key, parser in nodes.items():
if not key:
continue
name = ' '.join(key)
with self.subTest(command=name):
text = parser.description or ''
self.assertNotIn(text.lower(), {name.lower(), key[-1].lower(), f'{key[-1]} commands'})
self.assertNotRegex(text, r'^[A-Z][a-z]+: ', 'placeholder "Group: name" description')
self.assertNotIn('--file JSON', text, 'input format belongs to the --file help')
def test_no_help_lists_an_empty_commands_section(self):
_, nodes = build_parser()
for path, parser in nodes.items():
text = parser.format_help()
with self.subTest(command=' '.join(path)):
if 'Commands:' in text:
self.assertRegex(text.split('Commands:', 1)[1], r'\n\s+[a-z][\w-]*\s')
else:
self.assertNotIn('COMMAND', text.splitlines()[0])
def test_help_hides_options_that_do_nothing(self):
_, nodes = build_parser()
for path, hidden in [(('stop',), ['--url', '--timeout', '--output', '--yes']),
(('version',), ['--url', '--output']),
(('voices',), ['--url', '--json']),
(('voices', 'list'), ['--yes'])]:
with self.subTest(path=path):
text = nodes[path].format_help()
for flag in hidden:
self.assertNotIn(flag, text)
self.assertIn('--yes', nodes[('voices', 'delete')].format_help())
def test_renamed_commands_keep_their_former_names_working_but_unlisted(self):
from voicestudio_cli.__main__ import RENAMED, HIDDEN
root, nodes = build_parser()
for former, current in RENAMED.items():
with self.subTest(former=former):
self.assertEqual(nodes[tuple(former.split())].get_default('handler'),
nodes[tuple(current.split())].get_default('handler'))
parent = nodes[tuple(former.split()[:-1])].format_help()
self.assertNotRegex(parent, rf'\n\s+{re.escape(former.split()[-1])}\s')
for former in HIDDEN:
self.assertNotRegex(nodes[tuple(former.split()[:-1])].format_help(),
rf'\n\s+{re.escape(former.split()[-1])}\s')
self.assertNotIn('stories', root.format_help().split('Commands:')[1].split())
if __name__ == '__main__':
unittest.main()
+238
View File
@@ -0,0 +1,238 @@
"""Desktop dispatch and migration use fixture executables, never the installed app."""
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from io import StringIO
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'cli'))
from voicestudio_cli import desktop, install, updates
from voicestudio_cli.__main__ import main
from voicestudio_cli.errors import CLIError
def _symlink_or_skip(test, link, target):
"""Windows needs Developer Mode or elevation to create symlinks; skip, never error."""
try:
link.symlink_to(target)
except (OSError, NotImplementedError) as exc:
test.skipTest(f'symlinks unavailable in this environment: {exc}')
class DesktopTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.env = patch.dict(os.environ, {
'VOICESTUDIO_CONFIG': str(self.root / 'config.json'),
'VOICESTUDIO_DESKTOP_APP': str(self.root / 'missing'),
})
self.env.start()
self.addCleanup(self.env.stop)
def executable(self, name='desktop'):
path = self.root / name
path.write_text('#!/bin/sh\nexit 0\n')
path.chmod(0o755)
return path
def test_empty_arguments_launch_desktop_without_backend_or_config(self):
(self.root / 'config.json').write_text('{broken')
with patch('voicestudio_cli.__main__.launch_desktop', return_value=0) as launch:
self.assertEqual(main([]), 0)
launch.assert_called_once_with([])
def test_commands_never_launch_gui(self):
with patch('voicestudio_cli.__main__.launch_desktop') as launch, \
patch('voicestudio_cli.__main__.app_version', return_value='9.8.7'):
self.assertEqual(main(['version']), 0)
self.assertEqual(main(['voices']), 0)
self.assertEqual(main(['udpate']), 2)
launch.assert_not_called()
def test_snap_switch_does_not_turn_cli_help_into_gui_launch(self):
self.assertEqual(desktop.split_arguments(['--no-sandbox', '--help']), (['--help'], ['--no-sandbox']))
self.assertEqual(desktop.split_arguments(['--ozone-platform', 'wayland']),
([], ['--ozone-platform', 'wayland']))
self.assertEqual(desktop.split_arguments(['voices', '--no-sandbox']),
(['voices', '--no-sandbox'], []))
with self.assertRaises(CLIError):
desktop.split_arguments(['--user-data-dir'])
def test_explicit_missing_app_does_not_fall_back_to_real_app(self):
with patch.object(desktop, 'desktop_candidates', side_effect=AssertionError('must not discover')):
with self.assertRaises(CLIError) as error:
desktop.resolve_desktop()
self.assertEqual(error.exception.code, 'desktop_not_found')
def test_linux_installer_location_is_discovered(self):
path = self.root / '.local/bin/VoiceStudio'
path.parent.mkdir(parents=True)
path.write_text('#!/bin/sh\nexit 0\n')
path.chmod(0o755)
os.environ.pop('VOICESTUDIO_DESKTOP_APP')
with patch.object(Path, 'home', return_value=self.root), patch.object(sys, 'platform', 'linux'):
with patch.object(desktop.shutil, 'which', return_value=None):
self.assertEqual(desktop.resolve_desktop(), [str(path)])
def test_launch_preserves_environment_and_uses_argument_array(self):
path = self.executable('app with spaces')
with patch.dict(os.environ, {'VOICESTUDIO_DESKTOP_APP': str(path), 'CLI_TEST_SETTING': 'value with spaces'}):
with patch.object(desktop.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as run:
self.assertEqual(desktop.launch_desktop(['--user-data-dir', 'profile with spaces']), 0)
self.assertEqual(run.call_args.args[0], [str(path), '--user-data-dir', 'profile with spaces'])
self.assertEqual(run.call_args.kwargs['env']['CLI_TEST_SETTING'], 'value with spaces')
def test_launch_failure_is_actionable(self):
with patch.object(desktop, 'resolve_desktop', return_value=['fixture']):
with patch.object(desktop.subprocess, 'run', side_effect=OSError('permission denied')):
with self.assertRaises(CLIError) as error:
desktop.launch_desktop()
self.assertEqual(error.exception.code, 'desktop_launch_failed')
with patch.object(desktop.subprocess, 'run', return_value=subprocess.CompletedProcess([], 7)):
with self.assertRaisesRegex(CLIError, 'status 7'):
desktop.launch_desktop()
def test_saved_wrapper_and_frozen_manifest(self):
os.environ.pop('VOICESTUDIO_DESKTOP_APP')
path = self.executable()
desktop.launcher_config().write_text(json.dumps({'executable': str(path)}))
self.assertEqual(desktop.resolve_desktop(), [str(path)])
frozen = self.executable('voicestudio')
frozen.with_name('desktop.json').write_text(json.dumps({'executable': 'desktop', 'application': 'desktop',
'version': '9.8.7', 'method': 'directory', 'arch': 'x64'}))
with patch.object(sys, 'frozen', True, create=True), patch.object(sys, 'executable', str(frozen)):
self.assertEqual(desktop.resolve_desktop(), [str(path)])
self.assertEqual(updates.install_info()['version'], '9.8.7')
frozen.with_name('desktop.json').write_text(json.dumps({'executable': 'voicestudio'}))
with self.assertRaisesRegex(CLIError, 'back to the CLI'):
desktop.resolve_desktop()
def test_frozen_launch_restores_system_library_environment(self):
with patch.object(sys, 'frozen', True, create=True), patch.object(sys, 'platform', 'linux'):
with patch.dict(os.environ, {'LD_LIBRARY_PATH': '/frozen', 'LD_LIBRARY_PATH_ORIG': '/system'}):
with patch.object(desktop, 'resolve_desktop', return_value=['fixture']):
with patch.object(desktop.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as run:
desktop.launch_desktop()
env = run.call_args.kwargs['env']
self.assertEqual(env['LD_LIBRARY_PATH'], '/system')
self.assertNotIn('LD_LIBRARY_PATH_ORIG', env)
self.assertEqual(env['PYINSTALLER_RESET_ENVIRONMENT'], '1')
def test_macos_app_bundle_uses_open(self):
app = self.root / 'VoiceStudio.app'
app.mkdir()
with patch.dict(os.environ, {'VOICESTUDIO_DESKTOP_APP': str(app)}), patch.object(sys, 'platform', 'darwin'):
self.assertEqual(desktop.resolve_desktop(), ['/usr/bin/open', '-a', str(app), '--args'])
class InstallTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.bin = self.root / 'bin'
self.bin.mkdir()
self.target = self.bin / ('voicestudio.exe' if sys.platform == 'win32' else 'voicestudio')
self.wrapper = b'#!/bin/sh\nexport CLI_TEST_SETTING="value with spaces"\nexec /opt/example/app "$@"\n'
self.env = patch.dict(os.environ, {'VOICESTUDIO_CONFIG': str(self.root / 'config/config.json')})
self.env.start()
self.addCleanup(self.env.stop)
self.query = patch.object(install.subprocess, 'check_output', side_effect=[str(self.bin) + '\n', ''])
self.query.start()
self.addCleanup(self.query.stop)
def test_refuses_collision_without_explicit_replacement(self):
self.target.write_bytes(self.wrapper)
with patch.object(install.subprocess, 'run') as run:
with self.assertRaises(CLIError):
install.install('./cli')
run.assert_not_called()
self.assertEqual(self.target.read_bytes(), self.wrapper)
def test_replacement_preserves_wrapper_and_configuration(self):
self.target.write_bytes(self.wrapper)
self.target.chmod(0o755)
output = StringIO()
with patch.object(install.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as run:
with redirect_stdout(output):
install.install('./cli', replace_launcher=True)
self.assertEqual(run.call_args_list[0].args[0], ['uv', 'tool', 'install', '--force', './cli'])
self.assertEqual(run.call_args_list[1].args[0], ['uv', 'tool', 'update-shell'])
manifest = json.loads(desktop.launcher_config().read_text())
backup = Path(manifest['executable'])
self.assertEqual(backup.read_bytes(), self.wrapper)
self.assertTrue(os.access(backup, os.X_OK))
self.assertEqual(output.getvalue().splitlines(), [f'Installed command: {self.target}'])
def test_fresh_install_reports_the_installed_command(self):
output = StringIO()
with patch.object(install.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)):
with redirect_stdout(output):
install.install('./cli', update_shell=False)
self.assertEqual(output.getvalue().splitlines(), [f'Installed command: {self.target}'])
def test_failed_fresh_install_does_not_claim_a_launcher_was_restored(self):
with patch.object(install.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'uv')):
with self.assertRaises(CLIError) as error:
install.install('./cli', update_shell=False)
self.assertEqual(str(error.exception), 'CLI installation failed.')
def test_path_warning_is_reported_only_when_shell_configuration_fails(self):
with patch.object(install.subprocess, 'run', side_effect=[subprocess.CompletedProcess([], 0),
subprocess.CompletedProcess([], 1)]):
with patch.object(sys, 'stderr', new_callable=StringIO) as errors, redirect_stdout(StringIO()):
install.install('./cli')
self.assertIn(str(self.bin), errors.getvalue())
self.assertIn('PATH configuration failed', errors.getvalue())
def test_failed_install_restores_wrapper_and_config(self):
self.target.write_bytes(self.wrapper)
self.target.chmod(0o755)
desktop.launcher_config().parent.mkdir()
desktop.launcher_config().write_text('{"executable": "previous"}')
def fail(*args, **kwargs):
self.target.write_text('damaged replacement')
raise subprocess.CalledProcessError(1, args)
with patch.object(install.subprocess, 'run', side_effect=fail):
with self.assertRaises(CLIError):
install.install('./cli', replace_launcher=True)
self.assertEqual(self.target.read_bytes(), self.wrapper)
self.assertEqual(json.loads(desktop.launcher_config().read_text()), {'executable': 'previous'})
self.assertFalse(desktop.launcher_config().with_name('desktop-launcher').exists())
def test_symlink_migration_keeps_real_desktop_in_place(self):
app = self.root / 'VoiceStudio'
app.write_bytes(b'fixture native desktop')
_symlink_or_skip(self, self.target, app)
with patch.object(install.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)):
install.install('./cli', replace_launcher=True, update_shell=False)
self.assertEqual(json.loads(desktop.launcher_config().read_text())['executable'], str(app))
self.assertEqual(app.read_bytes(), b'fixture native desktop')
def test_native_binary_is_not_moved_away_from_its_resources(self):
self.target.write_bytes(b'MZ native executable')
with patch.object(install.subprocess, 'run') as run:
with self.assertRaises(CLIError):
install.install('./cli', replace_launcher=True)
run.assert_not_called()
self.assertEqual(self.target.read_bytes(), b'MZ native executable')
def test_other_cli_symlink_cannot_be_saved_as_a_recursive_desktop_launcher(self):
other = self.root / 'other-cli'
other.write_bytes(b'#!/usr/bin/python\nfrom voicestudio_cli.__main__ import main\nmain()\n')
_symlink_or_skip(self, self.target, other)
with patch.object(install.subprocess, 'run') as run:
with self.assertRaises(CLIError):
install.install('./cli', replace_launcher=True)
run.assert_not_called()
if __name__ == '__main__':
unittest.main()
+410
View File
@@ -0,0 +1,410 @@
"""Real subprocess/HTTP tests, with an independently controlled service."""
import contextlib
from email import policy
from email.parser import BytesParser
import io
import json
from pathlib import Path
import queue
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import unittest
from urllib.parse import urlsplit, parse_qs
import test_cli as base
ROOT = base.ROOT
sys.path.insert(0, str(ROOT / 'cli'))
from voicestudio_cli.registry import COMMANDS
from voicestudio_cli.__main__ import build_parser
class Server(ThreadingHTTPServer):
daemon_threads = True
class HTTPTests(base.CommandTests):
@classmethod
def setUpClass(cls):
cls.requests = queue.Queue()
cls.response = (200, 'application/json', b'{"ok":true}', {})
cls.health = True
class Handler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def log_message(self, *args):
pass
def handle_request(self):
path = urlsplit(self.path).path
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
if path == '/health':
status, ct, data, headers = (200, 'application/json', b'{"status":"ok","version":"0.5.7"}', {})
if not cls.health:
data = b'{"status":"ok","version":"unrelated"}'
elif path == '/profiles' and self.command == 'GET':
status, ct, data, headers = 200, 'application/json', b'[{"id":"p1","name":"Narrator"}]', {}
elif path in cls.routes:
cls.requests.put((self.command, self.path, dict(self.headers), body))
status, ct, data, headers = cls.routes[path]
else:
cls.requests.put((self.command, self.path, dict(self.headers), body))
status, ct, data, headers = cls.response
self.send_response(status)
self.send_header('Content-Type', ct)
self.send_header('Content-Length', str(len(data)))
if cls.health:
self.send_header('X-OmniVoice-Backend', '0.5.7')
for key, val in headers.items():
self.send_header(key, val)
self.end_headers()
with contextlib.suppress(BrokenPipeError, ConnectionResetError):
self.wfile.write(data)
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_request
cls.server = Server(('127.0.0.1', 0), Handler)
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.thread.start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown(); cls.server.server_close(); cls.thread.join()
def setUp(self):
super().setUp()
self.env['VOICESTUDIO_URL'] = f'http://127.0.0.1:{self.server.server_port}'
type(self).health = True
type(self).routes = {}
type(self).response = (200, 'application/json', b'{"ok":true}', {})
while not self.requests.empty():
self.requests.get_nowait()
# The inherited refusal test needs an intentionally disconnected target.
def test_connection_refused_is_actionable(self):
self.env['VOICESTUDIO_URL'] = 'http://127.0.0.1:1'
super().test_connection_refused_is_actionable()
def test_all_registered_command_help(self):
root, nodes = build_parser()
for path, parser in nodes.items():
with self.subTest(path=path), contextlib.redirect_stdout(io.StringIO()):
with self.assertRaises(SystemExit) as exit:
root.parse_args([*path, '--help'])
self.assertEqual(exit.exception.code, 0)
self.assertIn('usage:', parser.format_help())
def test_registry_success_and_http_failures(self):
"""Every declarative command traverses the real parser, HTTP client and output handler."""
contracts = json.loads((ROOT / 'cli/voicestudio_cli/contracts.json').read_text())
_, nodes = build_parser()
for spec in COMMANDS:
parser = nodes[tuple(spec.name.split())]
if parser.get_default('spec') != spec:
continue # A custom handler has dedicated tests instead.
with self.subTest(command=spec.name):
args = spec.name.split() + ['value'] * len(spec.params)
sample = Path(self.temp.name) / 'input.wav'
sample.write_bytes(b'RIFF-test-input')
if spec.upload:
args.append(str(sample))
contract = contracts.get(spec.name, {})
fields = {k: 'example' for k in contract.get('required', []) if k != spec.upload}
for k, v in fields.items():
args += ['--field', f'{k}={v}']
for k in contract.get('required_query', []):
args += ['--query', f'{k}=example']
if spec.destructive:
args.append('--yes')
output = Path(self.temp.name) / 'result.bin'
output.unlink(missing_ok=True)
if spec.binary:
args += ['-o', str(output)]
type(self).response = (200, 'audio/wav', b'RIFF-output', {})
elif spec.stream:
type(self).response = (200, 'text/event-stream', b'data: {"type":"done"}\n\n', {})
else:
type(self).response = (200, 'application/json', b'{"ok":true}', {})
result = self.run_cli(*args, '--json')
self.assertEqual(result.returncode, 0, result.stderr)
if spec.name == 'voices list':
continue
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual(method, spec.method)
self.assertEqual(urlsplit(path).path, spec.route.format(**{p: 'value' for p in spec.params}))
if spec.binary:
self.assertEqual(output.read_bytes(), b'RIFF-output')
output.unlink()
type(self).response = (409, 'application/json', b'{"detail":"operation conflict"}', {})
result = self.run_cli(*args, '--json')
self.assertEqual(result.returncode, 1, result.stdout)
self.assertEqual(json.loads(result.stderr)['error']['code'], 'conflict')
self.requests.get(timeout=1)
def test_http_error_matrix(self):
for status, code in [(400, 'backend_error'), (401, 'authentication_error'), (403, 'permission_denied'),
(404, 'not_found'), (409, 'conflict'), (422, 'validation_error'),
(429, 'rate_limited'), (500, 'backend_error'), (503, 'backend_error')]:
with self.subTest(status=status):
type(self).response = (status, 'application/json', b'{"detail":{"message":"failed"}}', {'Retry-After': '3'})
r = self.run_cli('engines', 'list', '--json')
err = json.loads(r.stderr)['error']
self.assertEqual(r.returncode, 1)
self.assertEqual((err['code'], err['status'], err['retry_after']), (code, status, '3'))
self.assertEqual(r.stdout, b'')
def test_wrong_service_never_receives_mutation(self):
type(self).health = False
r = self.run_cli('projects', 'rename', '123', 'New name', '--json')
self.assertEqual(json.loads(r.stderr)['error']['code'], 'wrong_service')
self.assertTrue(self.requests.empty())
def test_speak_sends_selected_voice_and_engine_without_global_change(self):
type(self).response = (200, 'audio/wav', b'RIFF-generation', {})
output = Path(self.temp.name) / 'speech.wav'
r = self.run_cli('speak', 'Hello', '--voice', 'Narrator', '--engine', 'kitten', '-o', str(output))
self.assertEqual(r.returncode, 0, r.stderr)
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual((method, path), ('POST', '/generate'))
form = BytesParser(policy=policy.default).parsebytes(
('Content-Type: ' + headers['Content-Type'] + '\r\n\r\n').encode() + body)
fields = {part.get_param('name', header='content-disposition'): part.get_content() for part in form.iter_parts()}
self.assertIn('p1', str(fields['profile_id']))
self.assertIn('kitten', str(fields['engine']))
self.assertEqual(output.read_bytes(), b'RIFF-generation')
self.assertTrue(self.requests.empty())
def test_transcription_upload_and_text_output(self):
audio = Path(self.temp.name) / 'my recording.wav'; audio.write_bytes(b'RIFF-audio')
type(self).response = (200, 'text/plain', b'Hello world', {})
r = self.run_cli('transcribe', str(audio), '--format', 'text')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout, b'Hello world\n')
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual((method, path), ('POST', '/v1/audio/transcriptions'))
self.assertIn(b'RIFF-audio', body)
self.assertIn(b'my recording.wav', body)
def test_form_contract_rejects_missing_fields_before_http(self):
audio = Path(self.temp.name) / 'clip.wav'; audio.write_bytes(b'RIFF')
r = self.run_cli('gallery', 'import', str(audio), '--json')
self.assertEqual(r.returncode, 2)
self.assertIn('name', json.loads(r.stderr)['error']['message'])
self.assertTrue(self.requests.empty())
def test_delete_requires_confirmation_without_http(self):
r = self.run_cli('history', 'clear', '--json')
self.assertEqual(r.returncode, 1)
self.assertEqual(json.loads(r.stderr)['error']['code'], 'confirmation_required')
self.assertTrue(self.requests.empty())
def test_redirect_is_not_followed(self):
type(self).response = (302, 'text/plain', b'', {'Location': '/redirect-target'})
r = self.run_cli('engines', 'list', '--json')
self.assertEqual(json.loads(r.stderr)['error']['code'], 'redirect_refused')
self.assertEqual(self.requests.qsize(), 1)
def test_malformed_json(self):
type(self).response = (200, 'application/json', b'{bad', {})
r = self.run_cli('engines', 'list', '--json')
self.assertEqual(json.loads(r.stderr)['error']['code'], 'invalid_response')
def test_stream_error_after_200_is_failure(self):
payload = Path(self.temp.name) / 'plan.json'; payload.write_text('{"chapters":[]}')
type(self).response = (200, 'text/event-stream', b'data: {"type":"error","detail":"model failed"}\n\n', {})
r = self.run_cli('stories', 'render', '--file', str(payload), '--json')
self.assertEqual(r.returncode, 1)
self.assertEqual(json.loads(r.stderr)['error']['message'], 'model failed')
def test_stream_without_completion_is_failure(self):
type(self).response = (200, 'application/x-ndjson', b'{"type":"progress","percent":20}\n', {})
r = self.run_cli('stories', 'render', '--field', 'chapters=[]', '--json')
self.assertEqual(r.returncode, 1)
self.assertIn(b'completion', r.stderr)
def test_engine_selection_and_supported_model_are_persisted_explicitly(self):
for family, engine, model in [('tts', 'mlx-audio', 'kokoro'), ('asr', 'faster-whisper', 'Systran/faster-whisper-small')]:
with self.subTest(family=family):
r = self.run_cli('engines', 'select', engine, '--type', family, '--model', model)
self.assertEqual(r.returncode, 0, r.stderr)
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual((method, path), ('POST', '/engines/select'))
self.assertEqual(json.loads(body), {'family': family, 'backend_id': engine, 'model_id': model})
r = self.run_cli('engines', 'select', 'argos', '--type', 'translation')
self.assertEqual(r.returncode, 0, r.stderr)
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual((path, json.loads(body)), ('/engines/translation/select', {'engine_id': 'argos'}))
def test_settings_fields_and_typed_values(self):
for key, value, field in [('compute-device', 'cpu', 'value'), ('performance-profile', 'balanced', 'tier'),
('history-retention', '100', 'cap'), ('pause-fill', 'silence', 'mode')]:
with self.subTest(key=key):
r = self.run_cli('settings', 'set', key, value)
self.assertEqual(r.returncode, 0, r.stderr)
method, path, headers, body = self.requests.get(timeout=1)
expected = 100 if key == 'history-retention' else value
self.assertEqual(json.loads(body), {field: expected})
self.assertEqual(method, 'PUT')
def test_model_library_installed_filter(self):
type(self).response = (200, 'application/json', json.dumps({'models': [
{'repo_id': 'owner/one', 'installed': True}, {'repo_id': 'owner/two', 'installed': False}]}).encode(), {})
r = self.run_cli('models', 'list', '--installed', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual([m['repo_id'] for m in json.loads(r.stdout)['models']], ['owner/one'])
def test_model_install_requires_separate_license_acceptance(self):
type(self).routes = {
'/models': (200, 'application/json', b'{"models":[{"repo_id":"owner/model","installed":false,"supported":true}]}', {}),
'/models/licenses/acceptance/owner%2Fmodel': (200, 'application/json', b'{"required":true,"accepted":false,"fingerprint":"v2:example"}', {}),
'/models/licenses/details/owner%2Fmodel': (200, 'application/json', b'{"license":"Read these terms"}', {}),
}
r = self.run_cli('models', 'install', 'owner/model', '--json', '--yes')
self.assertEqual(r.returncode, 1)
self.assertIn(b'license_required', r.stderr)
paths = [self.requests.get_nowait()[1] for _ in range(self.requests.qsize())]
self.assertNotIn('/models/install', paths)
r = self.run_cli('models', 'install', 'owner/model', '--accept-license', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
requests = [self.requests.get_nowait() for _ in range(self.requests.qsize())]
self.assertEqual([r[1] for r in requests][-2:], ['/models/licenses/accept', '/models/install'])
self.assertEqual(json.loads(requests[-2][3])['fingerprint'], 'v2:example')
def test_existing_output_prevents_generation(self):
output = Path(self.temp.name) / 'speech.wav'; output.write_bytes(b'original')
r = self.run_cli('speak', 'Hi', '--voice', 'Narrator', '-o', str(output), '--json')
self.assertEqual(r.returncode, 1)
self.assertEqual(output.read_bytes(), b'original')
self.assertTrue(self.requests.empty())
def test_custom_http_command_success_contracts(self):
clip = Path(self.temp.name) / 'reference.wav'; clip.write_bytes(b'RIFF-reference')
cases = [
(['voices', 'clone', '--name', 'New', '--audio', str(clip)], 'POST', '/profiles'),
(['voices', 'describe', 'female'], 'POST', '/design/describe'),
(['voices', 'consent', 'show', 'p1'], 'GET', '/profiles/p1'),
(['history', 'star', 'h1'], 'PUT', '/history/h1/starred'),
(['history', 'unstar', 'h1'], 'PUT', '/history/h1/starred'),
(['models', 'install-cancel', 'owner/model'], 'POST', '/models/install/cancel'),
(['engines', 'install', 'gpt-sovits', '--type', 'tts'], 'POST', '/engines/sidecar/gpt-sovits/install'),
(['engines', 'install-status', 'gpt-sovits', '--type', 'tts'], 'GET', '/engines/sidecar/gpt-sovits/install/status'),
(['settings', 'get', 'compute-device'], 'GET', '/api/settings/compute-device'),
(['integrations', 'mcp', 'bindings', 'set', 'agent', '--voice', 'p1'], 'PUT', '/api/mcp/bindings'),
(['projects', 'rename', 'p1', 'New name'], 'PATCH', '/projects/p1'),
]
for args, method, path in cases:
with self.subTest(args=args):
r = self.run_cli(*args, '--json')
self.assertEqual(r.returncode, 0, r.stderr)
actual = self.requests.get(timeout=1)
self.assertEqual(actual[:2], (method, path))
type(self).response = (403, 'application/json', b'{"detail":"access refused"}', {})
r = self.run_cli(*args, '--json')
self.assertEqual(r.returncode, 1, r.stdout)
self.assertEqual(json.loads(r.stderr)['error']['code'], 'permission_denied')
self.requests.get(timeout=1)
type(self).response = (200, 'application/json', b'{"ok":true}', {})
def test_voice_design_maps_description_to_profile_fields(self):
type(self).routes = {'/design/describe': (200, 'application/json',
b'{"attrs":{"Gender":"female"},"instruct":"female","matched":[{}]}', {})}
r = self.run_cli('voices', 'design', '--name', 'Designed', '--description', 'female', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
requests = [self.requests.get_nowait() for _ in range(self.requests.qsize())]
self.assertEqual([r[1] for r in requests], ['/design/describe', '/profiles'])
self.assertIn(b'vd_states', requests[-1][3])
self.assertIn(b'female', requests[-1][3])
def test_cli_only_configuration_and_mcp_exports_are_offline(self):
for args in [('connection', 'show'), ('integrations', 'api', 'docs'),
('integrations', 'mcp', 'config'), ('integrations', 'mcp', 'config', '--client', 'codex')]:
with self.subTest(args=args):
r = self.run_cli(*args)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(self.requests.empty())
def test_credentialed_configuration_does_not_echo_secrets(self):
r = self.run_cli('connection', 'auth', 'set', '--stdin', '--json', input=b'secret-from-stdin')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn(b'secret-from-stdin', r.stdout + r.stderr)
r = self.run_cli('connection', 'auth', 'clear', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
def test_bad_json_and_unknown_fields_never_send_request(self):
bad = Path(self.temp.name) / 'bad.json'; bad.write_text('{broken')
for args in [('projects', 'create', '--file', str(bad)),
('projects', 'create', '--field', 'name=Name', '--field', 'state={}', '--field', 'typo=true')]:
with self.subTest(args=args):
r = self.run_cli(*args, '--json')
self.assertEqual(r.returncode, 2, r.stderr)
self.assertTrue(self.requests.empty())
def test_hf_token_input_is_not_reflected_in_backend_errors(self):
type(self).response = (400, 'application/json', b'{"detail":"bad secret-hf-input"}', {})
result = self.run_cli('settings', 'hf-token', 'set', '--stdin', '--json', input=b'secret-hf-input')
self.assertEqual(result.returncode, 1)
self.assertNotIn(b'secret-hf-input', result.stderr)
self.assertEqual(json.loads(result.stderr)['error']['code'], 'backend_error')
def test_people_get_readable_text_and_scripts_get_json(self):
r = self.run_cli('connection', 'show')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn(b'URL:', r.stdout)
self.assertIn(b'Authenticated: no', r.stdout)
self.assertFalse(r.stdout.startswith(b'{'))
self.assertIn('url', json.loads(self.run_cli('connection', 'show', '--json').stdout))
r = self.run_cli('status')
self.assertEqual(r.stdout.strip(), f'VoiceStudio 0.5.7 is running at {self.env["VOICESTUDIO_URL"]}.'.encode())
self.assertTrue(json.loads(self.run_cli('status', '--json').stdout)['running'])
def test_settings_get_without_a_name_shows_every_setting(self):
type(self).routes = {'/api/settings/' + route: (200, 'application/json', json.dumps({field: 'v-' + key}).encode(), {})
for key, (route, field) in __import__('voicestudio_cli.__main__', fromlist=['SETTINGS']).SETTINGS.items()}
r = self.run_cli('settings', 'get', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
values = json.loads(r.stdout)
self.assertEqual(values['compute-device'], 'v-compute-device')
self.assertEqual(len(values), 6)
self.assertIn(b'Pause fill:', self.run_cli('settings', 'get').stdout)
def test_connection_set_is_local_and_respects_flag_precedence(self):
r = self.run_cli('connection', 'set', 'https://saved.example', '--json')
self.assertEqual(r.returncode, 0, r.stderr)
# Environment still wins over the saved URL.
r = self.run_cli('connection', 'show', '--json')
self.assertEqual(json.loads(r.stdout)['source'], 'environment')
r = self.run_cli('connection', 'show', '--url', 'https://explicit.example', '--json')
self.assertEqual(json.loads(r.stdout)['url'], 'https://explicit.example')
self.assertTrue(self.requests.empty())
def test_generic_upload_from_stdin_preserves_audio_bytes(self):
result = self.run_cli('gallery', 'import', '-', '--stdin-filename', 'clip.wav', '--field', 'name=From stdin', input=b'RIFF-stdin-audio')
self.assertEqual(result.returncode, 0, result.stderr)
method, path, headers, body = self.requests.get(timeout=1)
self.assertEqual((method, path), ('POST', '/gallery/upload'))
self.assertIn(b'RIFF-stdin-audio', body)
def test_metadata_output_flag_writes_the_actual_result(self):
target = Path(self.temp.name) / 'status.json'
result = self.run_cli('status', '-o', str(target), '--json')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(target.read_text())['status'], 'ok')
def test_metadata_output_to_stdout_is_not_silent(self):
result = self.run_cli('version', '-o', '-', '--json')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('version', json.loads(result.stdout))
def test_text_output_does_not_add_a_second_newline(self):
audio = Path(self.temp.name) / 'audio.wav'; audio.write_bytes(b'RIFF')
type(self).response = (200, 'text/plain', 'café\n'.encode(), {})
result = self.run_cli('transcribe', str(audio))
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, 'café\n'.encode())
def test_invalid_response_encoding_is_a_backend_error(self):
audio = Path(self.temp.name) / 'audio.wav'; audio.write_bytes(b'RIFF')
type(self).response = (200, 'text/plain', b'\xff', {})
result = self.run_cli('transcribe', str(audio), '--json')
self.assertEqual(result.returncode, 1)
self.assertEqual(json.loads(result.stderr)['error']['code'], 'invalid_response')
if __name__ == '__main__':
unittest.main()
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more