fix(cli): address review findings on the terminal command

- Background launches keep the launcher's switches, so Snap's
  --no-sandbox reaches Electron and the app can start confined.
- A crashed backend fails fast instead of waiting out the startup budget.
- The AUR launcher runs the renamed executable, and package-managed
  installs (VOICESTUDIO_DISABLE_UPDATER=1) are told to update through
  their package manager instead of opening a disabled updater.
- Windows: PATH is edited in the registry as stored (unexpanded entries,
  same value type); the warning never blocks a silent install; an
  update keeps the PATH entry in case it rolls back.
- Relative command links are resolved against their own folder, and
  bash users with ~/.bash_profile get the PATH entry there.
- Settings shows a translated, actionable message when PATH setup fails.
- Tests: the network guard also blocks connect_ex and sendto; the lock
  tests synchronize on events instead of sleeps and kill the holder to
  test a real crash; a Windows path assertion is separator-agnostic.
This commit is contained in:
mostafa-ismail-2004 committed 2026-11-05 19:40:27 +02:00
1 parent 7426ef77a9
commit ff1aa131f6
43 files changed
+345 -49

No files matched your search

+2 -1
View File
@@ -18,7 +18,7 @@ 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 .desktop import launch_desktop, remember_launcher_arguments, split_arguments
from .render import render
@@ -889,6 +889,7 @@ def main(argv=None):
argv, desktop_arguments = split_arguments(argv)
if not argv:
return launch_desktop(desktop_arguments)
remember_launcher_arguments(desktop_arguments)
root, nodes = build_parser()
args = root.parse_args(argv)
if not hasattr(args, 'handler'):
+9 -1
View File
@@ -22,6 +22,14 @@ CHECK_UPDATES_FLAG = '--voicestudio-check-updates'
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'}
INTENT_FLAGS = {BACKGROUND_FLAG, STOP_FLAG, CHECK_UPDATES_FLAG}
# Switches the launcher passed with this command (Snap's --no-sandbox, a chosen
# --ozone-platform, ...). Background launches need them as much as a window does.
launcher_arguments = []
def remember_launcher_arguments(arguments):
launcher_arguments[:] = [item for item in arguments if item.split('=', 1)[0] not in INTENT_FLAGS]
def split_arguments(argv):
@@ -184,7 +192,7 @@ def desktop_process(arguments, *, detached=False):
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)
return subprocess.Popen([*command, *launcher_arguments, *arguments], env=desktop_environment(), **options)
except OSError as exc:
raise CLIError('desktop_launch_failed', f'Could not launch VoiceStudio: {exc}') from None
+1 -1
View File
@@ -84,7 +84,7 @@ def _check_stage(record):
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'}:
if stage in {'failed', 'crashed', 'port_in_use'}: # the app does not restart these on its own
raise CLIError('backend_failed', 'VoiceStudio could not start its backend. Open VoiceStudio to see '
'why and repair it, then run this command again.')
+6 -1
View File
@@ -1,4 +1,6 @@
"""VoiceStudio application releases; installing an update belongs to the app's own updater."""
import os
from .application import installed_application
from .errors import CLIError
@@ -11,8 +13,11 @@ def install_info(app=None):
'Update VoiceStudio through the Mac App Store.'),
'directory': 'Install an application package to enable managed updates.',
}
automatic = app.method in {'appimage', 'dmg', 'nsis', 'deb'}
# Package managers (the AUR package, for one) turn the app's updater off.
managed = os.environ.get('VOICESTUDIO_DISABLE_UPDATER') == '1'
automatic = app.method in {'appimage', 'dmg', 'nsis', 'deb'} and not managed
fallback = ('Run voicestudio update, or use Settings → Updates in the app.' if automatic
else 'Update VoiceStudio with the package manager that installed it.' if managed
else 'Update VoiceStudio using its application installer.')
return app.info() | {'automatic': automatic, 'instructions': instructions.get(app.method, fallback)}
+5 -3
View File
@@ -189,9 +189,11 @@ 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
an update, the same as from the app. The terminal command makes no update
request of its own, and otherwise contacts only the backend it is connected to;
choose the update channel in **Settings → Updates**. Installations managed by
a package manager (`VOICESTUDIO_DISABLE_UPDATER=1`) are updated by that package
manager. 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.
+11 -6
View File
@@ -6,15 +6,20 @@
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."
; /SD IDOK: a silent (/S) install must never wait on a dialog.
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." /SD IDOK
${EndIf}
!macroend
!macro customUnInstall
StrCpy $0 "User"
${If} $installMode == "all"
StrCpy $0 "Machine"
; An update runs the old uninstaller first; if the update then rolls back, the
; restored files must still be on PATH. The new install re-adds the entry.
${IfNot} ${isUpdated}
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
${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
+26 -5
View File
@@ -1,12 +1,33 @@
# Called by NSIS; add/remove only the command directory owned by this installation.
# PATH is edited in the registry as stored: %SystemRoot%-style entries stay
# unexpanded and the value keeps its type ([Environment]::SetEnvironmentVariable
# would expand every entry and rewrite the value as a plain string).
param([ValidateSet('Install', 'Uninstall')][string]$Action,
[ValidateSet('User', 'Machine')][string]$Scope = 'User')
[ValidateSet('User', 'Machine')][string]$Scope = 'User',
# Tests point this at a scratch key under HKCU; installers never pass it.
[string]$TestKey = '')
$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)
if ($TestKey) {
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($TestKey)
} elseif ($Scope -eq 'Machine') {
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
} else {
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
}
try {
$current = [string]$key.GetValue('Path', '',
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
$kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
if ($key.GetValueNames() -contains 'Path') { $kind = $key.GetValueKind('Path') }
$entries = @($current -split ';' | Where-Object { $_ -and $_.TrimEnd('\') -ine $commandDir.TrimEnd('\') })
if ($Action -eq 'Install') { $entries = @($commandDir) + $entries }
$key.SetValue('Path', ($entries -join ';'), $kind)
} finally {
$key.Close()
}
if ($TestKey) { exit 0 }
# Notify Explorer so newly opened terminals inherit the updated PATH.
Add-Type @'
using System;
@@ -117,3 +117,27 @@ test('AppImage links the persistent image, rather than its temporary mount', ()
expect(linkTerminalCommand({ ...f, platform: 'linux' })).toBe('unavailable');
expect(terminalCommandStatus({ ...f, platform: 'win32' }).supported).toBe(false);
});
test('a live relative link is kept, whatever the working directory', () => {
const f = fixture();
const appImage = join(f.home, 'Apps/VoiceStudio-new.AppImage');
mkdirSync(join(f.home, 'Apps'));
writeFileSync(appImage, 'fixture');
writeFileSync(join(f.home, 'Apps/VoiceStudio-mine.AppImage'), 'user-managed');
mkdirSync(join(f.home, '.local/bin'), { recursive: true });
const command = join(f.home, '.local/bin/voicestudio');
symlinkSync('../../Apps/VoiceStudio-mine.AppImage', command);
expect(linkTerminalCommand({ ...f, platform: 'linux', appImage })).toBe('existing');
expect(readlinkSync(command)).toBe('../../Apps/VoiceStudio-mine.AppImage');
});
test('bash login shells that read .bash_profile get the PATH entry there', () => {
const f = fixture();
const appImage = join(f.home, 'VoiceStudio.AppImage');
writeFileSync(appImage, 'fixture');
writeFileSync(join(f.home, '.bash_profile'), '# login settings\n');
addTerminalCommandToPath({ ...f, platform: 'linux', appImage });
const profile = readFileSync(join(f.home, '.bash_profile'), 'utf8');
expect(profile).toContain('# login settings\n');
expect(profile).toContain('.local/bin');
});
+5 -3
View File
@@ -9,7 +9,7 @@ import {
unlinkSync,
writeFileSync,
} from 'node:fs';
import { basename, join } from 'node:path';
import { basename, dirname, join, resolve } from 'node:path';
export type TerminalCommandOptions = {
platform: NodeJS.Platform;
@@ -36,7 +36,8 @@ const PROFILE_LINES =
PROFILE_MARKER +
'case ":$PATH:" in\n *":$HOME/.local/bin:"*) ;;\n' +
' *) export PATH="$HOME/.local/bin:$PATH" ;;\nesac\n';
const PROFILES = ['.profile', '.bashrc', '.zshrc'];
// Bash login shells read .bash_profile instead of .profile when it exists.
const PROFILES = ['.profile', '.bash_profile', '.bashrc', '.zshrc'];
function commandTarget(options: TerminalCommandOptions): string | null {
// Windows installers own PATH; Snap exposes its own command; a translocated
@@ -59,7 +60,8 @@ function commandPath(home: string): string {
/** A dangling link left by a moved or replaced VoiceStudio, never someone else's command. */
function isStaleOwnLink(command: string): boolean {
const target = readlinkSync(command);
// A relative target is relative to the link's folder, not the working directory.
const target = resolve(dirname(command), readlinkSync(command));
if (existsSync(target)) return false;
return (
target.endsWith('/Contents/Resources/cli/voicestudio') ||
@@ -64,3 +64,13 @@ it('is hidden where installers or stores own the command', async () => {
cleanup();
expect(render(<TerminalCommandSettings />).container).toBeEmptyDOMElement();
});
it('turns a filesystem failure into a message the user can act on', async () => {
withBridge();
mock.status.mockResolvedValue(status({}));
mock.addToPath.mockRejectedValue(new Error("EACCES: permission denied, open '/home/user/.profile'"));
render(<TerminalCommandSettings />);
fireEvent.click(await screen.findByRole('button', { name: 'settings.terminal_command' }));
await waitFor(() => expect(mock.error).toHaveBeenCalledWith('settings.terminal_command_failed'));
expect(screen.getByRole('button', { name: 'settings.terminal_command' })).toBeEnabled();
});
@@ -4,7 +4,6 @@ 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';
@@ -41,8 +40,9 @@ export function TerminalCommandSettings() {
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));
} catch {
// A filesystem error ("EACCES: ...") tells the user nothing they can act on.
toast.error(t('settings.terminal_command_failed'));
} finally {
setBusy(false);
}
@@ -1510,6 +1510,7 @@
"terminal_command_add": "إضافة إلى الطرفية",
"terminal_command_ready": "متاح في نوافذ الطرفية الجديدة",
"terminal_command_added": "تمت الإضافة. افتح نافذة طرفية جديدة لاستخدام voicestudio.",
"terminal_command_failed": "تعذّرت إضافة voicestudio إلى الطرفية. تأكّد من أن مجلد المنزل ليس للقراءة فقط، ثم حاول مرة أخرى.",
"terminal_command_conflict": "{{path}} يخص تثبيتًا آخر، لذا تركه VoiceStudio دون تغيير.",
"review_mode_on": "مراجعة",
"review_mode_off": "سريع النيران",
@@ -1482,6 +1482,7 @@
"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_failed": "voicestudio konnte nicht zum Terminal hinzugefügt werden. Prüfe, ob dein Home-Ordner schreibgeschützt ist, und versuche es erneut.",
"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",
@@ -1665,6 +1665,7 @@
"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_failed": "Couldn't add voicestudio to your terminal. Check that your home folder isn't read-only, then try again.",
"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",
@@ -1484,6 +1484,7 @@
"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_failed": "No se pudo añadir voicestudio a la terminal. Comprueba que tu carpeta personal no sea de solo lectura e inténtalo de nuevo.",
"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",
@@ -1484,6 +1484,7 @@
"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_failed": "Impossible d'ajouter voicestudio au terminal. Vérifiez que votre dossier personnel n'est pas en lecture seule, puis réessayez.",
"terminal_command_conflict": "{{path}} appartient à une autre installation : VoiceStudio ne l'a pas modifié.",
"review_mode_on": "Examen",
"review_mode_off": "Tir rapide",
@@ -1665,6 +1665,7 @@
"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_failed": "Non se puido engadir voicestudio ao terminal. Comproba que o teu cartafol persoal non sexa de só lectura e téntao de novo.",
"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",
@@ -1482,6 +1482,7 @@
"terminal_command_add": "टर्मिनल में जोड़ें",
"terminal_command_ready": "नए टर्मिनल में उपलब्ध",
"terminal_command_added": "जोड़ दिया गया। voicestudio इस्तेमाल करने के लिए नई टर्मिनल विंडो खोलें।",
"terminal_command_failed": "voicestudio को टर्मिनल में नहीं जोड़ा जा सका। जाँचें कि आपका होम फ़ोल्डर केवल-पढ़ने योग्य नहीं है, फिर दोबारा कोशिश करें।",
"terminal_command_conflict": "{{path}} किसी दूसरे इंस्टॉलेशन का है, इसलिए VoiceStudio ने इसे नहीं बदला।",
"review_mode_on": "समीक्षा",
"review_mode_off": "तेजी से आग",
@@ -1482,6 +1482,7 @@
"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_failed": "Tidak dapat menambahkan voicestudio ke terminal. Pastikan folder home Anda tidak hanya-baca, lalu coba lagi.",
"terminal_command_conflict": "{{path}} milik instalasi lain, jadi VoiceStudio tidak mengubahnya.",
"review_mode_on": "Ulasan",
"review_mode_off": "Tembakan cepat",
@@ -1484,6 +1484,7 @@
"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_failed": "Impossibile aggiungere voicestudio al terminale. Verifica che la cartella home non sia di sola lettura, poi riprova.",
"terminal_command_conflict": "{{path}} appartiene a un'altra installazione, quindi VoiceStudio non l'ha modificato.",
"review_mode_on": "Recensione",
"review_mode_off": "Fuoco rapido",
@@ -1482,6 +1482,7 @@
"terminal_command_add": "ターミナルに追加",
"terminal_command_ready": "新しいターミナルで利用可能",
"terminal_command_added": "追加しました。voicestudio を使うには新しいターミナルウィンドウを開いてください。",
"terminal_command_failed": "voicestudio をターミナルに追加できませんでした。ホームフォルダーが読み取り専用でないことを確認して、もう一度お試しください。",
"terminal_command_conflict": "{{path}} は別のインストールのものなので、VoiceStudio は変更しませんでした。",
"review_mode_on": "レビュー",
"review_mode_off": "連射",
@@ -1340,6 +1340,7 @@
"terminal_command_add": "터미널에 추가",
"terminal_command_ready": "새 터미널에서 사용 가능",
"terminal_command_added": "추가했습니다. voicestudio를 사용하려면 새 터미널 창을 여세요.",
"terminal_command_failed": "voicestudio를 터미널에 추가하지 못했습니다. 홈 폴더가 읽기 전용이 아닌지 확인한 후 다시 시도하세요.",
"terminal_command_conflict": "{{path}}은(는) 다른 설치에 속해 있어 VoiceStudio가 변경하지 않았습니다.",
"review_mode_on": "검토",
"translate_agent": "에이전트 적합성",
@@ -1482,6 +1482,7 @@
"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_failed": "voicestudio kon niet aan de terminal worden toegevoegd. Controleer of je thuismap niet alleen-lezen is en probeer het opnieuw.",
"terminal_command_conflict": "{{path}} hoort bij een andere installatie, dus VoiceStudio heeft het niet gewijzigd.",
"review_mode_on": "Beoordeling",
"review_mode_off": "Snelvuur",
@@ -1496,6 +1496,7 @@
"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_failed": "Nie udało się dodać voicestudio do terminala. Sprawdź, czy folder domowy nie jest tylko do odczytu, i spróbuj ponownie.",
"terminal_command_conflict": "{{path}} należy do innej instalacji, więc VoiceStudio go nie zmienił.",
"review_mode_on": "Recenzja",
"review_mode_off": "Szybkostrzelny",
@@ -1484,6 +1484,7 @@
"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_failed": "Não foi possível adicionar voicestudio ao terminal. Verifique se a sua pasta pessoal não é só de leitura e tente novamente.",
"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",
@@ -1496,6 +1496,7 @@
"terminal_command_add": "Добавить в терминал",
"terminal_command_ready": "Доступна в новых терминалах",
"terminal_command_added": "Добавлено. Откройте новое окно терминала, чтобы использовать voicestudio.",
"terminal_command_failed": "Не удалось добавить voicestudio в терминал. Убедитесь, что домашняя папка не доступна только для чтения, и повторите попытку.",
"terminal_command_conflict": "{{path}} принадлежит другой установке, поэтому VoiceStudio его не изменил.",
"review_mode_on": "Обзор",
"review_mode_off": "Скорострельный",
@@ -1482,6 +1482,7 @@
"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_failed": "Det gick inte att lägga till voicestudio i terminalen. Kontrollera att din hemmapp inte är skrivskyddad och försök igen.",
"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",
@@ -1482,6 +1482,7 @@
"terminal_command_add": "เพิ่มลงในเทอร์มินัล",
"terminal_command_ready": "ใช้ได้ในเทอร์มินัลใหม่",
"terminal_command_added": "เพิ่มแล้ว เปิดหน้าต่างเทอร์มินัลใหม่เพื่อใช้ voicestudio",
"terminal_command_failed": "เพิ่ม voicestudio ลงในเทอร์มินัลไม่ได้ ตรวจสอบว่าโฟลเดอร์โฮมไม่ได้เป็นแบบอ่านอย่างเดียว แล้วลองอีกครั้ง",
"terminal_command_conflict": "{{path}} เป็นของการติดตั้งอื่น VoiceStudio จึงไม่ได้เปลี่ยนแปลง",
"review_mode_on": "รีวิว",
"review_mode_off": "ยิงเร็ว",
@@ -1482,6 +1482,7 @@
"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_failed": "voicestudio terminale eklenemedi. Ana klasörünüzün salt okunur olmadığını kontrol edip yeniden deneyin.",
"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ş",
@@ -1496,6 +1496,7 @@
"terminal_command_add": "Додати до терміналу",
"terminal_command_ready": "Доступна в нових терміналах",
"terminal_command_added": "Додано. Відкрийте нове вікно терміналу, щоб використовувати voicestudio.",
"terminal_command_failed": "Не вдалося додати voicestudio до терміналу. Переконайтеся, що домашня тека не лише для читання, і спробуйте ще раз.",
"terminal_command_conflict": "{{path}} належить іншому встановленню, тому VoiceStudio його не змінив.",
"review_mode_on": "огляд",
"review_mode_off": "Скорострільна",
@@ -1482,6 +1482,7 @@
"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_failed": "Không thể thêm voicestudio vào terminal. Hãy kiểm tra thư mục home của bạn không ở chế độ chỉ đọc, rồi thử lại.",
"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",
@@ -1471,6 +1471,7 @@
"terminal_command_add": "添加到终端",
"terminal_command_ready": "可在新终端中使用",
"terminal_command_added": "已添加。打开新的终端窗口即可使用 voicestudio。",
"terminal_command_failed": "无法将 voicestudio 添加到终端。请确认你的主文件夹不是只读的,然后重试。",
"terminal_command_conflict": "{{path}} 属于另一个安装,因此 VoiceStudio 未作更改。",
"review_mode_on": "审阅",
"translate_agent": "智能体适配",
@@ -1482,6 +1482,7 @@
"terminal_command_add": "加入終端機",
"terminal_command_ready": "可在新的終端機中使用",
"terminal_command_added": "已加入。開啟新的終端機視窗即可使用 voicestudio。",
"terminal_command_failed": "無法將 voicestudio 加入終端機。請確認你的主資料夾不是唯讀的,然後再試一次。",
"terminal_command_conflict": "{{path}} 屬於另一個安裝,因此 VoiceStudio 未作變更。",
"review_mode_on": "評論",
"review_mode_off": "速射",
+1 -1
View File
@@ -51,7 +51,7 @@ for (const platform of ['linux', 'darwin', 'win32']) {
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(manifest.executable.replaceAll('\\', '/'), '../../voicestudio-desktop');
assert.equal(
readFileSync(join(appOutDir, 'voicestudio-desktop'), 'utf8'),
'original desktop',
+1 -1
View File
@@ -85,7 +85,7 @@ package() {
cat > "$pkgdir/usr/bin/voicestudio" <<'EOF'
#!/bin/sh
export VOICESTUDIO_DISABLE_UPDATER=1
exec /opt/VoiceStudio/voicestudio-electron "$@"
exec /opt/VoiceStudio/voicestudio "$@"
EOF
chmod 755 "$pkgdir/usr/bin/voicestudio"
+20 -2
View File
@@ -3,6 +3,8 @@ import ipaddress
import socket
original_connect = socket.socket.connect
original_connect_ex = socket.socket.connect_ex
original_sendto = socket.socket.sendto
original_getaddrinfo = socket.getaddrinfo
@@ -15,12 +17,26 @@ def allowed(host):
return False
def connect(self, address):
if self.family in {socket.AF_INET, socket.AF_INET6} and not allowed(address[0]):
def check(sock, address):
if sock.family in {socket.AF_INET, socket.AF_INET6} and not allowed(address[0]):
raise OSError('External network access forbidden in CLI tests')
def connect(self, address):
check(self, address)
return original_connect(self, address)
def connect_ex(self, address):
check(self, address)
return original_connect_ex(self, address)
def sendto(self, data, *args):
check(self, args[-1]) # sendto(data, address) or sendto(data, flags, address)
return original_sendto(self, data, *args)
def getaddrinfo(host, *args, **kwargs):
if not allowed(host):
raise OSError('External DNS access forbidden in CLI tests')
@@ -28,4 +44,6 @@ def getaddrinfo(host, *args, **kwargs):
socket.socket.connect = connect
socket.socket.connect_ex = connect_ex
socket.socket.sendto = sendto
socket.getaddrinfo = getaddrinfo
+2 -1
View File
@@ -130,7 +130,8 @@ def test_state_queries_never_start_the_app(home, monkeypatch, command):
@pytest.mark.parametrize('stage, code', [('setup_required', 'runtime_not_ready'),
('failed', 'backend_failed'), ('port_in_use', 'backend_failed')])
('failed', 'backend_failed'), ('crashed', '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()
+13
View File
@@ -81,6 +81,19 @@ class DesktopTests(unittest.TestCase):
with patch.object(desktop.shutil, 'which', return_value=None):
self.assertEqual(desktop.resolve_desktop(), [str(path)])
def test_background_launches_keep_the_launchers_switches(self):
# Snap runs "voicestudio --no-sandbox voices list"; Chromium cannot start
# under strict confinement without that switch, window or not.
self.addCleanup(desktop.launcher_arguments.clear)
path = self.executable()
with patch('voicestudio_cli.__main__.app_version', return_value='9.8.7'):
self.assertEqual(main(['--no-sandbox', '--ozone-platform', 'x11', desktop.STOP_FLAG, 'version']), 0)
with patch.dict(os.environ, {'VOICESTUDIO_DESKTOP_APP': str(path)}), \
patch.object(desktop.subprocess, 'Popen') as popen:
desktop.desktop_process([desktop.BACKGROUND_FLAG], detached=True)
self.assertEqual(popen.call_args.args[0],
[str(path), '--no-sandbox', '--ozone-platform', 'x11', desktop.BACKGROUND_FLAG])
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'}):
+40
View File
@@ -0,0 +1,40 @@
"""The CLI test subprocess guard blocks every way out to a non-loopback address."""
import os
from pathlib import Path
import subprocess
import sys
GUARD = Path(__file__).resolve().parent / 'network_guard'
# 192.0.2.1 is TEST-NET-1: never routed, so even an unguarded attempt goes nowhere.
PROBE = r'''
import socket
results = []
for name, attempt in [
('connect', lambda s: s.connect(('192.0.2.1', 9))),
('connect_ex', lambda s: s.connect_ex(('192.0.2.1', 9))),
]:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(0.2)
try:
attempt(sock)
results.append(name + ':allowed')
except OSError as exc:
results.append(name + (':blocked' if 'forbidden' in str(exc) else ':allowed'))
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
for name, args in [('sendto', (('192.0.2.1', 9),)), ('sendto-flags', (0, ('192.0.2.1', 9)))]:
try:
sock.sendto(b'x', *args)
results.append(name + ':allowed')
except OSError as exc:
results.append(name + (':blocked' if 'forbidden' in str(exc) else ':allowed'))
sock.sendto(b'x', ('127.0.0.1', 9)) # loopback stays allowed
print(' '.join(results))
'''
def test_guard_blocks_connect_connect_ex_and_sendto():
env = {**os.environ, 'PYTHONPATH': str(GUARD)}
result = subprocess.run([sys.executable, '-c', PROBE], env=env, capture_output=True, text=True, timeout=30)
assert result.returncode == 0, result.stderr
assert result.stdout.split() == ['connect:blocked', 'connect_ex:blocked',
'sendto:blocked', 'sendto-flags:blocked']
+9 -1
View File
@@ -51,6 +51,14 @@ class UpdateTests(unittest.TestCase):
self.assertIn(fragment, json.loads(errors)['error']['message'])
launch.assert_not_called()
def test_package_managed_installs_never_open_a_disabled_updater(self):
with patch.dict('os.environ', {'VOICESTUDIO_DISABLE_UPDATER': '1'}), \
patch.object(desktop, 'desktop_process') as launch:
code, _, errors = self.run_main('update', '--json')
self.assertEqual(code, 1)
self.assertIn('package manager', json.loads(errors)['error']['message'])
launch.assert_not_called()
def test_removed_release_and_channel_options_are_rejected(self):
for flag in [('--release', '1.0.1'), ('--channel', 'beta')]:
with self.subTest(flag=flag), patch.object(desktop, 'desktop_process') as launch:
@@ -58,7 +66,7 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(code, 2)
launch.assert_not_called()
def test_the_cli_never_contacts_the_internet(self):
def test_the_cli_has_no_internet_endpoints_of_its_own(self):
# The app's updater is the sanctioned update check (CONTRIBUTING.md →
# Local-first); a CLI that fetched releases itself would be a second one.
for source in PACKAGE.glob('*.py'):
+73
View File
@@ -0,0 +1,73 @@
"""The Windows installer's PATH step: unexpanded entries, silent installs, update rollback."""
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
import uuid
PACKAGING = Path(__file__).resolve().parents[2] / 'electron' / 'packaging'
SCRIPT = PACKAGING / 'cli-path.ps1'
INSTALLER = PACKAGING / 'cli-installer.nsh'
class InstallerScriptTests(unittest.TestCase):
def test_path_is_edited_as_stored_in_the_registry(self):
text = SCRIPT.read_text(encoding='utf-8')
self.assertIn('DoNotExpandEnvironmentNames', text)
self.assertNotIn("SetEnvironmentVariable('Path'", text)
def test_a_silent_install_never_waits_on_a_dialog(self):
for line in INSTALLER.read_text(encoding='utf-8').splitlines():
if line.strip().startswith('MessageBox'):
self.assertIn('/SD ', line)
def test_an_update_keeps_the_path_entry_for_a_rollback(self):
uninstall = INSTALLER.read_text(encoding='utf-8').split('!macro customUnInstall', 1)[1]
self.assertLess(uninstall.index('${IfNot} ${isUpdated}'), uninstall.index('-Action Uninstall'))
@unittest.skipUnless(sys.platform == 'win32', 'runs the real script against the Windows registry')
class RegistryTests(unittest.TestCase):
def setUp(self):
import winreg
self.winreg = winreg
self.key = rf'Software\VoiceStudioTests\{uuid.uuid4().hex}'
self.addCleanup(self._delete_key)
# The script adds its own folder, so run a copy from a scratch folder.
folder = Path(tempfile.mkdtemp()); self.addCleanup(shutil.rmtree, folder, True)
self.script = folder / 'path.ps1'
shutil.copy(SCRIPT, self.script)
self.folder = str(folder.resolve())
def _delete_key(self):
try:
self.winreg.DeleteKey(self.winreg.HKEY_CURRENT_USER, self.key)
except OSError:
pass
def run_script(self, action):
powershell = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
subprocess.run([str(powershell), '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', str(self.script), '-Action', action, '-TestKey', self.key], check=True, timeout=60)
def read(self):
with self.winreg.OpenKey(self.winreg.HKEY_CURRENT_USER, self.key) as key:
return self.winreg.QueryValueEx(key, 'Path')
def test_install_and_uninstall_keep_unexpanded_entries_and_the_value_type(self):
original = r'%SystemRoot%\system32;%USERPROFILE%\bin'
with self.winreg.CreateKey(self.winreg.HKEY_CURRENT_USER, self.key) as key:
self.winreg.SetValueEx(key, 'Path', 0, self.winreg.REG_EXPAND_SZ, original)
self.run_script('Install')
self.assertEqual(self.read(), (f'{self.folder};{original}', self.winreg.REG_EXPAND_SZ))
self.run_script('Install') # idempotent
self.assertEqual(self.read()[0], f'{self.folder};{original}')
self.run_script('Uninstall')
self.assertEqual(self.read(), (original, self.winreg.REG_EXPAND_SZ))
if __name__ == '__main__':
unittest.main()
+8
View File
@@ -26,3 +26,11 @@ def test_ci_validates_the_installed_desktop_entry():
filename, _ = _desktop_entry()
workflow = (ROOT / ".github/workflows/aur-package.yml").read_text(encoding="utf-8")
assert f"desktop-file-validate pkg/voicestudio-git/usr/share/applications/{filename}" in workflow
def test_launcher_runs_the_executable_electron_builder_produces():
recipe = (ROOT / "packaging/aur/voicestudio-git/PKGBUILD").read_text(encoding="utf-8")
config = (ROOT / "electron/electron-builder.config.mjs").read_text(encoding="utf-8")
executable = re.search(r"linuxExecutableName: '([^']+)'", config)
assert executable, "electron-builder no longer names the Linux executable"
assert re.search(rf"^exec /opt/VoiceStudio/{re.escape(executable[1])} \"\$@\"$", recipe, re.M)
+54 -19
View File
@@ -17,25 +17,60 @@ def test_second_backend_is_refused_with_an_actionable_message(tmp_path):
pass
def _holder(tmp_path):
"""A separate backend process that holds the lock until stdin closes or it is killed."""
backend = Path(__file__).resolve().parents[1] / 'backend'
script = ('import sys; from core.runtime_owner import DataDirectoryLease\n'
'with DataDirectoryLease(sys.argv[1]):\n print("held", flush=True); sys.stdin.read()')
holder = subprocess.Popen([sys.executable, '-c', script, str(tmp_path)], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, env={**os.environ, 'PYTHONPATH': str(backend)})
assert holder.stdout.readline().strip() == b'held'
return holder
def test_crashed_owner_releases_the_directory(tmp_path):
backend = Path(__file__).resolve().parents[1] / 'backend'
script = ('import os,sys; from core.runtime_owner import DataDirectoryLease; '
'DataDirectoryLease(sys.argv[1]).__enter__(); os._exit(0)')
subprocess.run([sys.executable, '-c', script, str(tmp_path)], check=True,
env={**os.environ, 'PYTHONPATH': str(backend)})
with DataDirectoryLease(tmp_path):
pass
def test_waiting_backend_acquires_after_its_predecessor_exits(tmp_path):
backend = Path(__file__).resolve().parents[1] / 'backend'
script = ('import sys,time; from core.runtime_owner import DataDirectoryLease\n'
'with DataDirectoryLease(sys.argv[1]):\n print("held", flush=True); time.sleep(0.5)')
holder = subprocess.Popen([sys.executable, '-c', script, str(tmp_path)], stdout=subprocess.PIPE,
env={**os.environ, 'PYTHONPATH': str(backend)})
holder = _holder(tmp_path)
try:
assert holder.stdout.readline().strip() == b'held'
with DataDirectoryLease(tmp_path, timeout=10):
assert holder.wait(timeout=10) == 0
finally:
with pytest.raises(DataDirectoryBusy):
DataDirectoryLease(tmp_path).__enter__()
holder.kill() # a crash: no __exit__, no cleanup
holder.wait(timeout=10)
with DataDirectoryLease(tmp_path):
pass
finally:
holder.kill()
holder.wait(timeout=10)
def test_waiting_backend_acquires_after_its_predecessor_exits(tmp_path, monkeypatch):
import threading
from core import runtime_owner
holder = _holder(tmp_path)
waiting = threading.Event()
real_sleep = runtime_owner.time.sleep
def sleep(seconds):
waiting.set() # the first attempt failed: the lease is now waiting
real_sleep(seconds)
monkeypatch.setattr(runtime_owner.time, 'sleep', sleep)
acquired = []
def acquire():
with DataDirectoryLease(tmp_path, timeout=30):
acquired.append(True)
worker = threading.Thread(target=acquire)
try:
worker.start()
assert waiting.wait(timeout=10)
assert not acquired
holder.stdin.close() # the predecessor exits normally
assert holder.wait(timeout=10) == 0
worker.join(timeout=30)
assert acquired == [True]
finally:
holder.kill()
holder.wait(timeout=10)
worker.join(timeout=30)