Merge pull request #3594 from debpalash/community/batch-oct27b

community: batch — macOS 14 dev launch, Galician locale, 24-hour times, speech-client framing
This commit is contained in:
Palash Debnath authored and GitHub committed 2026-10-28 02:23:51 +05:30
commit 9f7088d1cb
32 files changed
+8005 -31

No files matched your search

+2 -2
View File
@@ -444,8 +444,8 @@ hard rules from the first prompt.
*implementation* is fine; platform-divergent *default behavior* is a P0.
Platform-only features go behind an explicit opt-in (Settings toggle, env
var, or CLI flag).
- **i18n — all 21 locales (hard rule):** every user-facing string goes through
`t('...')` and the key must exist in **all 21** files of the catalog the code
- **i18n — every locale (hard rule):** every user-facing string goes through
`t('...')` and the key must exist in **every** file of the catalog the code
uses: `electron/src/shared/i18n/locales/` (checked by
`tests/test_locale_parity.py`) or `electron/src/renderer/src/i18n/locales/`
(checked by `bun run --cwd electron locale:check`). Translate; don't copy
+4 -1
View File
@@ -752,7 +752,10 @@ def _numbers_to_words(text: str, lang: str, locale: Optional[str] = None) -> str
h, mm = int(m.group(1)), int(m.group(2))
hw = num2words(h, lang="en")
if mm == 0:
return f"{hw} o'clock"
# "o'clock" belongs to the 12-hour dial: a 24-hour hour on the
# hour is read in hundreds ("thirteen hundred"), never
# "thirteen o'clock" or "zero o'clock".
return f"{hw} o'clock" if 1 <= h <= 12 else f"{hw} hundred"
if mm < 10:
return f"{hw} oh {num2words(mm, lang='en')}"
return f"{hw} {num2words(mm, lang='en')}"
+31 -6
View File
@@ -17,6 +17,7 @@ import mimetypes
import os
from pathlib import Path
import secrets
import socket
import sys
from typing import Any
from urllib import error, request
@@ -24,8 +25,10 @@ from urllib.parse import urlsplit
try:
from core.app_config import DEFAULT_BACKEND_PORT
from core.path_security import portable_filename
except ModuleNotFoundError: # ``python -m backend.speech_client`` from the repo root
from backend.core.app_config import DEFAULT_BACKEND_PORT
from backend.core.path_security import portable_filename
DEFAULT_ENGINE_URL = f"http://127.0.0.1:{DEFAULT_BACKEND_PORT}"
@@ -75,7 +78,29 @@ def _is_loopback_host(host: str | None) -> bool:
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
pass
# Match the OS's numeric IPv4 spellings without resolving a hostname.
try:
addresses = socket.getaddrinfo(host, None, flags=socket.AI_NUMERICHOST)
except OSError:
return False
return bool(addresses) and all(
ipaddress.ip_address(info[4][0]).is_loopback for info in addresses
)
class _LoopbackDirectProxyHandler(request.ProxyHandler):
"""Environment proxies, except for loopback targets.
no_proxy rarely lists numeric aliases like 127.1, and a plain-HTTP bearer
key must not reach a proxy in the clear. Checked per request, so a redirect
from loopback to a remote host still uses the configured proxy.
"""
def proxy_open(self, req, proxy, type): # noqa: A002 - urllib signature
if _is_loopback_host(urlsplit(req.full_url).hostname):
return None
return super().proxy_open(req, proxy, type)
def _open(req: request.Request, timeout: float = 300.0) -> tuple[bytes, str]:
@@ -86,12 +111,11 @@ def _open(req: request.Request, timeout: float = 300.0) -> tuple[bytes, str]:
credentialed = bool(req.get_header("Authorization"))
if credentialed and scheme != "https" and not _is_loopback_host(target.hostname):
raise SpeechClientError("Remote VoiceStudio credentials require https://")
handlers: list[request.BaseHandler] = [_LoopbackDirectProxyHandler()]
if credentialed:
handlers.append(_RejectCredentialRedirect())
try:
opener = (
request.build_opener(_RejectCredentialRedirect())
if credentialed
else request.build_opener()
)
opener = request.build_opener(*handlers)
with opener.open(req, timeout=timeout) as response: # noqa: S310
return response.read(), response.headers.get("Content-Type", "")
except error.HTTPError as exc:
@@ -131,7 +155,8 @@ def _encode_multipart(
b"\r\n",
]
)
safe_filename = Path(filename).name.replace('"', "") or "audio.wav"
basename = filename.replace("\\", "/").rsplit("/", 1)[-1]
safe_filename = portable_filename(basename, default="audio.wav")
content_type = mimetypes.guess_type(safe_filename)[0] or "application/octet-stream"
if Path(safe_filename).suffix.lower() in {".wav", ".wave"}:
content_type = "audio/wav"
+1
View File
@@ -0,0 +1 @@
Galician (Galego) is now available as an app language on desktop and mobile (#3594) — thanks @B1NAR10!
+1
View File
@@ -0,0 +1 @@
English speech reads a 24-hour time on the hour as "nineteen hundred" instead of "nineteen o'clock" (#3594) — thanks @kevin9327!
+1
View File
@@ -0,0 +1 @@
The speech CLI keeps uploads well-formed for any file name, accepts numeric loopback addresses such as 127.1, and never sends local requests through a proxy (#3594) — thanks @rudycelekli!
+1
View File
@@ -0,0 +1 @@
Source checkouts on macOS 14 and older start with `bun run dev` again instead of failing on a missing `lockf` (#3594) — thanks @sebas-rodri!
+1 -1
View File
@@ -31,4 +31,4 @@ and displays the source thumbnail while a first preview is prepared. Audio previ
buttons show pending/buffering and unavailable states instead of silently swallowing
playback failures. An audio-only dub's preview mixes the dubbed track with the
background once and reuses that file for every seek; regenerating the track
replaces the old mix. Playback labels are translated in all 21 locales.
replaces the old mix. Playback labels are translated in every app locale.
+4 -1
View File
@@ -41,7 +41,10 @@ python -m backend.speech_client transcribe recording.wav
It targets `VOICESTUDIO_URL`, else the loopback backend on `OMNIVOICE_PORT`
(default 3900), and sends `OMNIVOICE_API_KEY` as a bearer key when set. The
former `status`, `start`, `stop`, `toggle` and `transcribe --insert` commands
exit with an explanation.
exit with an explanation. Numeric loopback spellings such as `127.1` are
recognized without a DNS lookup; remote bearer credentials still require HTTPS.
Uploaded filenames are reduced to a portable basename before entering multipart
headers; audio bytes and form-field contents are preserved.
## Bring your own capture interface
+16 -3
View File
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import {
closeSync,
existsSync,
mkdirSync,
openSync,
readFileSync,
@@ -20,11 +21,23 @@ export function macDevLeaseDirectory(cacheRoot) {
return join(homedir(), 'Library', 'Caches', 'VoiceStudio', 'dev-bundle-locks', key);
}
// /usr/bin/lockf first shipped in macOS 15; older releases lack it but always
// ship /usr/bin/perl, whose flock() takes the same open-file-description lock.
const PERL_FLOCK =
'use Fcntl qw(:flock); open(my $fh, "+<&=", 3) or die "fd 3: $!\\n";' +
' exit(flock($fh, LOCK_EX | ($ARGV[0] ? 0 : LOCK_NB)) ? 0 : 75);';
export function lockCommand(wait, exists = existsSync) {
return exists('/usr/bin/lockf')
? ['/usr/bin/lockf', ['-s', ...(wait ? [] : ['-t', '0']), '3']]
: ['/usr/bin/perl', ['-e', PERL_FLOCK, wait ? '1' : '0']];
}
function lockDescriptor(fd, wait) {
// Darwin lockf has a descriptor-only form: lockf [-s] [-t seconds] fd.
// The kernel lock survives
// Both helpers lock the inherited descriptor 3. The kernel lock survives
// this helper's exit until every copy of that open descriptor is closed.
const result = spawnSync('/usr/bin/lockf', ['-s', ...(wait ? [] : ['-t', '0']), '3'], {
const [command, args] = lockCommand(wait);
const result = spawnSync(command, args, {
stdio: ['ignore', 'pipe', 'pipe', fd],
encoding: 'utf8',
});
+1 -1
View File
@@ -33,7 +33,7 @@ describe('blank window fallback', () => {
it('stays aligned with every renderer locale catalogue', () => {
const directory = join(process.cwd(), 'src/renderer/src/i18n/locales');
const locales = readdirSync(directory).filter((file) => file.endsWith('.json'));
expect(locales).toHaveLength(21);
expect(locales).toHaveLength(22);
for (const file of locales) {
const locale = file.slice(0, -5);
const catalogue = JSON.parse(readFileSync(join(directory, file), 'utf8')) as {
+1
View File
@@ -17,6 +17,7 @@ const FALLBACK_COPY: Record<string, FallbackCopy> = {
en: { title: 'Something went wrong', retry: 'Try again' },
es: { title: 'algo salió mal', retry: 'Inténtalo de nuevo' },
fr: { title: "Quelque chose s'est mal passé", retry: 'Réessayez' },
gl: { title: 'Erro', retry: 'Téntao de novo' },
hi: { title: 'कुछ ग़लत हो गया', retry: 'पुनः प्रयास करें' },
id: { title: 'Ada yang tidak beres', retry: 'Coba lagi' },
it: { title: 'Qualcosa è andato storto', retry: 'Riprova' },
+1
View File
@@ -26,6 +26,7 @@ export const SUPPORTED_LOCALES = [
'uk',
'ar',
'zh-TW',
'gl',
] as const;
export type AppLocale = (typeof SUPPORTED_LOCALES)[number];
File diff suppressed because it is too large. Load diff
@@ -63,6 +63,7 @@ const getSystemLanguage = () => {
'id',
'uk',
'ar',
'gl',
].find((code) => navLang.startsWith(code.split('-')[0]));
return match || 'en';
};
@@ -12,7 +12,7 @@ import React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import i18n from '../i18n';
import i18n, { LANGUAGES } from '../i18n';
const captureLocales = import.meta.glob('../i18n/locales/*.json', {
eager: true,
@@ -221,7 +221,7 @@ describe('CaptureWidget', () => {
const typeCalls = () => mocks.holder.calls.filter(([c]) => c === 'simulate_type');
it('provides a translated Inserted outcome in every supported locale', () => {
expect(Object.keys(captureLocales)).toHaveLength(21);
expect(Object.keys(captureLocales)).toHaveLength(LANGUAGES.length);
for (const [path, locale] of Object.entries(captureLocales)) {
expect(locale.capture.inserted, path).toBeTruthy();
if (!path.endsWith('/en.json')) expect(locale.capture.inserted, path).not.toBe('Inserted');
+2
View File
@@ -30,6 +30,7 @@ const LOADERS: Record<string, () => Promise<{ default: Record<string, unknown> }
uk: () => import('./locales/uk.json'),
ar: () => import('./locales/ar.json'),
'zh-TW': () => import('./locales/zh-TW.json'),
gl: () => import('./locales/gl.json'),
};
const loading = new Set<string>();
@@ -118,6 +119,7 @@ export const LANGUAGES = [
{ code: 'uk', label: 'Українська' },
{ code: 'ar', label: 'العربية' },
{ code: 'zh-TW', label: '繁體中文' },
{ code: 'gl', label: 'Galego' },
];
export default i18n;
@@ -27,6 +27,7 @@ describe('selectable UI languages', () => {
'uk',
'ar',
'zh-TW',
'gl',
]);
expect(LANGUAGES.every(({ label }) => label.trim().length > 0)).toBe(true);
});
File diff suppressed because it is too large. Load diff
+1
View File
@@ -425,6 +425,7 @@ export const createPrefsSlice: StateCreator<PrefsSlice, [], [], PrefsSlice> = (s
'id',
'uk',
'ar',
'gl',
].find((code) => nav.startsWith(code.split('-')[0]));
return match || 'en';
})()
@@ -123,6 +123,7 @@ describe('toastErrorWithReport voice-design instruct guidance (#1771)', () => {
'en',
'es',
'fr',
'gl',
'hi',
'id',
'it',
@@ -141,9 +142,9 @@ describe('toastErrorWithReport voice-design instruct guidance (#1771)', () => {
'zh-TW',
];
it('every new i18n key added for #1771 exists in all 21 locales', () => {
it('every new i18n key added for #1771 exists in all locales', () => {
const localesDir = path.resolve(__dirname, '../i18n/locales');
expect(SUPPORTED_LOCALES).toHaveLength(21);
expect(SUPPORTED_LOCALES).toHaveLength(22);
for (const code of SUPPORTED_LOCALES) {
const locale = JSON.parse(fs.readFileSync(path.join(localesDir, `${code}.json`), 'utf8'));
expect(locale.tts_errors?.dialect_accent_conflict, `${code} missing key`).toBeTruthy();
+1
View File
@@ -28,6 +28,7 @@ const locales = [
'uk',
'ar',
'zh-TW',
'gl',
];
const longStringLocales = ['de', 'fr', 'ru', 'uk', 'hi', 'ar', 'zh-TW'];
const routes = ['settings/general', 'settings/performance', 'settings/models', 'clone', 'dub'];
@@ -35,7 +35,7 @@ class L10n(private val catalogs: Map<String, JsonObject>, val locale: String) {
// Escape both braces: Android's ICU regex rejects a bare `}` that the
// JVM (and so Robolectric) accepts, which crashed the app on launch.
private val PLACEHOLDER = Regex("""\{\{\s*([^{}]+?)\s*\}\}""")
val languages = listOf("en", "zh-CN", "es", "fr", "de", "ja", "pt", "it", "ru", "ko", "hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW")
val languages = listOf("en", "zh-CN", "es", "fr", "de", "ja", "pt", "it", "ru", "ko", "hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW", "gl")
private fun lookup(obj: JsonObject?, key: String): String? {
var node: JsonElement? = obj
for(part in key.split('.')) node = (node as? JsonObject)?.get(part) ?: return null
@@ -1,7 +1,7 @@
import Foundation
public struct L10n: Sendable {
public static let languages = ["en", "zh-CN", "es", "fr", "de", "ja", "pt", "it", "ru", "ko", "hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW"]
public static let languages = ["en", "zh-CN", "es", "fr", "de", "ja", "pt", "it", "ru", "ko", "hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW", "gl"]
public var locale: String
private let catalogs: [String: [String: String]]
public init(locale: String = Locale.current.identifier, catalogs: [String: Data]) throws {
+1 -1
View File
@@ -38,7 +38,7 @@ const eagerRows = eager.map((file) => {
});
const sum = (rows, key) => rows.reduce((total, row) => total + row[key], 0);
const LOCALE = /^(ar|de|es|fr|hi|id|it|ja|ko|nl|pl|pt|ru|sv|th|tr|uk|vi|zh-CN|zh-TW)-/;
const LOCALE = /^(ar|de|es|fr|hi|id|it|ja|ko|nl|pl|pt|ru|sv|th|tr|uk|vi|zh-CN|zh-TW|gl)-/;
const locales = js.filter((a) => LOCALE.test(a.name));
console.log('### Renderer bundle');
+1 -1
View File
@@ -10,7 +10,7 @@ LOCALES_DIR = os.path.join(
LANGUAGES = [
"zh-CN", "es", "fr", "de", "ja", "pt", "it", "ru", "ko",
"hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW"
"hi", "tr", "pl", "nl", "sv", "th", "vi", "id", "uk", "ar", "zh-TW", "gl"
]
VAR_PAT = re.compile(r'\{\{[a-zA-Z0-9_]+\}\}')
+33
View File
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import {
activeMacDevBundles,
holdMacDevBundle,
lockCommand,
withMacDevCacheLock,
} from "../../electron/scripts/mac-dev-cache.mjs";
test("lock helper falls back to perl where /usr/bin/lockf is missing (macOS 14 and older)", () => {
assert.equal(lockCommand(true, () => true)[0], "/usr/bin/lockf");
const [command, args] = lockCommand(false, () => false);
assert.equal(command, "/usr/bin/perl");
assert.equal(args.at(-1), "0");
assert.equal(lockCommand(true, () => false)[1].at(-1), "1");
});
test("leases stay held while open and are pruned once released", { skip: process.platform !== "darwin" }, () => {
const root = mkdtempSync(join(tmpdir(), "mac-dev-cache-"));
try {
const cache = join(root, "cache");
const leases = join(root, "leases");
const lease = withMacDevCacheLock(cache, (directory) => holdMacDevBundle(directory, cache), leases);
assert.equal(activeMacDevBundles(leases)?.size, 1);
lease.release();
assert.equal(activeMacDevBundles(leases)?.size, 0);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
+1 -1
View File
@@ -429,7 +429,7 @@ def test_a_host_with_no_mismatched_kernels_keeps_its_vendor_verdict(
sorted(f[:-5] for f in os.listdir(LOCALES_DIR) if f.endswith(".json")),
)
def test_every_locale_says_what_the_state_means(locale):
"""The user-facing strings exist in all 21 locales and keep the
"""The user-facing strings exist in every locale and keep the
placeholders the state text interpolates."""
with open(os.path.join(LOCALES_DIR, f"{locale}.json"), encoding="utf-8") as fh:
settings = json.load(fh)["settings"]
+4 -4
View File
@@ -1,4 +1,4 @@
"""Locale key parity — all 21 i18n files stay in lockstep with en.json.
"""Locale key parity — every i18n file stay in lockstep with en.json.
Two catalogs exist. ``electron/src/renderer/src/i18n/locales`` is the one the
app loads at runtime; it must have full key parity (see the ``renderer``
@@ -17,7 +17,7 @@ tokens. Real bug classes this pins down:
Missing keys degrade gracefully (i18next falls back to en), so full key parity
is enforced as a RATCHET: each locale's missing-key count may only go down.
When en.json gains keys, add them to all 21 locales in the same change — that
When en.json gains keys, add them to every locale in the same change — that
is exactly the house rule this test automates.
"""
@@ -101,7 +101,7 @@ _ENGINE_AGNOSTIC_KEYS = (
# Never raise one: if this fails after adding en.json keys, add the keys to
# every locale (translated) in the same change instead.
_MISSING_BASELINE = {
"ar": 464, "de": 464, "es": 464, "fr": 464, "hi": 464, "id": 464,
"ar": 464, "de": 464, "es": 464, "fr": 464, "gl": 0, "hi": 464, "id": 464,
"it": 464, "ja": 464, "ko": 0, "nl": 464, "pl": 464, "pt": 464,
"ru": 464, "sv": 464, "th": 464, "tr": 464, "uk": 464, "vi": 464,
"zh-CN": 0, "zh-TW": 464,
@@ -224,7 +224,7 @@ def test_missing_keys_ratchet(locale):
allowed = _MISSING_BASELINE[locale]
assert len(missing) <= allowed, (
f"{locale}.json is missing {len(missing)} en.json keys — the ratchet "
f"allows at most {allowed}. New en.json keys must land in all 21 "
f"allows at most {allowed}. New en.json keys must land in all "
f"locales (translated) in the same change (CLAUDE.md, Localization). "
f"Newly missing keys include: {missing[:20]}"
)
+4 -3
View File
@@ -160,9 +160,10 @@ def test_every_locale_discloses_hugging_face_model_access():
import json
from pathlib import Path
locales = Path(__file__).resolve().parents[1] / "electron/src/shared/i18n/locales"
paths = sorted(locales.glob("*.json"))
assert len(paths) == 21
root = Path(__file__).resolve().parents[1] / "electron/src"
paths = sorted((root / "shared/i18n/locales").glob("*.json"))
renderer = {p.name for p in (root / "renderer/src/i18n/locales").glob("*.json")}
assert {p.name for p in paths} == renderer and "en.json" in renderer
for path in paths:
strings = json.loads(path.read_text("utf-8"))
footer = strings["license"]["pockettts_footer"]
+85
View File
@@ -0,0 +1,85 @@
"""Local CLI requests keep headers framed and endpoint checks DNS-free."""
from email import policy
from email.parser import BytesParser
import socket
import pytest
def test_multipart_filename_cannot_add_headers_and_fields_are_not_rewritten():
from speech_client.__main__ import _encode_multipart
audio = b"RIFF-synthetic-audio"
fields = {"model": "whisper-1", "prompt": "First line\r\nSecond line"}
body, content_type = _encode_multipart(
filename='clip.wav"\r\nX-Injected: yes', audio=audio,
fields=fields, boundary="synthetic-boundary",
)
message = BytesParser(policy=policy.default).parsebytes(
f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode() + body
)
parts = list(message.iter_parts())
assert len(parts) == 3
assert not any(part.get("X-Injected") for part in parts)
assert parts[-1].get_payload(decode=True) == audio
assert parts[1].get_payload(decode=True) == fields["prompt"].encode()
assert "\r" not in parts[-1].get_filename()
assert "\n" not in parts[-1].get_filename()
@pytest.mark.parametrize("host", ["2130706433", "0x7f000001", "127.1"])
def test_numeric_loopback_aliases_are_local_without_dns(monkeypatch, host):
from speech_client import __main__ as client
original = socket.getaddrinfo
calls = []
def numeric_only(*args, **kwargs):
assert kwargs.get("flags", 0) & socket.AI_NUMERICHOST
calls.append(args[0])
return original(*args, **kwargs)
monkeypatch.setattr(socket, "getaddrinfo", numeric_only)
assert client._is_loopback_host(host)
assert calls == [host]
@pytest.mark.parametrize("host", ["8.8.8.8", "gpu.example", "localhost.evil.example"])
def test_remote_addresses_never_gain_loopback_credentials(monkeypatch, host):
from speech_client import __main__ as client
def no_dns(*args, **kwargs):
assert kwargs.get("flags", 0) & socket.AI_NUMERICHOST
raise socket.gaierror("synthetic nonnumeric host")
monkeypatch.setattr(socket, "getaddrinfo", no_dns)
assert not client._is_loopback_host(host)
@pytest.mark.parametrize(
("url", "proxied"),
[
("http://127.1:3900/v1/x", False),
("http://localhost:3900/v1/x", False),
# e.g. the target of a redirect from an uncredentialed loopback request
("http://gpu.example/v1/x", True),
],
)
def test_only_loopback_requests_bypass_environment_proxies(monkeypatch, url, proxied):
from urllib import error, request
from speech_client import __main__ as client
monkeypatch.setenv("http_proxy", "http://proxy.example:8080")
monkeypatch.setenv("no_proxy", "")
seen = []
class _Record(request.HTTPHandler):
def http_open(self, req):
seen.append(req.has_proxy())
raise error.URLError("stop before network")
opener = request.build_opener(client._LoopbackDirectProxyHandler(), _Record())
with pytest.raises(error.URLError):
opener.open(request.Request(url))
assert seen == [proxied]
+5
View File
@@ -36,6 +36,11 @@ _CHANGE_CASES = [
("English", "It is 3:30 now", "It is three thirty now"),
("English", "At 3:00 sharp", "At three o'clock sharp"),
("English", "At 12:05 sharp", "At twelve oh five sharp"),
# A 24-hour time on the hour is read in hundreds, not with "o'clock".
("English", "Dinner at 19:00 sharp", "Dinner at nineteen hundred sharp"),
("English", "Closes at 0:00 tonight", "Closes at zero hundred tonight"),
("English", "At 12:00 sharp", "At twelve o'clock sharp"),
("English", "At 18:30 sharp", "At eighteen thirty sharp"),
("English", "the 21st of May", "the twenty-first of May"),
("English", "It costs $5", "It costs five dollars"),
("English", "Just $1 more", "Just one dollar more"),