VoiceStudio is the open-source, fully-local ElevenLabs alternative — voice cloning, voice design, video dubbing, dictation, transcription & audiobook creation in 646 languages.
Python aiaudiobookcudadubbingelevenlabs-alternativehuggingfacelocal-firstmlxomnivoice-studiospeech-to-texttext-to-speechtranscriptiontranslatettsvoice-aivoice-cloningvoice-generationvoicestudioworkflow
feat(mobile): report generated content from the phone apps
velixio4dab817e78d5
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex 63ad1c1a0..041e41b0f 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -427,6 +427,11 @@ hard rules from the first prompt.account features off sends one best-effort token revocation. Hidden inpackaged builds until VoiceStudio Cloud launches.- Bug reports as prefilled GitHub Issue URLs opened in the user's browser.+ - **Phone content reports, only when the user taps Send** in a generated+ result's Report sheet: `appapi.voicestudio.sh/v1/content-reports` with the+ reason, optional note and typed text, app version and model; no audio,+ account or device identifier (`mobile/contract/SPEC.md` → Reporting+ generated content; required by Google Play's AI-generated content policy).- PostHog analytics only after a yes at the first-run consent prompt(`backend/core/analytics.py`, allowlisted content-free metadata).- The GitHub star count (no credentials or referrer, refreshed every 20diff --git a/AGENTS.md b/AGENTS.mdindex 3b7a4cd60..9df898699 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -51,7 +51,7 @@ Binding for every AI agent (Claude, Codex, Cursor, review bots, …). CLAUDE.md## Change rules (see CLAUDE.md for full text)- Root-cause the class, not the instance; fail-before/pass-after regression test; smallest correct change.- Default behavior identical on macOS/Windows/Linux; platform-only features go behind explicit opt-in. Divergent default = P0.-- Local-first: no new required network calls; any HF download gated on installed-ness or explicit user action; all synthetic audio through the `mark_synthetic` chokepoint. Sanctioned calls are listed in `.github/CONTRIBUTING.md` → Quality gates: user-started first-run setup (ffmpeg from GitHub `zackees/ffmpeg_bins`, the huggingface.co/hf-mirror.com reachability probe, HF model downloads), opening/enabling the galleries (jsDelivr manifest, GitHub Releases), packaged update checks, user-clicked yt-dlp updates from PyPI, consent-gated analytics, prefilled-URL bug reports, the Pro licence check after a key is entered, and VoiceStudio Cloud sign-in/account calls (and settings sync once cloud sync is on) only after the user turns them on (off by default; switching off stops them at once). Owner-approved exception (2026-09-28): the public GitHub star count may refresh automatically every 20 minutes, without credentials/referrer or user content; offline use remains unaffected.+- Local-first: no new required network calls; any HF download gated on installed-ness or explicit user action; all synthetic audio through the `mark_synthetic` chokepoint. Sanctioned calls are listed in `.github/CONTRIBUTING.md` → Quality gates: user-started first-run setup (ffmpeg from GitHub `zackees/ffmpeg_bins`, the huggingface.co/hf-mirror.com reachability probe, HF model downloads), opening/enabling the galleries (jsDelivr manifest, GitHub Releases), packaged update checks, user-clicked yt-dlp updates from PyPI, consent-gated analytics, prefilled-URL bug reports, phone content reports sent from a result's Report sheet, the Pro licence check after a key is entered, and VoiceStudio Cloud sign-in/account calls (and settings sync once cloud sync is on) only after the user turns them on (off by default; switching off stops them at once). Owner-approved exception (2026-09-28): the public GitHub star count may refresh automatically every 20 minutes, without credentials/referrer or user content; offline use remains unaffected.- Every user-facing string via i18n, present in ALL 21 `electron/src/renderer/src/i18n/locales/*.json` files (the catalog the app loads) with real translations; `tests/test_locale_parity.py` and Electron `locale:check` enforce it. The legacy `electron/src/shared/i18n/` catalog is loaded only by shared-module tests.- Docs-sync in the same PR. CHANGELOG Unreleased: quiet one-liners ending `(#N)` + `— thanks @user!` for community work, under a short `**Highlights**` list.- Tagged release announcements lead with the biggest user-visible change; redesigns need real UI screenshots and migrations need installer links and steps. Verify all contributor credits from the tag comparison and included PRs; list authors and bug reporters separately (see `docs/RELEASING.md`).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 752d6f50f..5525edf3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ metadata and the backend fallback mirror it.### Added+- The phone apps have a Report action on every generated result: pick a reason, add an optional note, and it reaches the VoiceStudio team only when you tap Send (#PR)- The phone apps run speech, dictation, voice cloning and dubbing on the phone itself, offline once you download the models; pairing a computer is optional ([guide](docs/mobile.md)) (#2969)- Beta update channel: choose Stable or Beta under Settings → Updates; betas are `-beta.N` prereleases that never reach Stable users, and Docker gets matching `:beta` tags ([guide](docs/update-channels.md)) (#3175)diff --git a/CLAUDE.md b/CLAUDE.mdindex 71f242048..f656b4a8e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -40,7 +40,7 @@ Everything else (new engines, fancy features) is downstream of "the thing instal- **Cross-platform parity**: Every fix must work on macOS (Apple Silicon; Intel Macs are limited to the app UI with a remote backend, as README.md and `docs/install/macos.md` document), Windows (x64), and Linux (AppImage + deb). No platform-only regressions; the cross-platform bug bash (PR #51) is the baseline.- **Default features must work on every platform (strict rule, 2026-05-20):** A feature that ships in default mode — out-of-the-box, no user customization, no opt-in toggle — must behave identically on macOS, Windows, and Linux. Platform-specific *implementation code* is allowed for OS APIs / shells / packaging, but the user-visible *default behavior* cannot diverge. Platform-only features (e.g., a macOS-only global shortcut, a Windows-only path picker) must go behind explicit user opt-in: Settings toggle, env var, or CLI flag. When a default doesn't work on a platform, that's a P0 bug — either fix it on the missing platform or move it behind opt-in. No third option. **This rule governs BEHAVIOUR, not PERFORMANCE** (clarified 2026-07-30, council): hardware acceleration is expected to vary by host — CUDA, MPS, DirectML, Triton availability and `torch.compile` are all host-dependent by design, and reading the rule to forbid that would forbid GPU support itself. An optimization that is skipped where it cannot work (missing Triton, an arch the wheel lacks, a path its toolchain cannot link) is NOT a parity violation; a *feature* the user can see and use on one OS but not another is.- **Backward-compatible project data**: Existing `omnivoice_data/` (user voices, projects, settings) must keep working without manual migration. Any DB schema change goes through alembic with a tested upgrade path.-- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Auto bug reporting is opt-in and submits only to GitHub Issues (prefilled-URL, from the user's own browser). Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in PostHog US with a **first-run consent prompt** — two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — carries the in-repo publishable write-only token and shows the same consent ask, with env/baked token overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); packaged update checks against GitHub Releases (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on, all stopped at once when switched off. Narrow owner-approved exception (2026-09-28): the GitHub Star badge may fetch the public repository star count when shown and refresh every 20 minutes while visible, without credentials or a referrer. It sends no project, recording, or account data, retains the last count on failure, and never blocks offline use.+- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Auto bug reporting is opt-in and submits only to GitHub Issues (prefilled-URL, from the user's own browser). Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in PostHog US with a **first-run consent prompt** — two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — carries the in-repo publishable write-only token and shows the same consent ask, with env/baked token overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); packaged update checks against GitHub Releases (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; phone content reports to `appapi.voicestudio.sh/v1/content-reports`, only when the user taps Send on a result's Report sheet (`mobile/contract/SPEC.md`); and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on, all stopped at once when switched off. Narrow owner-approved exception (2026-09-28): the GitHub Star badge may fetch the public repository star count when shown and refresh every 20 minutes while visible, without credentials or a referrer. It sends no project, recording, or account data, retains the last count on failure, and never blocks offline use.- **Beta release cadence (no RC, no ceremony — strict rule, 2026-05-20):** the current release line (0.5.x today) has **no release candidates, no 48h soak, no formal release ceremony**. Every fix goes continuous-to-main; the owner tags a patch from main whenever the current state is worth cutting. No `-rc` tags. No phased release. The one sanctioned prerelease is the opt-in **Beta channel** (owner-approved 2026-10-22): `vX.Y.Z-beta.N` tags cut from `main`, published as GitHub prereleases that never become `latest`, with their own `electron-beta-*` update feed and `:beta` Docker tag (see `docs/RELEASING.md` → Beta channel). It adds no soak, ceremony or side branch. No deferrals to a future minor or major version — every open issue and every open community PR gets absorbed into the current line or explicitly declined. Users follow `main` for previews; users wanting stable stay on the latest tagged release.<!-- GSD:project-end -->diff --git a/docs/mobile.md b/docs/mobile.mdindex dcf4a8e4b..471829168 100644--- a/docs/mobile.md+++ b/docs/mobile.md@@ -65,6 +65,15 @@ run are shown greyed out with the reason.Plain `http://` works only for addresses on your own network (home Wi-Fi,`.local`, Tailscale); everything else must be `https://`.+## Report a result++Every generated result (a Speak take, a cloned voice, a finished dub) has a+**Report** action. Pick what's wrong, optionally add a note or the text you+typed, and tap **Send report**. It sends only the reason, your note, that text+if you ticked it, the app version and the model that made the result to the+VoiceStudio team; no audio, account or device ID. Nothing is sent until you tap+Send, and reports are deleted after 180 days.+## If something doesn't work- **"Accept the licence on your computer"**: some models need their licencediff --git a/electron/src/renderer/src/i18n/locales/ar.json b/electron/src/renderer/src/i18n/locales/ar.jsonindex bbbc2c49a..6b24b5162 100644--- a/electron/src/renderer/src/i18n/locales/ar.json+++ b/electron/src/renderer/src/i18n/locales/ar.json@@ -3870,6 +3870,28 @@},"consent": {"phone_note": "يُحفظ على هذا الهاتف. لا يُرسل شيء."+ },+ "report": {+ "action": "إبلاغ",+ "title": "الإبلاغ عن هذه النتيجة",+ "reason": "ما المشكلة؟",+ "reasons": {+ "sexual": "محتوى جنسي",+ "hateful": "محتوى يحض على الكراهية أو مسيء",+ "impersonation": "انتحال شخصية أو صوت مستنسخ دون موافقة",+ "misleading": "مضلل أو ضار",+ "other": "شيء آخر"+ },+ "note": "تفاصيل (اختياري)",+ "include_text": "تضمين النص الذي أدخلته",+ "disclosure": "يرسل سببك وملاحظتك وإصدار التطبيق والنموذج الذي أنشأ هذا إلى فريق VoiceStudio. لا يُرسل أي صوت أو حساب أو معرّف للجهاز.",+ "send": "إرسال البلاغ",+ "sending": "جارٍ الإرسال…",+ "sent": "تم إرسال البلاغ. شكرًا لك.",+ "failed": "تعذّر إرسال البلاغ. تحقق من اتصالك وحاول مرة أخرى.",+ "retry": "إعادة المحاولة",+ "rate_limited": "بلاغات كثيرة جدًا من هذه الشبكة. حاول لاحقًا.",+ "invalid": "تعذّر إرسال هذا البلاغ. حدّث التطبيق وحاول مرة أخرى."}}}diff --git a/electron/src/renderer/src/i18n/locales/de.json b/electron/src/renderer/src/i18n/locales/de.jsonindex fc4e3e8a7..43f31aee2 100644--- a/electron/src/renderer/src/i18n/locales/de.json+++ b/electron/src/renderer/src/i18n/locales/de.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Gespeichert auf diesem Telefon. Es wird nichts gesendet."+ },+ "report": {+ "action": "Melden",+ "title": "Dieses Ergebnis melden",+ "reason": "Was stimmt damit nicht?",+ "reasons": {+ "sexual": "Sexuelle Inhalte",+ "hateful": "Hasserfüllt oder beleidigend",+ "impersonation": "Identitätsdiebstahl oder ohne Einwilligung geklonte Stimme",+ "misleading": "Irreführend oder schädlich",+ "other": "Etwas anderes"+ },+ "note": "Details (optional)",+ "include_text": "Den eingegebenen Text mitsenden",+ "disclosure": "Sendet deinen Grund, deine Notiz, die App-Version und das verwendete Modell an das VoiceStudio-Team. Es werden kein Audio, kein Konto und keine Geräte-ID gesendet.",+ "send": "Meldung senden",+ "sending": "Wird gesendet…",+ "sent": "Meldung gesendet. Danke.",+ "failed": "Die Meldung konnte nicht gesendet werden. Prüfe deine Verbindung und versuche es erneut.",+ "retry": "Erneut versuchen",+ "rate_limited": "Zu viele Meldungen aus diesem Netzwerk. Versuche es später erneut.",+ "invalid": "Diese Meldung konnte nicht gesendet werden. Aktualisiere die App und versuche es erneut."}}}diff --git a/electron/src/renderer/src/i18n/locales/en.json b/electron/src/renderer/src/i18n/locales/en.jsonindex ed99fafd5..87d3e2932 100644--- a/electron/src/renderer/src/i18n/locales/en.json+++ b/electron/src/renderer/src/i18n/locales/en.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Saved on this phone. Nothing is sent."+ },+ "report": {+ "action": "Report",+ "title": "Report this result",+ "reason": "What's wrong with it?",+ "reasons": {+ "sexual": "Sexual content",+ "hateful": "Hateful or abusive",+ "impersonation": "Impersonation or a voice cloned without consent",+ "misleading": "Misleading or harmful",+ "other": "Something else"+ },+ "note": "Details (optional)",+ "include_text": "Include the text I entered",+ "disclosure": "Sends your reason, note, the app version and the model that made this to the VoiceStudio team. No audio, account or device ID is sent.",+ "send": "Send report",+ "sending": "Sending…",+ "sent": "Report sent. Thank you.",+ "failed": "Couldn't send the report. Check your connection and try again.",+ "retry": "Try again",+ "rate_limited": "Too many reports from this network. Try again later.",+ "invalid": "This report couldn't be sent. Update the app and try again."}}}diff --git a/electron/src/renderer/src/i18n/locales/es.json b/electron/src/renderer/src/i18n/locales/es.jsonindex 8742be556..7def8b160 100644--- a/electron/src/renderer/src/i18n/locales/es.json+++ b/electron/src/renderer/src/i18n/locales/es.json@@ -3864,6 +3864,28 @@},"consent": {"phone_note": "Guardado en este teléfono. No se envía nada."+ },+ "report": {+ "action": "Denunciar",+ "title": "Denunciar este resultado",+ "reason": "¿Qué problema tiene?",+ "reasons": {+ "sexual": "Contenido sexual",+ "hateful": "Odio o abuso",+ "impersonation": "Suplantación o voz clonada sin consentimiento",+ "misleading": "Engañoso o dañino",+ "other": "Otra cosa"+ },+ "note": "Detalles (opcional)",+ "include_text": "Incluir el texto que escribí",+ "disclosure": "Envía tu motivo, tu nota, la versión de la app y el modelo que lo generó al equipo de VoiceStudio. No se envía audio, cuenta ni ID del dispositivo.",+ "send": "Enviar denuncia",+ "sending": "Enviando…",+ "sent": "Denuncia enviada. Gracias.",+ "failed": "No se pudo enviar la denuncia. Comprueba tu conexión e inténtalo de nuevo.",+ "retry": "Reintentar",+ "rate_limited": "Demasiadas denuncias desde esta red. Inténtalo más tarde.",+ "invalid": "No se pudo enviar esta denuncia. Actualiza la app e inténtalo de nuevo."}}}diff --git a/electron/src/renderer/src/i18n/locales/fr.json b/electron/src/renderer/src/i18n/locales/fr.jsonindex e7bce230d..103998dab 100644--- a/electron/src/renderer/src/i18n/locales/fr.json+++ b/electron/src/renderer/src/i18n/locales/fr.json@@ -3864,6 +3864,28 @@},"consent": {"phone_note": "Enregistré sur ce téléphone. Rien n'est envoyé."+ },+ "report": {+ "action": "Signaler",+ "title": "Signaler ce résultat",+ "reason": "Quel est le problème ?",+ "reasons": {+ "sexual": "Contenu sexuel",+ "hateful": "Haineux ou abusif",+ "impersonation": "Usurpation d'identité ou voix clonée sans consentement",+ "misleading": "Trompeur ou dangereux",+ "other": "Autre chose"+ },+ "note": "Détails (facultatif)",+ "include_text": "Inclure le texte que j'ai saisi",+ "disclosure": "Envoie votre motif, votre note, la version de l'app et le modèle utilisé à l'équipe VoiceStudio. Aucun audio, compte ni identifiant d'appareil n'est envoyé.",+ "send": "Envoyer le signalement",+ "sending": "Envoi…",+ "sent": "Signalement envoyé. Merci.",+ "failed": "Impossible d'envoyer le signalement. Vérifiez votre connexion et réessayez.",+ "retry": "Réessayer",+ "rate_limited": "Trop de signalements depuis ce réseau. Réessayez plus tard.",+ "invalid": "Ce signalement n'a pas pu être envoyé. Mettez l'app à jour et réessayez."}}}diff --git a/electron/src/renderer/src/i18n/locales/hi.json b/electron/src/renderer/src/i18n/locales/hi.jsonindex 43a505473..bbd7db7cd 100644--- a/electron/src/renderer/src/i18n/locales/hi.json+++ b/electron/src/renderer/src/i18n/locales/hi.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "इसी फ़ोन पर सहेजा गया। कुछ भी भेजा नहीं जाता।"+ },+ "report": {+ "action": "रिपोर्ट करें",+ "title": "इस परिणाम की रिपोर्ट करें",+ "reason": "इसमें क्या गलत है?",+ "reasons": {+ "sexual": "यौन सामग्री",+ "hateful": "घृणास्पद या अपमानजनक",+ "impersonation": "किसी का रूप धरना या बिना सहमति क्लोन की गई आवाज़",+ "misleading": "भ्रामक या हानिकारक",+ "other": "कुछ और"+ },+ "note": "विवरण (वैकल्पिक)",+ "include_text": "मेरे द्वारा लिखा गया टेक्स्ट शामिल करें",+ "disclosure": "आपका कारण, नोट, ऐप संस्करण और इसे बनाने वाला मॉडल VoiceStudio टीम को भेजता है। कोई ऑडियो, खाता या डिवाइस ID नहीं भेजा जाता।",+ "send": "रिपोर्ट भेजें",+ "sending": "भेजा जा रहा है…",+ "sent": "रिपोर्ट भेज दी गई। धन्यवाद।",+ "failed": "रिपोर्ट नहीं भेजी जा सकी। अपना कनेक्शन जांचें और फिर से कोशिश करें।",+ "retry": "फिर से कोशिश करें",+ "rate_limited": "इस नेटवर्क से बहुत अधिक रिपोर्ट। बाद में फिर से कोशिश करें।",+ "invalid": "यह रिपोर्ट नहीं भेजी जा सकी। ऐप अपडेट करें और फिर से कोशिश करें।"}}}diff --git a/electron/src/renderer/src/i18n/locales/id.json b/electron/src/renderer/src/i18n/locales/id.jsonindex fb9993a7c..a9bd819d4 100644--- a/electron/src/renderer/src/i18n/locales/id.json+++ b/electron/src/renderer/src/i18n/locales/id.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Disimpan di ponsel ini. Tidak ada yang dikirim."+ },+ "report": {+ "action": "Laporkan",+ "title": "Laporkan hasil ini",+ "reason": "Apa masalahnya?",+ "reasons": {+ "sexual": "Konten seksual",+ "hateful": "Kebencian atau pelecehan",+ "impersonation": "Peniruan identitas atau suara yang dikloning tanpa izin",+ "misleading": "Menyesatkan atau berbahaya",+ "other": "Lainnya"+ },+ "note": "Detail (opsional)",+ "include_text": "Sertakan teks yang saya masukkan",+ "disclosure": "Mengirim alasan, catatan, versi aplikasi, dan model yang membuat ini ke tim VoiceStudio. Tidak ada audio, akun, atau ID perangkat yang dikirim.",+ "send": "Kirim laporan",+ "sending": "Mengirim…",+ "sent": "Laporan terkirim. Terima kasih.",+ "failed": "Laporan tidak dapat dikirim. Periksa koneksi Anda dan coba lagi.",+ "retry": "Coba lagi",+ "rate_limited": "Terlalu banyak laporan dari jaringan ini. Coba lagi nanti.",+ "invalid": "Laporan ini tidak dapat dikirim. Perbarui aplikasi dan coba lagi."}}}diff --git a/electron/src/renderer/src/i18n/locales/it.json b/electron/src/renderer/src/i18n/locales/it.jsonindex 55d1ae78b..0671d0e18 100644--- a/electron/src/renderer/src/i18n/locales/it.json+++ b/electron/src/renderer/src/i18n/locales/it.json@@ -3864,6 +3864,28 @@},"consent": {"phone_note": "Salvato su questo telefono. Non viene inviato nulla."+ },+ "report": {+ "action": "Segnala",+ "title": "Segnala questo risultato",+ "reason": "Qual è il problema?",+ "reasons": {+ "sexual": "Contenuti sessuali",+ "hateful": "Odio o abusi",+ "impersonation": "Impersonificazione o voce clonata senza consenso",+ "misleading": "Fuorviante o dannoso",+ "other": "Altro"+ },+ "note": "Dettagli (facoltativo)",+ "include_text": "Includi il testo che ho inserito",+ "disclosure": "Invia al team di VoiceStudio il motivo, la nota, la versione dell'app e il modello usato. Non vengono inviati audio, account né ID del dispositivo.",+ "send": "Invia segnalazione",+ "sending": "Invio…",+ "sent": "Segnalazione inviata. Grazie.",+ "failed": "Impossibile inviare la segnalazione. Controlla la connessione e riprova.",+ "retry": "Riprova",+ "rate_limited": "Troppe segnalazioni da questa rete. Riprova più tardi.",+ "invalid": "Impossibile inviare questa segnalazione. Aggiorna l'app e riprova."}}}diff --git a/electron/src/renderer/src/i18n/locales/ja.json b/electron/src/renderer/src/i18n/locales/ja.jsonindex c2bc2a8f8..7d3dda919 100644--- a/electron/src/renderer/src/i18n/locales/ja.json+++ b/electron/src/renderer/src/i18n/locales/ja.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "このスマートフォンに保存されます。何も送信されません。"+ },+ "report": {+ "action": "報告",+ "title": "この結果を報告",+ "reason": "どのような問題がありますか?",+ "reasons": {+ "sexual": "性的なコンテンツ",+ "hateful": "憎悪的または攻撃的",+ "impersonation": "なりすまし、または同意なく複製された声",+ "misleading": "誤解を招く、または有害",+ "other": "その他"+ },+ "note": "詳細(任意)",+ "include_text": "入力したテキストを含める",+ "disclosure": "理由、メモ、アプリのバージョン、生成したモデルを VoiceStudio チームに送信します。音声、アカウント、端末 ID は送信されません。",+ "send": "報告を送信",+ "sending": "送信中…",+ "sent": "報告を送信しました。ありがとうございます。",+ "failed": "報告を送信できませんでした。接続を確認して、もう一度お試しください。",+ "retry": "再試行",+ "rate_limited": "このネットワークからの報告が多すぎます。しばらくしてからお試しください。",+ "invalid": "この報告を送信できませんでした。アプリを更新して、もう一度お試しください。"}}}diff --git a/electron/src/renderer/src/i18n/locales/ko.json b/electron/src/renderer/src/i18n/locales/ko.jsonindex 5c861c1c0..0a2654702 100644--- a/electron/src/renderer/src/i18n/locales/ko.json+++ b/electron/src/renderer/src/i18n/locales/ko.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "이 휴대폰에 저장됩니다. 아무것도 전송되지 않습니다."+ },+ "report": {+ "action": "신고",+ "title": "이 결과 신고",+ "reason": "어떤 문제가 있나요?",+ "reasons": {+ "sexual": "성적인 콘텐츠",+ "hateful": "혐오 또는 모욕",+ "impersonation": "사칭 또는 동의 없이 복제된 목소리",+ "misleading": "오해의 소지가 있거나 유해함",+ "other": "기타"+ },+ "note": "세부 정보(선택 사항)",+ "include_text": "입력한 텍스트 포함",+ "disclosure": "신고 사유, 메모, 앱 버전, 이 결과를 만든 모델을 VoiceStudio 팀에 보냅니다. 오디오, 계정, 기기 ID는 보내지 않습니다.",+ "send": "신고 보내기",+ "sending": "보내는 중…",+ "sent": "신고를 보냈습니다. 감사합니다.",+ "failed": "신고를 보내지 못했습니다. 연결을 확인하고 다시 시도하세요.",+ "retry": "다시 시도",+ "rate_limited": "이 네트워크에서 신고가 너무 많습니다. 나중에 다시 시도하세요.",+ "invalid": "이 신고를 보낼 수 없습니다. 앱을 업데이트하고 다시 시도하세요."}}}diff --git a/electron/src/renderer/src/i18n/locales/nl.json b/electron/src/renderer/src/i18n/locales/nl.jsonindex 79a5650cc..327846978 100644--- a/electron/src/renderer/src/i18n/locales/nl.json+++ b/electron/src/renderer/src/i18n/locales/nl.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Opgeslagen op deze telefoon. Er wordt niets verzonden."+ },+ "report": {+ "action": "Melden",+ "title": "Dit resultaat melden",+ "reason": "Wat is er mis mee?",+ "reasons": {+ "sexual": "Seksuele inhoud",+ "hateful": "Haatdragend of beledigend",+ "impersonation": "Imitatie of een stem gekloond zonder toestemming",+ "misleading": "Misleidend of schadelijk",+ "other": "Iets anders"+ },+ "note": "Details (optioneel)",+ "include_text": "De tekst die ik invoerde meesturen",+ "disclosure": "Stuurt je reden, notitie, de app-versie en het gebruikte model naar het VoiceStudio-team. Er wordt geen audio, account of apparaat-ID verstuurd.",+ "send": "Melding versturen",+ "sending": "Versturen…",+ "sent": "Melding verstuurd. Bedankt.",+ "failed": "De melding kon niet worden verstuurd. Controleer je verbinding en probeer het opnieuw.",+ "retry": "Opnieuw proberen",+ "rate_limited": "Te veel meldingen vanaf dit netwerk. Probeer het later opnieuw.",+ "invalid": "Deze melding kon niet worden verstuurd. Werk de app bij en probeer het opnieuw."}}}diff --git a/electron/src/renderer/src/i18n/locales/pl.json b/electron/src/renderer/src/i18n/locales/pl.jsonindex e9a03ffcc..b99518a06 100644--- a/electron/src/renderer/src/i18n/locales/pl.json+++ b/electron/src/renderer/src/i18n/locales/pl.json@@ -3868,6 +3868,28 @@},"consent": {"phone_note": "Zapisano na tym telefonie. Nic nie jest wysyłane."+ },+ "report": {+ "action": "Zgłoś",+ "title": "Zgłoś ten wynik",+ "reason": "Co jest nie tak?",+ "reasons": {+ "sexual": "Treści seksualne",+ "hateful": "Nienawiść lub nękanie",+ "impersonation": "Podszywanie się lub głos sklonowany bez zgody",+ "misleading": "Wprowadzające w błąd lub szkodliwe",+ "other": "Coś innego"+ },+ "note": "Szczegóły (opcjonalnie)",+ "include_text": "Dołącz wpisany przeze mnie tekst",+ "disclosure": "Wysyła powód, notatkę, wersję aplikacji i użyty model do zespołu VoiceStudio. Nie są wysyłane nagrania, konto ani identyfikator urządzenia.",+ "send": "Wyślij zgłoszenie",+ "sending": "Wysyłanie…",+ "sent": "Zgłoszenie wysłane. Dziękujemy.",+ "failed": "Nie udało się wysłać zgłoszenia. Sprawdź połączenie i spróbuj ponownie.",+ "retry": "Spróbuj ponownie",+ "rate_limited": "Zbyt wiele zgłoszeń z tej sieci. Spróbuj później.",+ "invalid": "Nie udało się wysłać tego zgłoszenia. Zaktualizuj aplikację i spróbuj ponownie."}}}diff --git a/electron/src/renderer/src/i18n/locales/pt.json b/electron/src/renderer/src/i18n/locales/pt.jsonindex ea7e45c5e..3034d36f4 100644--- a/electron/src/renderer/src/i18n/locales/pt.json+++ b/electron/src/renderer/src/i18n/locales/pt.json@@ -3864,6 +3864,28 @@},"consent": {"phone_note": "Salvo neste celular. Nada é enviado."+ },+ "report": {+ "action": "Denunciar",+ "title": "Denunciar este resultado",+ "reason": "Qual é o problema?",+ "reasons": {+ "sexual": "Conteúdo sexual",+ "hateful": "Ódio ou abuso",+ "impersonation": "Falsificação de identidade ou voz clonada sem consentimento",+ "misleading": "Enganoso ou prejudicial",+ "other": "Outra coisa"+ },+ "note": "Detalhes (opcional)",+ "include_text": "Incluir o texto que digitei",+ "disclosure": "Envia o motivo, a nota, a versão do app e o modelo usado para a equipe do VoiceStudio. Nenhum áudio, conta ou ID do dispositivo é enviado.",+ "send": "Enviar denúncia",+ "sending": "Enviando…",+ "sent": "Denúncia enviada. Obrigado.",+ "failed": "Não foi possível enviar a denúncia. Verifique sua conexão e tente novamente.",+ "retry": "Tentar novamente",+ "rate_limited": "Muitas denúncias desta rede. Tente mais tarde.",+ "invalid": "Não foi possível enviar esta denúncia. Atualize o app e tente novamente."}}}diff --git a/electron/src/renderer/src/i18n/locales/ru.json b/electron/src/renderer/src/i18n/locales/ru.jsonindex 6be0e207f..35e9b81ff 100644--- a/electron/src/renderer/src/i18n/locales/ru.json+++ b/electron/src/renderer/src/i18n/locales/ru.json@@ -3868,6 +3868,28 @@},"consent": {"phone_note": "Сохранено на этом телефоне. Ничего не отправляется."+ },+ "report": {+ "action": "Пожаловаться",+ "title": "Пожаловаться на результат",+ "reason": "Что не так?",+ "reasons": {+ "sexual": "Сексуальный контент",+ "hateful": "Ненависть или оскорбления",+ "impersonation": "Выдача себя за другого или голос, клонированный без согласия",+ "misleading": "Вводит в заблуждение или вредит",+ "other": "Другое"+ },+ "note": "Подробности (необязательно)",+ "include_text": "Приложить введённый мной текст",+ "disclosure": "Отправляет команде VoiceStudio причину, комментарий, версию приложения и использованную модель. Аудио, аккаунт и идентификатор устройства не отправляются.",+ "send": "Отправить жалобу",+ "sending": "Отправка…",+ "sent": "Жалоба отправлена. Спасибо.",+ "failed": "Не удалось отправить жалобу. Проверьте подключение и попробуйте снова.",+ "retry": "Повторить",+ "rate_limited": "Слишком много жалоб из этой сети. Попробуйте позже.",+ "invalid": "Не удалось отправить эту жалобу. Обновите приложение и попробуйте снова."}}}diff --git a/electron/src/renderer/src/i18n/locales/sv.json b/electron/src/renderer/src/i18n/locales/sv.jsonindex 0e74e33ad..5874f0366 100644--- a/electron/src/renderer/src/i18n/locales/sv.json+++ b/electron/src/renderer/src/i18n/locales/sv.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Sparas på telefonen. Ingenting skickas."+ },+ "report": {+ "action": "Rapportera",+ "title": "Rapportera det här resultatet",+ "reason": "Vad är fel?",+ "reasons": {+ "sexual": "Sexuellt innehåll",+ "hateful": "Hatiskt eller kränkande",+ "impersonation": "Imitation eller en röst klonad utan samtycke",+ "misleading": "Vilseledande eller skadligt",+ "other": "Något annat"+ },+ "note": "Detaljer (valfritt)",+ "include_text": "Ta med texten jag skrev",+ "disclosure": "Skickar din anledning, anteckning, appversionen och modellen som skapade detta till VoiceStudio-teamet. Inget ljud, konto eller enhets-ID skickas.",+ "send": "Skicka rapport",+ "sending": "Skickar…",+ "sent": "Rapporten har skickats. Tack.",+ "failed": "Det gick inte att skicka rapporten. Kontrollera anslutningen och försök igen.",+ "retry": "Försök igen",+ "rate_limited": "För många rapporter från det här nätverket. Försök igen senare.",+ "invalid": "Rapporten kunde inte skickas. Uppdatera appen och försök igen."}}}diff --git a/electron/src/renderer/src/i18n/locales/th.json b/electron/src/renderer/src/i18n/locales/th.jsonindex 04297af42..891851c7f 100644--- a/electron/src/renderer/src/i18n/locales/th.json+++ b/electron/src/renderer/src/i18n/locales/th.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "บันทึกในโทรศัพท์เครื่องนี้ ไม่มีการส่งข้อมูลใดๆ"+ },+ "report": {+ "action": "รายงาน",+ "title": "รายงานผลลัพธ์นี้",+ "reason": "มีปัญหาอะไร",+ "reasons": {+ "sexual": "เนื้อหาทางเพศ",+ "hateful": "แสดงความเกลียดชังหรือหยาบคาย",+ "impersonation": "การแอบอ้างตัวตนหรือเสียงที่โคลนโดยไม่ได้รับความยินยอม",+ "misleading": "ทำให้เข้าใจผิดหรือเป็นอันตราย",+ "other": "อื่นๆ"+ },+ "note": "รายละเอียด (ไม่บังคับ)",+ "include_text": "แนบข้อความที่ฉันพิมพ์",+ "disclosure": "ส่งเหตุผล บันทึก เวอร์ชันแอป และโมเดลที่สร้างสิ่งนี้ไปยังทีม VoiceStudio ไม่มีการส่งเสียง บัญชี หรือรหัสอุปกรณ์",+ "send": "ส่งรายงาน",+ "sending": "กำลังส่ง…",+ "sent": "ส่งรายงานแล้ว ขอบคุณ",+ "failed": "ส่งรายงานไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง",+ "retry": "ลองอีกครั้ง",+ "rate_limited": "มีรายงานจากเครือข่ายนี้มากเกินไป โปรดลองใหม่ภายหลัง",+ "invalid": "ส่งรายงานนี้ไม่ได้ อัปเดตแอปแล้วลองอีกครั้ง"}}}diff --git a/electron/src/renderer/src/i18n/locales/tr.json b/electron/src/renderer/src/i18n/locales/tr.jsonindex 5ac1d2c8c..f16a79539 100644--- a/electron/src/renderer/src/i18n/locales/tr.json+++ b/electron/src/renderer/src/i18n/locales/tr.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Bu telefonda saklanır. Hiçbir şey gönderilmez."+ },+ "report": {+ "action": "Bildir",+ "title": "Bu sonucu bildir",+ "reason": "Sorun nedir?",+ "reasons": {+ "sexual": "Cinsel içerik",+ "hateful": "Nefret içeren veya taciz edici",+ "impersonation": "Kimliğe bürünme veya izinsiz klonlanmış ses",+ "misleading": "Yanıltıcı veya zararlı",+ "other": "Başka bir şey"+ },+ "note": "Ayrıntılar (isteğe bağlı)",+ "include_text": "Girdiğim metni ekle",+ "disclosure": "Nedeninizi, notunuzu, uygulama sürümünü ve bunu üreten modeli VoiceStudio ekibine gönderir. Ses, hesap veya cihaz kimliği gönderilmez.",+ "send": "Bildirimi gönder",+ "sending": "Gönderiliyor…",+ "sent": "Bildirim gönderildi. Teşekkürler.",+ "failed": "Bildirim gönderilemedi. Bağlantınızı kontrol edip tekrar deneyin.",+ "retry": "Tekrar dene",+ "rate_limited": "Bu ağdan çok fazla bildirim geldi. Daha sonra tekrar deneyin.",+ "invalid": "Bu bildirim gönderilemedi. Uygulamayı güncelleyip tekrar deneyin."}}}diff --git a/electron/src/renderer/src/i18n/locales/uk.json b/electron/src/renderer/src/i18n/locales/uk.jsonindex 653ac63b9..b98ed8874 100644--- a/electron/src/renderer/src/i18n/locales/uk.json+++ b/electron/src/renderer/src/i18n/locales/uk.json@@ -3868,6 +3868,28 @@},"consent": {"phone_note": "Збережено на цьому телефоні. Нічого не надсилається."+ },+ "report": {+ "action": "Поскаржитися",+ "title": "Поскаржитися на результат",+ "reason": "Що не так?",+ "reasons": {+ "sexual": "Сексуальний вміст",+ "hateful": "Ненависть або образи",+ "impersonation": "Видавання себе за іншого або голос, клонований без згоди",+ "misleading": "Вводить в оману або шкодить",+ "other": "Інше"+ },+ "note": "Подробиці (необов'язково)",+ "include_text": "Додати введений мною текст",+ "disclosure": "Надсилає команді VoiceStudio причину, коментар, версію застосунку й використану модель. Аудіо, обліковий запис та ідентифікатор пристрою не надсилаються.",+ "send": "Надіслати скаргу",+ "sending": "Надсилання…",+ "sent": "Скаргу надіслано. Дякуємо.",+ "failed": "Не вдалося надіслати скаргу. Перевірте з'єднання й спробуйте ще раз.",+ "retry": "Спробувати ще раз",+ "rate_limited": "Забагато скарг із цієї мережі. Спробуйте пізніше.",+ "invalid": "Не вдалося надіслати цю скаргу. Оновіть застосунок і спробуйте ще раз."}}}diff --git a/electron/src/renderer/src/i18n/locales/vi.json b/electron/src/renderer/src/i18n/locales/vi.jsonindex 4d41922c4..bdfa82fc8 100644--- a/electron/src/renderer/src/i18n/locales/vi.json+++ b/electron/src/renderer/src/i18n/locales/vi.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "Lưu trên điện thoại này. Không gửi gì cả."+ },+ "report": {+ "action": "Báo cáo",+ "title": "Báo cáo kết quả này",+ "reason": "Có vấn đề gì?",+ "reasons": {+ "sexual": "Nội dung tình dục",+ "hateful": "Thù ghét hoặc lăng mạ",+ "impersonation": "Mạo danh hoặc giọng nói bị nhân bản khi chưa được đồng ý",+ "misleading": "Gây hiểu lầm hoặc có hại",+ "other": "Lý do khác"+ },+ "note": "Chi tiết (không bắt buộc)",+ "include_text": "Kèm văn bản tôi đã nhập",+ "disclosure": "Gửi lý do, ghi chú, phiên bản ứng dụng và mô hình đã tạo nội dung này đến nhóm VoiceStudio. Không gửi âm thanh, tài khoản hay ID thiết bị.",+ "send": "Gửi báo cáo",+ "sending": "Đang gửi…",+ "sent": "Đã gửi báo cáo. Cảm ơn bạn.",+ "failed": "Không thể gửi báo cáo. Hãy kiểm tra kết nối và thử lại.",+ "retry": "Thử lại",+ "rate_limited": "Quá nhiều báo cáo từ mạng này. Hãy thử lại sau.",+ "invalid": "Không thể gửi báo cáo này. Hãy cập nhật ứng dụng và thử lại."}}}diff --git a/electron/src/renderer/src/i18n/locales/zh-CN.json b/electron/src/renderer/src/i18n/locales/zh-CN.jsonindex 57d639f76..ae4e163cc 100644--- a/electron/src/renderer/src/i18n/locales/zh-CN.json+++ b/electron/src/renderer/src/i18n/locales/zh-CN.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "保存在这部手机上,不会发送任何内容。"+ },+ "report": {+ "action": "举报",+ "title": "举报此结果",+ "reason": "有什么问题?",+ "reasons": {+ "sexual": "色情内容",+ "hateful": "仇恨或辱骂",+ "impersonation": "冒充他人或未经同意克隆的声音",+ "misleading": "误导或有害",+ "other": "其他"+ },+ "note": "详细说明(可选)",+ "include_text": "附上我输入的文字",+ "disclosure": "将你的举报原因、说明、应用版本和生成此内容的模型发送给 VoiceStudio 团队。不会发送音频、账号或设备 ID。",+ "send": "发送举报",+ "sending": "正在发送…",+ "sent": "举报已发送,谢谢。",+ "failed": "无法发送举报。请检查网络连接后重试。",+ "retry": "重试",+ "rate_limited": "此网络的举报次数过多,请稍后再试。",+ "invalid": "无法发送此举报。请更新应用后重试。"}}}diff --git a/electron/src/renderer/src/i18n/locales/zh-TW.json b/electron/src/renderer/src/i18n/locales/zh-TW.jsonindex cc5325260..088eed273 100644--- a/electron/src/renderer/src/i18n/locales/zh-TW.json+++ b/electron/src/renderer/src/i18n/locales/zh-TW.json@@ -3862,6 +3862,28 @@},"consent": {"phone_note": "儲存在這支手機上,不會傳送任何內容。"+ },+ "report": {+ "action": "檢舉",+ "title": "檢舉此結果",+ "reason": "有什麼問題?",+ "reasons": {+ "sexual": "色情內容",+ "hateful": "仇恨或辱罵",+ "impersonation": "冒充他人或未經同意複製的聲音",+ "misleading": "誤導或有害",+ "other": "其他"+ },+ "note": "詳細說明(選填)",+ "include_text": "附上我輸入的文字",+ "disclosure": "將你的檢舉原因、說明、應用程式版本和產生此內容的模型傳送給 VoiceStudio 團隊。不會傳送音訊、帳號或裝置 ID。",+ "send": "傳送檢舉",+ "sending": "正在傳送…",+ "sent": "檢舉已傳送,謝謝。",+ "failed": "無法傳送檢舉。請檢查網路連線後重試。",+ "retry": "重試",+ "rate_limited": "此網路的檢舉次數過多,請稍後再試。",+ "invalid": "無法傳送此檢舉。請更新應用程式後重試。"}}}diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.ktsindex 01ef80924..94ec7ac92 100644--- a/mobile/android/app/build.gradle.kts+++ b/mobile/android/app/build.gradle.kts@@ -37,6 +37,11 @@ android {}buildTypes.getByName("release").signingConfig = signingConfigs.getByName("upload")}+ // Content reports (mobile/contract/SPEC.md): debug builds never reach the production app API.+ buildTypes {+ getByName("debug") { buildConfigField("String", "CONTENT_REPORTS_URL", "\"https://dev-appapi.voicestudio.sh\"") }+ getByName("release") { buildConfigField("String", "CONTENT_REPORTS_URL", "\"https://appapi.voicestudio.sh\"") }+ }buildFeatures { compose = true; buildConfig = true }compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }testOptions { unitTests.isIncludeAndroidResources = true }diff --git a/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.ktindex 501026b5f..eefdf3a43 100644--- a/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt+++ b/mobile/android/app/src/main/kotlin/com/voicestudio/mobile/MainActivity.kt@@ -34,6 +34,7 @@ import com.voicestudio.mobile.features.voices.VoicesScreenimport com.voicestudio.mobile.features.dub.DubScreenimport com.voicestudio.mobile.features.dictate.DictateScreenimport com.voicestudio.mobile.features.settings.SettingsScreen+import com.voicestudio.mobile.network.ContentReportClientimport java.util.Localeclass VoiceStudioApplication:Application()@@ -45,7 +46,10 @@ class MainActivity:ComponentActivity() {}}-@Composable fun StudioApp(vm:StudioViewModel = viewModel()) {+/** Reports go to VoiceStudio's app API: the dev server for debug builds, production for release. */+fun contentReportClient()=ContentReportClient(BuildConfig.CONTENT_REPORTS_URL,BuildConfig.VERSION_NAME)++@Composable fun StudioApp(vm:StudioViewModel = viewModel(), reportClient:ContentReportClient? = remember {contentReportClient()}) {val prefs by vm.preferences.collectAsStateWithLifecycle()val state by vm.state.collectAsStateWithLifecycle()val context=LocalContext.current@@ -62,7 +66,8 @@ class MainActivity:ComponentActivity() {}}val direction=if(Locale.forLanguageTag(locale).language=="ar") LayoutDirection.Rtl else LayoutDirection.Ltr- CompositionLocalProvider(LocalL10n provides l,LocalLayoutDirection provides direction) {+ val snackbars=remember {SnackbarHostState()}+ CompositionLocalProvider(LocalL10n provides l,LocalLayoutDirection provides direction,LocalContentReportClient provides reportClient) {VoiceStudioTheme(ThemePreferences(prefs.mode,prefs.lightPalette,prefs.darkPalette)) {key(state.connectionId) {val initialRoute=remember {if(state.error?.key=="mobile.connect.error_session_expired") "connect" else "home"}@@ -70,7 +75,7 @@ class MainActivity:ComponentActivity() {val back by nav.currentBackStackEntryAsState()val route=back?.destination?.route ?: "home"val dismissKeyboard=rememberKeyboardDismiss()- Scaffold(containerColor=role("canvas"),bottomBar={+ Scaffold(containerColor=role("canvas"),snackbarHost={SnackbarHost(snackbars)},bottomBar={NavigationBar(containerColor=role("chrome"),contentColor=role("toolbarForeground")) {val tabs=listOf("home","voices","dub","dictate","settings")tabs.forEach {tab ->@@ -134,6 +139,7 @@ class MainActivity:ComponentActivity() {text={Column(Modifier.verticalScroll(rememberScrollState()),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {Text(tr("consent.body"));Text(tr("mobile.consent.phone_note"))}},confirmButton={TextButton(shape=MaterialTheme.shapes.small,onClick={vm.consent(true)}) {Text(tr("consent.yes"))}},dismissButton={TextButton(shape=MaterialTheme.shapes.small,onClick={vm.consent(false)}) {Text(tr("consent.no"))}})+ ContentReportHost(vm,snackbars)}}}diff --git a/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/ContentReportUiTest.kt b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/ContentReportUiTest.ktnew file mode 100644index 000000000..b6f8042ae--- /dev/null+++ b/mobile/android/app/src/test/kotlin/com/voicestudio/mobile/ContentReportUiTest.kt@@ -0,0 +1,71 @@+package com.voicestudio.mobile++import android.app.Application+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.test.*+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import com.voicestudio.mobile.designsystem.VoiceStudioTheme+import com.voicestudio.mobile.features.*+import com.voicestudio.mobile.l10n.L10n+import com.voicestudio.mobile.network.ReportSubject+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import org.junit.*+import org.junit.Assert.*+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++@RunWith(RobolectricTestRunner::class)+@Config(sdk=[34])+class ContentReportUiTest {+ @get:Rule val compose=createComposeRule()+ private fun show(subject: ReportSubject): ContentReports {+ val app=ApplicationProvider.getApplicationContext<Application>()+ val reports=ContentReports(CoroutineScope(Dispatchers.Unconfined))+ reports.open(subject)+ compose.setContent {+ CompositionLocalProvider(LocalL10n provides L10n.load(app,"en")) {VoiceStudioTheme {+ val sheet by reports.sheet.collectAsState()+ sheet?.let {ContentReportSheet(it,edit=reports::edit,send={},dismiss=reports::close)}+ }}+ }+ return reports+ }+ @Test fun sendWaitsForAReasonAndTheTextBoxStartsUnticked() {+ val reports=show(ReportSubject("speak:phone:1","speak","phone","org/model","a".repeat(40),"Typed words"))+ compose.onNodeWithText("Report this result").assertExists()+ compose.onNodeWithText("Sends your reason, note, the app version and the model that made this to the VoiceStudio team. No audio, account or device ID is sent.").assertExists()+ compose.onNodeWithText("Send report").assertIsNotEnabled()+ listOf("Sexual content","Hateful or abusive","Impersonation or a voice cloned without consent","Misleading or harmful","Something else").forEach {+ compose.onNodeWithText(it).assertIsNotSelected()+ }+ compose.onNodeWithContentDescription("Include the text I entered").assertIsOff()+ compose.onNodeWithText("Hateful or abusive").performClick()+ compose.onNodeWithText("Hateful or abusive").assertIsSelected()+ compose.onNodeWithText("Send report").assertIsEnabled()+ compose.onNodeWithText("Cancel").performClick()+ compose.waitForIdle()+ assertNull(reports.sheet.value)+ assertEquals("hateful",reports.draft("speak:phone:1")!!.reason)+ }+ @Test fun includeTextIsHiddenWithoutTypedText() {+ show(ReportSubject("clone:computer:p","clone","computer","unknown"))+ compose.onNodeWithText("Report this result").assertExists()+ compose.onNodeWithText("Include the text I entered").assertDoesNotExist()+ }+ @Test fun debugBuildsUseTheDevServerAndReleaseBuildsProduction() {+ assertTrue(BuildConfig.DEBUG)+ assertEquals("https://dev-appapi.voicestudio.sh",BuildConfig.CONTENT_REPORTS_URL)+ assertEquals("https://dev-appapi.voicestudio.sh/v1/content-reports",contentReportClient().endpoint.toString())+ // Unit tests run the debug variant; the release value is checked where it is declared.+ val script=File(requireNotNull(System.getProperty("androidRoot")),"app/build.gradle.kts").readText()+ val declared=Regex("""getByName\("(debug|release)"\) \{ buildConfigField\("String", "CONTENT_REPORTS_URL", "\\"([^"\\]+)\\""\) \}""")+ .findAll(script).associate {it.groupValues[1] to it.groupValues[2]}+ assertEquals(mapOf("debug" to "https://dev-appapi.voicestudio.sh","release" to "https://appapi.voicestudio.sh"),declared)+ }+}diff --git a/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/PhoneVoices.kt b/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/PhoneVoices.ktindex 103d136ca..fcb4cd257 100644--- a/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/PhoneVoices.kt+++ b/mobile/android/core/local/src/main/kotlin/com/voicestudio/mobile/local/PhoneVoices.kt@@ -18,7 +18,9 @@ internal fun atomicText(file: File, text: String) {java.io.FileOutputStream(pending).use {it.write(text.toByteArray(Charsets.UTF_8));it.fd.sync()}Files.move(pending.toPath(),file.toPath(),StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING)}-@Serializable data class PhoneVoice(val id: String, val name: String, val transcript: String, val createdAt: Long, val consentAt: Long, val sampleRate: Int = 24000)+/** [modelRepo]/[modelRevision] name the model that made the voice, for reports; older voices have none. */+@Serializable data class PhoneVoice(val id: String, val name: String, val transcript: String, val createdAt: Long, val consentAt: Long, val sampleRate: Int = 24000,+ val modelRepo: String? = null, val modelRevision: String? = null)/** One atomic metadata publication after ASR + reference writes. No user paths. */class PhoneVoiceStore(private val root: File) {private val mutex=Mutex()@@ -51,7 +53,7 @@ class PhoneVoiceStore(private val root: File) {writeReferenceWave(audio.read(0,audio.frames.toInt()),File(dir,"reference.wav"))currentCoroutineContext().ensureActive()val now=System.currentTimeMillis()- val voice=PhoneVoice(id,name.trim(),transcript,now,now)+ val voice=PhoneVoice(id,name.trim(),transcript,now,now,modelRepo=asr.repo,modelRevision=asr.revision)mutex.withLock {atomicText(File(dir,"voice.json"),LocalJson.encodeToString(PhoneVoice.serializer(),voice))}progress(1f);voice} catch(e:Throwable) {dir.deleteRecursively();throw e}diff --git a/mobile/android/core/network/src/main/kotlin/com/voicestudio/mobile/network/ContentReports.kt b/mobile/android/core/network/src/main/kotlin/com/voicestudio/mobile/network/ContentReports.ktnew file mode 100644index 000000000..019e65fa5--- /dev/null+++ b/mobile/android/core/network/src/main/kotlin/com/voicestudio/mobile/network/ContentReports.kt@@ -0,0 +1,121 @@+package com.voicestudio.mobile.network++import java.io.IOException+import java.security.SecureRandom+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.*+import okhttp3.*+import okhttp3.HttpUrl.Companion.toHttpUrl+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.RequestBody.Companion.toRequestBody+import kotlin.coroutines.resume++/** One generated result the person can report; nothing here is editable by them. */+data class ReportSubject(val id: String, val task: String, val runsOn: String, val modelId: String,+ val modelRevision: String? = null, val typedText: String? = null) {+ val hasTypedText get() = !typedText.isNullOrBlank()+}++/** The person's unsent answers. The key is made with the draft and reused on retry. */+data class ReportDraft(val reason: String? = null, val note: String = "", val includeText: Boolean = false,+ val idempotencyKey: String = ContentReport.newKey())++enum class ReportOutcome { SENT, RATE_LIMITED, INVALID, FAILED }+/** [idempotencyKey] is the key to keep on the draft: a 409 replaces it. */+data class ReportResult(val outcome: ReportOutcome, val idempotencyKey: String)++/** The content-report contract of mobile/contract/SPEC.md ("Reporting generated content"). */+object ContentReport {+ const val PATH = "v1/content-reports"+ const val NOTE_LIMIT = 1000+ const val PROMPT_LIMIT = 5000+ const val MODEL_ID_LIMIT = 128+ const val UNKNOWN_MODEL = "unknown"+ val REASONS = listOf("sexual", "hateful", "impersonation", "misleading", "other")+ private const val KEY_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"+ private val random = SecureRandom()++ fun newKey(source: SecureRandom = random): String =+ buildString(32) { repeat(32) { append(KEY_ALPHABET[source.nextInt(KEY_ALPHABET.length)]) } }++ /** Characters outside `0-9A-Za-z._/:-` are removed and the result capped; nothing left is `unknown`. */+ fun modelId(raw: String?): String = raw.orEmpty()+ .filter { it in '0'..'9' || it in 'A'..'Z' || it in 'a'..'z' || it in "._/:-" }+ .take(MODEL_ID_LIMIT).ifEmpty { UNKNOWN_MODEL }++ private fun revision(raw: String?): String? = raw.orEmpty()+ .filter { it in '0'..'9' || it in 'A'..'Z' || it in 'a'..'z' || it in "._-" }.take(64).ifEmpty { null }++ /** Cut at [limit] UTF-16 units without splitting a surrogate pair. */+ internal fun cap(text: String, limit: Int): String {+ if (text.length <= limit) return text+ val end = if (Character.isHighSurrogate(text[limit - 1])) limit - 1 else limit+ return text.substring(0, end)+ }++ /** Exactly the documented fields; empty optional fields are omitted. */+ fun body(subject: ReportSubject, draft: ReportDraft, appVersion: String): JsonObject = buildJsonObject {+ put("reason", requireNotNull(draft.reason) { "reason required" }.also { require(it in REASONS) })+ cap(draft.note.trim(), NOTE_LIMIT).trim().takeIf { it.isNotEmpty() }?.let { put("note", it) }+ if (draft.includeText) subject.typedText?.let { cap(it, PROMPT_LIMIT) }?.takeIf { it.isNotBlank() }?.let { put("prompt_text", it) }+ put("platform", "android")+ put("app_version", appVersion)+ put("task", subject.task)+ put("model_id", modelId(subject.modelId))+ if (subject.runsOn == "phone") revision(subject.modelRevision)?.let { put("model_revision", it) }+ put("runs_on", subject.runsOn)+ }+}++/**+ * Sends reports to VoiceStudio's app API. It has its own client: the paired+ * host's PIN, session and Authorization headers never reach this server.+ */+class ContentReportClient(baseUrl: String, private val appVersion: String, client: OkHttpClient? = null) {+ val endpoint: HttpUrl = baseUrl.toHttpUrl().also(HostPolicy::validate).let {+ it.newBuilder().encodedPath(it.encodedPath.trimEnd('/') + "/").build().resolve(ContentReport.PATH)+ ?: throw ClientFailure("mobile.connect.error_invalid_url")+ }+ private val client: OkHttpClient = client ?: OkHttpClient.Builder()+ .connectTimeout(15, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS)+ // A redirect would repeat the report elsewhere; treat it as a failure.+ .followRedirects(false).followSslRedirects(false).build()++ /** Never throws for HTTP or connection failures; cancellation still propagates. */+ suspend fun send(subject: ReportSubject, draft: ReportDraft): ReportResult = withContext(Dispatchers.IO) {+ val body = ContentReport.body(subject, draft, appVersion).toString()+ var key = draft.idempotencyKey+ var status = post(body, key)+ if (status == 409) {+ // The key was used for a different body: send once more with a new one.+ key = ContentReport.newKey()+ status = post(body, key)+ }+ val outcome = when (status) {+ 201 -> ReportOutcome.SENT+ 429 -> ReportOutcome.RATE_LIMITED+ 400 -> ReportOutcome.INVALID+ else -> ReportOutcome.FAILED+ }+ ReportResult(outcome, key)+ }++ /** The response status, or null when there was no response. */+ private suspend fun post(body: String, key: String): Int? {+ val request = Request.Builder().url(endpoint)+ .header("Idempotency-Key", key)+ .post(body.toRequestBody("application/json".toMediaType()))+ .build()+ return suspendCancellableCoroutine { cont ->+ val call = client.newCall(request)+ cont.invokeOnCancellation { call.cancel() }+ call.enqueue(object : Callback {+ override fun onFailure(call: Call, e: IOException) { if (cont.isActive) cont.resume(null) }+ override fun onResponse(call: Call, response: Response) { response.use { if (cont.isActive) cont.resume(it.code) } }+ })+ }+ }+}diff --git a/mobile/android/core/network/src/test/kotlin/com/voicestudio/mobile/network/ContentReportsTest.kt b/mobile/android/core/network/src/test/kotlin/com/voicestudio/mobile/network/ContentReportsTest.ktnew file mode 100644index 000000000..be12d5351--- /dev/null+++ b/mobile/android/core/network/src/test/kotlin/com/voicestudio/mobile/network/ContentReportsTest.kt@@ -0,0 +1,125 @@+package com.voicestudio.mobile.network++import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.*+import okhttp3.mockwebserver.*+import org.junit.*+import org.junit.Assert.*++class ContentReportsTest {+ private lateinit var server: MockWebServer+ private lateinit var client: ContentReportClient+ private val phone = ReportSubject("speak:phone:1", "speak", "phone", "org/model", "a".repeat(40), "Hello there")+ private val computer = ReportSubject("clone:computer:p1", "clone", "computer", "unknown")+ @Before fun setup() { server = MockWebServer(); server.start(); client = ContentReportClient(server.url("/").toString(), "1.2.3") }+ @After fun teardown() { server.shutdown() }+ private fun created() = MockResponse().setResponseCode(201).setBody("""{"report_id":"ABCDEFGHIJKLMNOP","received_at":"2026-10-24T00:00:00Z"}""")+ private fun RecordedRequest.json() = Json.parseToJsonElement(body.readUtf8()).jsonObject++ @Test fun bodyHasExactlyTheDocumentedFieldsAndOmitsEmptyOptionals() = runBlocking {+ server.enqueue(created())+ val result = client.send(phone, ReportDraft(reason = "hateful", note = " "))+ assertEquals(ReportOutcome.SENT, result.outcome)+ val request = server.takeRequest()+ assertEquals("POST", request.method)+ assertEquals("/v1/content-reports", request.path)+ assertEquals(buildJsonObject {+ put("reason", "hateful"); put("platform", "android"); put("app_version", "1.2.3"); put("task", "speak")+ put("model_id", "org/model"); put("model_revision", "a".repeat(40)); put("runs_on", "phone")+ }, request.json())+ }+ @Test fun promptTextOnlyWhenTickedAndCapped() = runBlocking {+ val long = phone.copy(typedText = "x".repeat(6000))+ server.enqueue(created()); client.send(long, ReportDraft(reason = "other"))+ assertFalse(server.takeRequest().json().containsKey("prompt_text"))+ server.enqueue(created()); client.send(long, ReportDraft(reason = "other", includeText = true))+ assertEquals("x".repeat(5000), server.takeRequest().json()["prompt_text"]!!.jsonPrimitive.content)+ // A ticked box on a result without typed text sends nothing extra.+ server.enqueue(created()); client.send(computer, ReportDraft(reason = "other", includeText = true))+ assertFalse(server.takeRequest().json().containsKey("prompt_text"))+ }+ @Test fun noteIsTrimmedAndCapped() = runBlocking {+ server.enqueue(created()); client.send(phone, ReportDraft(reason = "sexual", note = " sounds wrong \n"))+ assertEquals("sounds wrong", server.takeRequest().json()["note"]!!.jsonPrimitive.content)+ server.enqueue(created()); client.send(phone, ReportDraft(reason = "sexual", note = "n".repeat(1200)))+ assertEquals(1000, server.takeRequest().json()["note"]!!.jsonPrimitive.content.length)+ }+ @Test fun computerReportHasNoRevisionAndSanitizedModel() = runBlocking {+ server.enqueue(created())+ client.send(computer.copy(modelId = "my engine/v2:ö#1", modelRevision = "abc"), ReportDraft(reason = "impersonation"))+ val body = server.takeRequest().json()+ assertEquals("myengine/v2:1", body["model_id"]!!.jsonPrimitive.content)+ assertEquals("computer", body["runs_on"]!!.jsonPrimitive.content)+ assertEquals("clone", body["task"]!!.jsonPrimitive.content)+ assertFalse(body.containsKey("model_revision"))+ assertEquals(setOf("reason", "platform", "app_version", "task", "model_id", "runs_on"), body.keys)+ }+ @Test fun modelIdSanitizing() {+ assertEquals("unknown", ContentReport.modelId(null))+ assertEquals("unknown", ContentReport.modelId(" ## "))+ assertEquals("a.b_c/d:e-f", ContentReport.modelId("a.b_c/d:e-f"))+ assertEquals(128, ContentReport.modelId("m".repeat(300)).length)+ }+ @Test fun headersCarryAKeyAndNoCredentials() = runBlocking {+ server.enqueue(created())+ val draft = ReportDraft(reason = "misleading")+ client.send(phone, draft)+ val request = server.takeRequest()+ assertTrue(request.getHeader("Content-Type")!!.startsWith("application/json"))+ assertEquals(draft.idempotencyKey, request.getHeader("Idempotency-Key"))+ assertTrue(Regex("[A-Za-z0-9]{32}").matches(draft.idempotencyKey))+ assertNull(request.getHeader("Authorization"))+ assertNull(request.getHeader("X-OmniVoice-Pin"))+ assertNull(request.getHeader("Cookie"))+ }+ @Test fun keysAreRandom() {+ val keys = (1..50).map { ContentReport.newKey() }+ assertEquals(50, keys.toSet().size)+ keys.forEach { assertTrue(it, Regex("[A-Za-z0-9]{32}").matches(it)) }+ }+ @Test fun retryReusesTheKey() = runBlocking {+ val draft = ReportDraft(reason = "other")+ server.enqueue(MockResponse().setResponseCode(503))+ val failed = client.send(phone, draft)+ assertEquals(ReportOutcome.FAILED, failed.outcome)+ assertEquals(draft.idempotencyKey, failed.idempotencyKey)+ server.enqueue(created())+ assertEquals(ReportOutcome.SENT, client.send(phone, draft.copy(idempotencyKey = failed.idempotencyKey)).outcome)+ assertEquals(server.takeRequest().getHeader("Idempotency-Key"), server.takeRequest().getHeader("Idempotency-Key"))+ }+ @Test fun conflictMakesANewKeyAndResendsOnce() = runBlocking {+ val draft = ReportDraft(reason = "other")+ server.enqueue(MockResponse().setResponseCode(409)); server.enqueue(created())+ val result = client.send(phone, draft)+ assertEquals(ReportOutcome.SENT, result.outcome)+ val first = server.takeRequest(); val second = server.takeRequest()+ assertEquals(draft.idempotencyKey, first.getHeader("Idempotency-Key"))+ assertNotEquals(first.getHeader("Idempotency-Key"), second.getHeader("Idempotency-Key"))+ assertEquals(second.getHeader("Idempotency-Key"), result.idempotencyKey)+ assertEquals(first.body.readUtf8(), second.body.readUtf8())+ // A second conflict is not resent again.+ server.enqueue(MockResponse().setResponseCode(409)); server.enqueue(MockResponse().setResponseCode(409))+ assertEquals(ReportOutcome.FAILED, client.send(phone, draft).outcome)+ assertEquals(4, server.requestCount)+ }+ @Test fun statusMapping() = runBlocking {+ val draft = ReportDraft(reason = "other")+ mapOf(429 to ReportOutcome.RATE_LIMITED, 400 to ReportOutcome.INVALID, 503 to ReportOutcome.FAILED,+ 404 to ReportOutcome.FAILED, 500 to ReportOutcome.FAILED, 200 to ReportOutcome.FAILED, 302 to ReportOutcome.FAILED).forEach { (code, outcome) ->+ server.enqueue(MockResponse().setResponseCode(code).setHeader("Location", "https://outside.example/"))+ assertEquals("HTTP $code", outcome, client.send(phone, draft).outcome)+ }+ assertEquals(7, server.requestCount)+ }+ @Test fun noConnectionIsFailed() = runBlocking {+ val closed = MockWebServer().apply { start() }+ val offline = ContentReportClient(closed.url("/").toString(), "1.2.3")+ closed.shutdown()+ assertEquals(ReportOutcome.FAILED, offline.send(phone, ReportDraft(reason = "other")).outcome)+ }+ @Test fun endpointsUseHttpsAndThePath() {+ assertEquals("https://appapi.voicestudio.sh/v1/content-reports", ContentReportClient("https://appapi.voicestudio.sh", "1").endpoint.toString())+ assertEquals("https://dev-appapi.voicestudio.sh/v1/content-reports", ContentReportClient("https://dev-appapi.voicestudio.sh/", "1").endpoint.toString())+ assertThrows(ClientFailure::class.java) { ContentReportClient("http://appapi.voicestudio.sh", "1") }+ }+}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.ktindex 52c6ef710..29b5a932e 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/Components.kt@@ -257,6 +257,7 @@ fun languageName(code: String, locale: String): String = Locale.forLanguageTag(c}fun actionIcon(key: String): ImageVector = when {+ key=="mobile.report.action" -> Icons.Default.Warningkey.contains("scan_qr") -> VSIcons.Qrkey.contains("clone")||key.contains("pick") -> Icons.Default.Addkey.contains("cancel")||key.contains("abort")||key.contains("stop") -> Icons.Default.Closediff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReportSheet.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReportSheet.ktnew file mode 100644index 000000000..9e2e7d179--- /dev/null+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReportSheet.kt@@ -0,0 +1,104 @@+package com.voicestudio.mobile.features++import androidx.compose.foundation.layout.*+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.selection.selectable+import androidx.compose.foundation.selection.selectableGroup+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Warning+import androidx.compose.material3.*+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.semantics.*+import androidx.compose.ui.unit.dp+import com.voicestudio.mobile.designsystem.*+import com.voicestudio.mobile.network.ContentReport+import com.voicestudio.mobile.network.ReportSubject++/** Reason ids in contract order with their full catalogue keys. */+internal val reportReasons = listOf(+ "sexual" to "mobile.report.reasons.sexual",+ "hateful" to "mobile.report.reasons.hateful",+ "impersonation" to "mobile.report.reasons.impersonation",+ "misleading" to "mobile.report.reasons.misleading",+ "other" to "mobile.report.reasons.other",+)++/** The Report action on one generated result; hidden when the app supplies no report client. */+@Composable fun ReportAction(vm: StudioViewModel, subject: () -> ReportSubject) {+ if(LocalContentReportClient.current==null) return+ IconAction("mobile.report.action",Icons.Default.Warning) {vm.reports.open(subject())}+}++/** Full-width Report button under a just-made result. */+@Composable fun ReportButton(vm: StudioViewModel, enabled: Boolean = true, subject: () -> ReportSubject) {+ if(LocalContentReportClient.current==null) return+ Secondary("mobile.report.action",enabled) {vm.reports.open(subject())}+}++/** Hosts the report sheet once for the whole app and announces a stored report. */+@Composable fun ContentReportHost(vm: StudioViewModel, snackbars: SnackbarHostState) {+ val l=LocalL10n.current+ val strings by rememberUpdatedState(l)+ LaunchedEffect(vm.reports) {vm.reports.sent.collect {snackbars.showSnackbar(strings.t("mobile.report.sent"))}}+ val sheet by vm.reports.sheet.collectAsState()+ val client=LocalContentReportClient.current+ val current=sheet+ if(current!=null&&client!=null) ContentReportSheet(current,+ edit=vm.reports::edit, send={vm.reports.send(client)}, dismiss=vm.reports::close)+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable fun ContentReportSheet(sheet: ReportSheet, edit: ((com.voicestudio.mobile.network.ReportDraft)->com.voicestudio.mobile.network.ReportDraft)->Unit, send: ()->Unit, dismiss: ()->Unit) {+ val draft=sheet.draft+ val sending=sheet.status==ReportStatus.SENDING+ ModalBottomSheet(onDismissRequest=dismiss,containerColor=role("surfaceOverlay")) {+ Column(Modifier.fillMaxWidth().heightIn(max=(LocalConfiguration.current.screenHeightDp*.7f).dp).dismissKeyboardOnTap()+ .verticalScroll(rememberScrollState()).padding(horizontal=VSTheme.inset),verticalArrangement=Arrangement.spacedBy(VSTheme.gap)) {+ Text(tr("mobile.report.title"),style=MaterialTheme.typography.titleLarge,modifier=Modifier.semantics {heading()})+ Text(tr("mobile.report.reason"),style=MaterialTheme.typography.titleSmall,modifier=Modifier.semantics {heading()})+ Column(Modifier.fillMaxWidth().selectableGroup()) {+ reportReasons.forEach {(id,key) ->+ val selected=draft.reason==id+ Row(Modifier.fillMaxWidth().heightIn(min=VSTheme.touchTarget).testTag("report.reason.$id")+ .selectable(selected=selected,enabled=!sending,role=Role.RadioButton,onClick={edit {it.copy(reason=id)}}),+ verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(VSTheme.gap)) {+ RadioButton(selected=selected,onClick=null,enabled=!sending)+ Text(tr(key),Modifier.weight(1f))+ }+ }+ }+ OutlinedTextField(value=draft.note,onValueChange={value -> edit {it.copy(note=value.take(ContentReport.NOTE_LIMIT))}},+ enabled=!sending,label={Text(tr("mobile.report.note"))},minLines=3,maxLines=6,+ supportingText={Text("${draft.note.length} / ${ContentReport.NOTE_LIMIT}",Modifier.fillMaxWidth().clearAndSetSemantics {},style=MaterialTheme.typography.labelSmall)},+ modifier=Modifier.fillMaxWidth().testTag("report.note"),shape=MaterialTheme.shapes.small,+ colors=OutlinedTextFieldDefaults.colors(focusedBorderColor=role("focus"),unfocusedBorderColor=role("border"),focusedContainerColor=role("input"),unfocusedContainerColor=role("input")))+ if(sheet.subject.hasTypedText) ConsentCheck("mobile.report.include_text",draft.includeText) {checked -> if(!sending) edit {it.copy(includeText=checked)}}+ Text(tr("mobile.report.disclosure"),style=MaterialTheme.typography.bodySmall,color=role("textMuted"))+ val message=when(sheet.status) {+ ReportStatus.FAILED -> "mobile.report.failed"+ ReportStatus.RATE_LIMITED -> "mobile.report.rate_limited"+ ReportStatus.INVALID -> "mobile.report.invalid"+ else -> null+ }+ message?.let {Text(tr(it),color=role("error"),style=MaterialTheme.typography.bodyMedium,modifier=Modifier.testTag("report.status").semantics {liveRegion=LiveRegionMode.Polite})}+ }+ Row(Modifier.fillMaxWidth().padding(VSTheme.inset),horizontalArrangement=Arrangement.spacedBy(VSTheme.gap,Alignment.End),verticalAlignment=Alignment.CenterVertically) {+ TextButton(onClick=dismiss,shape=MaterialTheme.shapes.small,modifier=Modifier.heightIn(min=VSTheme.touchTarget)) {Text(tr("common.cancel"))}+ val label=when {+ sending -> "mobile.report.sending"+ sheet.status==ReportStatus.FAILED -> "mobile.report.retry"+ else -> "mobile.report.send"+ }+ Button(onClick=send,enabled=sheet.canSend,shape=MaterialTheme.shapes.small,modifier=Modifier.heightIn(min=VSTheme.touchTarget).testTag("report.send"),+ colors=ButtonDefaults.buttonColors(containerColor=role("messageAction"),contentColor=role("messageActionForeground"))) {+ if(sending) {CircularProgressIndicator(Modifier.size(16.dp),strokeWidth=2.dp,color=role("messageActionForeground"));Spacer(Modifier.width(VSTheme.gap))}+ Text(tr(label))+ }+ }+ }+}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReports.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReports.ktnew file mode 100644index 000000000..b44f9dae6--- /dev/null+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/ContentReports.kt@@ -0,0 +1,93 @@+package com.voicestudio.mobile.features++import com.voicestudio.mobile.local.*+import com.voicestudio.mobile.network.*+import androidx.compose.runtime.staticCompositionLocalOf+import kotlinx.coroutines.*+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.*++/** The app's report client (base URL per build type, root package.json version); null hides Report. */+val LocalContentReportClient = staticCompositionLocalOf<ContentReportClient?> { null }++enum class ReportStatus { IDLE, SENDING, FAILED, RATE_LIMITED, INVALID }+data class ReportSheet(val subject: ReportSubject, val draft: ReportDraft, val status: ReportStatus = ReportStatus.IDLE) {+ val canSend get() = draft.reason != null && status != ReportStatus.SENDING && status != ReportStatus.INVALID+}++/**+ * Drafts live in memory per result until they are sent, so closing and reopening+ * the sheet keeps the reason, note, checkbox and idempotency key.+ */+class ContentReports(private val scope: CoroutineScope) {+ private val drafts = mutableMapOf<String, ReportDraft>()+ private val inFlight = mutableSetOf<String>()+ private val mutable = MutableStateFlow<ReportSheet?>(null)+ val sheet: StateFlow<ReportSheet?> = mutable.asStateFlow()+ private val sentEvents = MutableSharedFlow<Unit>(extraBufferCapacity = 1)+ /** One event per report the server stored. */+ val sent: SharedFlow<Unit> = sentEvents.asSharedFlow()++ fun draft(id: String): ReportDraft? = drafts[id]+ fun open(subject: ReportSubject) {+ val draft = drafts.getOrPut(subject.id) { ReportDraft() }+ mutable.value = ReportSheet(subject, draft, if (subject.id in inFlight) ReportStatus.SENDING else ReportStatus.IDLE)+ }+ fun close() { mutable.value = null }+ fun edit(transform: (ReportDraft) -> ReportDraft) {+ val current = mutable.value ?: return+ if (current.status == ReportStatus.SENDING) return+ val changed = transform(current.draft)+ val draft = changed.copy(note = changed.note.take(ContentReport.NOTE_LIMIT),+ includeText = changed.includeText && current.subject.hasTypedText)+ drafts[current.subject.id] = draft+ // A changed draft may be sent again; a failed one keeps its Retry.+ mutable.value = current.copy(draft = draft, status = if (current.status == ReportStatus.FAILED) ReportStatus.FAILED else ReportStatus.IDLE)+ }+ fun send(client: ContentReportClient): Job? {+ val current = mutable.value ?: return null+ if (!current.canSend) return null+ val id = current.subject.id+ val draft = current.draft+ inFlight += id+ mutable.value = current.copy(status = ReportStatus.SENDING)+ return scope.launch {+ val result = try { client.send(current.subject, draft) } finally { inFlight -= id }+ if (result.outcome == ReportOutcome.SENT) {+ drafts.remove(id)+ if (mutable.value?.subject?.id == id) mutable.value = null+ sentEvents.tryEmit(Unit)+ return@launch+ }+ // Edits are blocked while sending, so the stored draft is the one sent.+ val kept = (drafts[id] ?: draft).copy(idempotencyKey = result.idempotencyKey)+ drafts[id] = kept+ val status = when (result.outcome) {+ ReportOutcome.RATE_LIMITED -> ReportStatus.RATE_LIMITED+ ReportOutcome.INVALID -> ReportStatus.INVALID+ else -> ReportStatus.FAILED+ }+ mutable.update { if (it?.subject?.id == id) it.copy(draft = kept, status = status) else it }+ }+ }+}++/** What each generated result reports as: task, where it ran and the model that made it. */+object ReportSubjects {+ fun phoneSpeak(item: PhoneGeneration) = ReportSubject("speak:phone:${item.id}", "speak", "phone",+ item.modelRepo ?: ContentReport.UNKNOWN_MODEL, item.modelRevision.takeIf { item.modelRepo != null }, item.text)+ /** [engine] is the host engine id that made the take, when known. */+ fun computerSpeak(audioPath: String, text: String, engine: String?) =+ ReportSubject("speak:computer:$audioPath", "speak", "computer", ContentReport.modelId(engine), typedText = text)+ fun phoneClone(voice: PhoneVoice) = ReportSubject("clone:phone:${voice.id}", "clone", "phone",+ voice.modelRepo ?: ContentReport.UNKNOWN_MODEL, voice.modelRevision.takeIf { voice.modelRepo != null })+ fun computerClone(profile: Profile) = ReportSubject("clone:computer:${profile.id}", "clone", "computer", ContentReport.UNKNOWN_MODEL)+ /** The phone dub's speech comes from its pinned voice model; a changed catalogue entry keeps only the repo. */+ fun phoneDub(request: PhoneDubRequest, models: List<PhoneModel>): ReportSubject {+ val clones = models.filter { it.capability == "clone" }+ val exact = clones.firstOrNull { modelPin(it) in request.models }+ val named = exact ?: clones.firstOrNull { model -> request.models.any { it.id == model.id } }+ return ReportSubject("dub:phone:${request.id}", "dub", "phone", named?.repo ?: ContentReport.UNKNOWN_MODEL, exact?.revision)+ }+ fun computerDub(job: String) = ReportSubject("dub:computer:$job", "dub", "computer", ContentReport.UNKNOWN_MODEL)+}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.ktindex 96e3d1478..182eab798 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/PhoneStudio.kt@@ -77,7 +77,7 @@ class PhoneStudio(context: Context, private val scope: CoroutineScope, private vval id=java.util.UUID.randomUUID().toString()val output=File(application.noBackupFilesDir,"speech/$id.wav")markSynthetic(audio,output)- val generation=PhoneGeneration(id,text,System.currentTimeMillis())+ val generation=PhoneGeneration(id,text,System.currentTimeMillis(),model.repo,model.revision)File(output.parentFile,"$id.json").writeText(kotlinx.serialization.json.Json.encodeToString(PhoneGeneration.serializer(),generation))output}@@ -114,4 +114,5 @@ class PhoneStudio(context: Context, private val scope: CoroutineScope, private vfun cancelInference() {inference?.cancel()}}[email protected] data class PhoneGeneration(val id: String,val text: String,val createdAt: Long)+/** The model that made the take is kept so it can be reported; older takes have none. */[email protected] data class PhoneGeneration(val id: String,val text: String,val createdAt: Long,val modelRepo: String? = null,val modelRevision: String? = null)diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/StudioViewModel.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/StudioViewModel.ktindex ea5f5ab46..c3bd7685b 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/StudioViewModel.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/StudioViewModel.kt@@ -24,6 +24,9 @@ class StudioViewModel @JvmOverloads constructor(application: Application, val stprivate var operation: Job? = nullprivate var retryAction: (() ->Unit)? = nullval phone = PhoneStudio(application,viewModelScope,::fail) {error,retry -> fail(error,retry)}+ val reports = ContentReports(viewModelScope)+ // Host takes made in this session: playback path -> engine id and full typed text, for reports.+ private val computerTakes = mutableMapOf<String,Pair<String,String>>()init {viewModelScope.launch {val prefs = store.preferences.first()@@ -46,6 +49,7 @@ class StudioViewModel @JvmOverloads constructor(application: Application, val st}}private fun clearHostState(host: String? = null, profiles: List<Profile> = emptyList(), error: ClientFailure? = null) {+ computerTakes.clear()mutable.value = StudioState(connectionId = mutable.value.connectionId + 1, hostUrl = host,loading = false, connected = host != null, busy = mutable.value.busy, catalogLoading = host != null, profiles = profiles, error = error)}@@ -134,11 +138,18 @@ class StudioViewModel @JvmOverloads constructor(application: Application, val stval current = api ?: return@runval result = current.generate(text, voice, engine, language)if(api !== current) return@run- mutable.update { it.copy(audio = current.audioPath(result.audioPath)) }+ val audio = current.audioPath(result.audioPath)+ computerTakes[audio] = engine to text+ mutable.update { it.copy(audio = audio) }val history = current.history()if(api === current) mutable.update { it.copy(history = history) }}fun play(path: String) { mutable.update { it.copy(audio = path) } }+ /** A host take: the engine this app asked for when it made it, else unknown. */+ fun computerSpeakSubject(audioPath: String, fallbackText: String = ""): com.voicestudio.mobile.network.ReportSubject {+ val take = computerTakes[audioPath]+ return ReportSubjects.computerSpeak(audioPath, take?.second ?: fallbackText, take?.first)+ }fun star(item: HistoryItem) = run { api?.star(item.id, !item.isStarred); reload() }fun deleteHistory(item: HistoryItem) = run { api?.deleteHistory(item.id); reload() }fun clone(name: String, file: File) = run { api?.clone(name, file); file.delete(); reload() }diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.ktindex a256e6b75..ffa2855a4 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/DubScreen.kt@@ -154,8 +154,11 @@ import java.io.File}}val job=info.outputData.getString("job") ?: info.progress.getString("job")- if(info.state==WorkInfo.State.SUCCEEDED&&job!=null) Secondary("mobile.dub.download",!state.busy) {- vm.run {shareFile(context,sharedDownload(context,vm.api!!,"/dub/download/${VoiceStudioApi.segment(job)}",if(inputType=="audio") "m4a" else "mkv"),"application/octet-stream")}+ if(info.state==WorkInfo.State.SUCCEEDED&&job!=null) {+ Secondary("mobile.dub.download",!state.busy) {+ vm.run {shareFile(context,sharedDownload(context,vm.api!!,"/dub/download/${VoiceStudioApi.segment(job)}",if(inputType=="audio") "m4a" else "mkv"),"application/octet-stream")}+ }+ ReportButton(vm) {ReportSubjects.computerDub(job)}}}}HorizontalDivider()@@ -173,7 +176,8 @@ import java.io.FilesavePath=file.absolutePathsave.launch(item.filename.substringBeforeLast('.').ifBlank {item.id}+"."+file.extension)}},- share={vm.run {shareFile(context,sharedDownload(context,vm.api!!,dubDownloadPath(job),"mkv"),"application/octet-stream")}})+ share={vm.run {shareFile(context,sharedDownload(context,vm.api!!,dubDownloadPath(job),"mkv"),"application/octet-stream")}},+ report=if(LocalContentReportClient.current!=null) {{vm.reports.open(ReportSubjects.computerDub(job))}} else null)if(index<state.dubHistory.lastIndex) HorizontalDivider()}}@@ -205,7 +209,7 @@ private fun dubDownloadPath(job: String) = "/dub/download/${VoiceStudioApi.segme}}-@Composable fun DubHistoryRow(item: DubHistory, enabled: Boolean, download: ()->Unit, share: ()->Unit) {+@Composable fun DubHistoryRow(item: DubHistory, enabled: Boolean, download: ()->Unit, share: ()->Unit, report: (()->Unit)? = null) {val name=item.filename.ifBlank {item.id}Row(Modifier.fillMaxWidth().padding(VSTheme.inset),verticalAlignment=Alignment.CenterVertically) {Column(Modifier.weight(1f)) {@@ -216,5 +220,6 @@ private fun dubDownloadPath(job: String) = "/dub/download/${VoiceStudioApi.segme}IconAction("mobile.dub.download_file",VSIcons.Download,enabled,mapOf("name" to name),download)IconAction("mobile.dub.share_file",Icons.Default.Share,enabled,mapOf("name" to name),share)+ report?.let {IconAction("mobile.report.action",Icons.Default.Warning,onClick=it)}}}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.ktindex affc9aefe..c76afeed1 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/dub/PhoneDubScreen.kt@@ -143,6 +143,7 @@ import java.io.FileIconAction("player.play",Icons.Default.PlayArrow) {playing=file.path}IconAction("mobile.speak.share",Icons.Default.Share) {scope.launch {try {shareLocalFile(context,file,if(file.extension=="mp4") "video/mp4" else "audio/wav")} catch(e:Exception) {vm.fail(e)}}}IconAction("common.save",VSIcons.Download) {savePath=file.path;save.launch(record.request.title.substringBeforeLast('.').ifBlank {record.request.id}+"-${output.language}.${file.extension}")}+ ReportAction(vm) {ReportSubjects.phoneDub(record.request,phone.models)}if(record.checkpoint.done) IconAction("mobile.simple.remove_job",Icons.Default.Delete) {vm.run {if(playing==file.path) playing=null;vm.phone.dubs.delete(record.request.id);vm.phone.refreshDubs()}}}}}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.ktindex 006c3739c..8ebe1c3da 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/speak/SpeakScreen.kt@@ -58,6 +58,7 @@ import kotlinx.coroutines.*HostPlayer(api,audio,vm::fail)Secondary("mobile.speak.share",!state.busy) {vm.run {shareFile(context,sharedDownload(context,api,audio,"wav"),"audio/wav")}}Secondary("common.save",!state.busy) {savePath=audio;save.launch("${java.util.UUID.randomUUID()}.wav")}+ ReportButton(vm) {vm.computerSpeakSubject(audio)}}Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {Box(Modifier.weight(1f)) {Heading("mobile.speak.recent")}@@ -72,6 +73,7 @@ import kotlinx.coroutines.*IconAction("player.play",Icons.Default.PlayArrow) {vm.play(vm.api!!.audioPath(item.audioPath))}IconAction(if(item.isStarred) "mobile.speak.unstar" else "mobile.speak.star",Icons.Default.Star,!state.busy) {vm.star(item)}IconAction("common.delete",Icons.Default.Delete,!state.busy) {vm.deleteHistory(item)}+ ReportAction(vm) {vm.computerSpeakSubject(vm.api?.audioPath(item.audioPath) ?: item.audioPath,item.text)}}HorizontalDivider()}@@ -132,6 +134,7 @@ internal fun chooseSpeakModel(models: List<PhoneModel>,installed: Set<String>,chLocalAudioPlayer(file,vm::fail)Secondary("mobile.speak.share") {scope.launch {try {shareLocalFile(context,file,"audio/wav")} catch(e:Exception) {vm.fail(e)}}}Secondary("common.save") {save.launch(file.name)}+ phone.recent.firstOrNull {vm.phone.generationFile(it)==file}?.let {take -> ReportButton(vm) {ReportSubjects.phoneSpeak(take)}}}Heading("mobile.speak.recent")if(phone.recent.isEmpty()) EmptyState("mobile.simple.empty_recent")@@ -140,6 +143,7 @@ internal fun chooseSpeakModel(models: List<PhoneModel>,installed: Set<String>,chText(item.text,Modifier.weight(1f),maxLines=1,overflow=androidx.compose.ui.text.style.TextOverflow.Ellipsis)IconAction("player.play",Icons.Default.PlayArrow) {vm.phone.play(item)}IconAction("common.delete",Icons.Default.Delete) {vm.phone.deleteGeneration(item)}+ ReportAction(vm) {ReportSubjects.phoneSpeak(item)}}}diff --git a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.ktindex d8707adc2..43b2a812c 100644--- a/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt+++ b/mobile/android/features/src/main/kotlin/com/voicestudio/mobile/features/voices/VoicesScreen.kt@@ -111,6 +111,9 @@ import java.io.FileDropdownMenu(expanded=menu,onDismissRequest={menu=false},shape=MaterialTheme.shapes.large,containerColor=role("surfaceOverlay")) {DropdownMenuItem(text={Text(tr("mobile.voices.rename"))},onClick={menu=false;edit=profile;editName=profile.name})DropdownMenuItem(text={Text(tr("common.delete"))},onClick={menu=false;delete=profile})+ if(LocalContentReportClient.current!=null) DropdownMenuItem(text={Text(tr("mobile.report.action"))},+ leadingIcon={Icon(Icons.Default.Warning,contentDescription=null)},modifier=Modifier.heightIn(min=VSTheme.touchTarget),+ onClick={menu=false;val voice=local(profile);vm.reports.open(if(voice!=null) ReportSubjects.phoneClone(voice) else ReportSubjects.computerClone(profile))})}}}diff --git a/mobile/android/features/src/test/kotlin/com/voicestudio/mobile/features/ContentReportsTest.kt b/mobile/android/features/src/test/kotlin/com/voicestudio/mobile/features/ContentReportsTest.ktnew file mode 100644index 000000000..1bace4049--- /dev/null+++ b/mobile/android/features/src/test/kotlin/com/voicestudio/mobile/features/ContentReportsTest.kt@@ -0,0 +1,138 @@+package com.voicestudio.mobile.features++import com.voicestudio.mobile.local.*+import com.voicestudio.mobile.network.ContentReport+import com.voicestudio.mobile.network.ContentReportClient+import com.voicestudio.mobile.network.ReportSubject+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.yield+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.*+import org.junit.Assert.*++class ContentReportsTest {+ private lateinit var server: MockWebServer+ private lateinit var client: ContentReportClient+ private val subject = ReportSubject("speak:phone:1", "speak", "phone", "org/model", "a".repeat(40), "Typed words")+ @Before fun setup() { server = MockWebServer(); server.start(); client = ContentReportClient(server.url("/").toString(), "1.2.3") }+ @After fun teardown() { server.shutdown() }+ private fun model(id: String, capability: String, revision: String = "a".repeat(40)) = PhoneModel(id, capability, "omnivoice.cpp", "org/$id", revision,+ emptyList(), 1, listOf("en"), 1.0, ModelLicence("mit", "commercial-ok", false, "", "", "b".repeat(64)))++ @Test fun draftStartsEmptyAndSurvivesClosingTheSheet() {+ runBlocking {+ val reports = ContentReports(this)+ reports.open(subject)+ val opened = reports.sheet.value!!+ assertNull(opened.draft.reason)+ assertFalse(opened.draft.includeText)+ assertFalse("Send is disabled until a reason is chosen", opened.canSend)+ reports.edit { it.copy(reason = "hateful", note = "n".repeat(1500), includeText = true) }+ reports.close()+ assertNull(reports.sheet.value)+ reports.open(subject)+ val reopened = reports.sheet.value!!+ assertEquals("hateful", reopened.draft.reason)+ assertEquals(ContentReport.NOTE_LIMIT, reopened.draft.note.length)+ assertTrue(reopened.draft.includeText)+ assertEquals(opened.draft.idempotencyKey, reopened.draft.idempotencyKey)+ assertTrue(reopened.canSend)+ // Another result has its own draft.+ reports.open(subject.copy(id = "speak:phone:2"))+ assertNull(reports.sheet.value!!.draft.reason)+ }+ }+ @Test fun includeTextNeedsTypedText() {+ runBlocking {+ val reports = ContentReports(this)+ reports.open(ReportSubject("clone:computer:p", "clone", "computer", "unknown"))+ reports.edit { it.copy(includeText = true) }+ assertFalse(reports.sheet.value!!.draft.includeText)+ }+ }+ @Test fun failureKeepsDraftAndKeyForRetryThenSuccessDiscardsIt() {+ runBlocking {+ val reports = ContentReports(this)+ reports.open(subject)+ reports.edit { it.copy(reason = "other") }+ val key = reports.sheet.value!!.draft.idempotencyKey+ server.enqueue(MockResponse().setResponseCode(503))+ reports.send(client)!!.join()+ assertEquals(ReportStatus.FAILED, reports.sheet.value!!.status)+ assertEquals(key, reports.draft(subject.id)!!.idempotencyKey)+ var sent = 0+ val collector = launch(kotlinx.coroutines.Dispatchers.Unconfined) { reports.sent.collect { sent++ } }+ server.enqueue(MockResponse().setResponseCode(201).setBody("{}"))+ reports.send(client)!!.join()+ assertEquals(key, server.takeRequest().getHeader("Idempotency-Key"))+ assertEquals(key, server.takeRequest().getHeader("Idempotency-Key"))+ assertNull("The sheet closes", reports.sheet.value)+ assertNull("The draft is discarded", reports.draft(subject.id))+ yield()+ assertEquals(1, sent)+ collector.cancel()+ }+ }+ @Test fun conflictKeepsTheNewKey() {+ runBlocking {+ val reports = ContentReports(this)+ reports.open(subject)+ reports.edit { it.copy(reason = "other") }+ val key = reports.sheet.value!!.draft.idempotencyKey+ server.enqueue(MockResponse().setResponseCode(409)); server.enqueue(MockResponse().setResponseCode(503))+ reports.send(client)!!.join()+ server.takeRequest()+ val second = server.takeRequest().getHeader("Idempotency-Key")+ assertNotEquals(key, second)+ assertEquals(second, reports.draft(subject.id)!!.idempotencyKey)+ }+ }+ @Test fun rateLimitedAndInvalidKeepTheSheet() {+ runBlocking {+ val reports = ContentReports(this)+ reports.open(subject)+ reports.edit { it.copy(reason = "other") }+ server.enqueue(MockResponse().setResponseCode(429))+ reports.send(client)!!.join()+ assertEquals(ReportStatus.RATE_LIMITED, reports.sheet.value!!.status)+ assertEquals("other", reports.sheet.value!!.draft.reason)+ server.enqueue(MockResponse().setResponseCode(400))+ reports.send(client)!!.join()+ assertEquals(ReportStatus.INVALID, reports.sheet.value!!.status)+ assertFalse("A rejected report is not retried", reports.sheet.value!!.canSend)+ assertNull(reports.send(client))+ assertEquals(2, server.requestCount)+ }+ }+ @Test fun subjectsCarryTaskPlaceAndModel() {+ val take = ReportSubjects.phoneSpeak(PhoneGeneration("t", "Hello", 1, "org/tts", "c".repeat(40)))+ assertEquals(listOf("speak", "phone", "org/tts", "c".repeat(40), "Hello"), listOf(take.task, take.runsOn, take.modelId, take.modelRevision, take.typedText))+ val older = ReportSubjects.phoneSpeak(PhoneGeneration("t", "Hello", 1))+ assertEquals("unknown", older.modelId); assertNull(older.modelRevision)+ val voice = ReportSubjects.phoneClone(PhoneVoice("v", "Name", "Transcript", 1, 1, modelRepo = "org/asr", modelRevision = "d".repeat(40)))+ assertEquals(listOf("clone", "phone", "org/asr", "d".repeat(40)), listOf(voice.task, voice.runsOn, voice.modelId, voice.modelRevision))+ assertFalse(voice.hasTypedText)+ val host = ReportSubjects.computerClone(com.voicestudio.mobile.network.Profile("p", "Name"))+ assertEquals(listOf("clone", "computer", "unknown"), listOf(host.task, host.runsOn, host.modelId))+ val hostTake = ReportSubjects.computerSpeak("/audio/a.wav", "Typed", "omni voice!")+ assertEquals(listOf("speak", "computer", "omnivoice", "Typed"), listOf(hostTake.task, hostTake.runsOn, hostTake.modelId, hostTake.typedText))+ assertEquals("unknown", ReportSubjects.computerSpeak("/audio/a.wav", "Typed", null).modelId)+ assertEquals(listOf("dub", "computer", "unknown"), ReportSubjects.computerDub("job").let { listOf(it.task, it.runsOn, it.modelId) })+ }+ @Test fun phoneDubReportsThePinnedVoiceModel() {+ val clone = model("clone-a", "clone"); val asr = model("asr-a", "asr")+ val request = PhoneDubRequest("id", "Title", "source.mp4", emptyList(), listOf(modelPin(asr), modelPin(clone)), 1, 1)+ val exact = ReportSubjects.phoneDub(request, listOf(asr, clone))+ assertEquals(listOf("dub", "phone", "org/clone-a", "a".repeat(40)), listOf(exact.task, exact.runsOn, exact.modelId, exact.modelRevision))+ // The catalogue moved to a new revision: keep the repo, never claim the new revision.+ val moved = ReportSubjects.phoneDub(request, listOf(asr, model("clone-a", "clone", "e".repeat(40))))+ assertEquals("org/clone-a", moved.modelId); assertNull(moved.modelRevision)+ assertEquals("unknown", ReportSubjects.phoneDub(request, listOf(asr)).modelId)+ }+ @Test fun reasonsMatchTheContractOrder() {+ assertEquals(ContentReport.REASONS, reportReasons.map { it.first })+ reportReasons.forEach { (id, key) -> assertEquals("mobile.report.reasons.$id", key) }+ }+}diff --git a/mobile/contract/SPEC.md b/mobile/contract/SPEC.mdindex 91cc680f2..572772d4f 100644--- a/mobile/contract/SPEC.md+++ b/mobile/contract/SPEC.md@@ -265,7 +265,8 @@ progress visible and resumes from a saved checkpoint after interruption).### PrivacyOn-device tasks send nothing anywhere. The only network requests are the model-downloads the user starts and, when paired, requests to their own computer.+downloads the user starts, content reports the user sends (see Reporting+generated content) and, when paired, requests to their own computer.Settings → Privacy states this.### Tests (in addition to M1)@@ -281,3 +282,57 @@ Settings → Privacy states this.VoiceStudioKit; Android on an `x86_64` emulator).- Routing: phone / computer / download prompt choices, and offline use with nocomputer paired.++## Reporting generated content++Google Play's AI-generated content policy requires an in-app way to report+offensive output; both apps ship it. The server is VoiceStudio's app API+(`POST /v1/content-reports`, spec `api/openapi/v1.yaml` in the vssaas+repository). It needs no sign-in and accepts no audio or identifiers.++- **Where:** every generated result the app shows has a **Report** action,+ whether it ran on the phone or the paired computer: a Speak result and its+ recent takes (`task: speak`), the cloned-voice result on Voices+ (`task: clone`) and a finished dub (`task: dub`).+- **Sheet:** title, a required reason chosen from five (`sexual`, `hateful`,+ `impersonation`, `misleading`, `other`; none preselected, Send disabled until+ one is picked), an optional note (at most 1000 characters), an **Include the+ text I entered** checkbox (unchecked, shown only when the result has text the+ user typed), the disclosure of what is sent, and Send / Cancel.+- **Nothing is sent until Send.** The request carries only the fields below; an+ unticked checkbox omits `prompt_text`, and empty optional fields are omitted.++ | Field | Value |+ |---|---|+ | `reason` | the chosen reason |+ | `note` | trimmed note, if any |+ | `prompt_text` | the typed text (first 5000 characters), only when ticked |+ | `platform` | `android` / `ios` |+ | `app_version` | root `package.json` version |+ | `task` | `speak` / `clone` / `dub` |+ | `model_id` | phone: the `repo` from `models.json` of the model that made it (Speak: the TTS or clone model; a cloned voice: the `asr` model that transcribed its reference; a dub: its pinned `clone` model; results saved before this feature: `unknown`); computer: the engine id the host reported, else `unknown` (characters outside `0-9A-Za-z._/:-` removed, at most 128) |+ | `model_revision` | phone only: the model's `revision` |+ | `runs_on` | `phone` / `computer` |++- **Request:** `POST <base>/v1/content-reports`, `Content-Type:+ application/json`, `Idempotency-Key` and no `Authorization`. Release builds+ use `https://appapi.voicestudio.sh`; debug builds use+ `https://dev-appapi.voicestudio.sh`. The key (32 characters of+ `A-Za-z0-9`) is made when the sheet opens and reused when the user retries,+ so a retried report is stored once.+- **Responses:**++ | Status | App |+ |---|---|+ | 201 | Close the sheet, show `mobile.report.sent`, discard the draft |+ | 409 | Make a new key and send once more automatically |+ | 429 | Keep the sheet and draft, show `mobile.report.rate_limited` |+ | 400 | Show `mobile.report.invalid`; no retry (an app bug) |+ | anything else, or no connection | Keep the draft, show `mobile.report.failed` with Retry |++- **Draft:** kept in memory per result until it is sent, so closing and+ reopening the sheet keeps the reason, note and checkbox.+- **Tests:** against a mock server: exact body (no extra fields, prompt text+ only when ticked, optional fields omitted when empty), headers (key format,+ no `Authorization`), the same key on Retry, a new key after 409, 429 and 400+ handling, and the base URL per build type.diff --git a/mobile/contract/strings.mobile.en.json b/mobile/contract/strings.mobile.en.jsonindex 339e30d32..95d36d722 100644--- a/mobile/contract/strings.mobile.en.json+++ b/mobile/contract/strings.mobile.en.json@@ -356,6 +356,28 @@},"consent": {"phone_note": "Saved on this phone. Nothing is sent."+ },+ "report": {+ "action": "Report",+ "title": "Report this result",+ "reason": "What's wrong with it?",+ "reasons": {+ "sexual": "Sexual content",+ "hateful": "Hateful or abusive",+ "impersonation": "Impersonation or a voice cloned without consent",+ "misleading": "Misleading or harmful",+ "other": "Something else"+ },+ "note": "Details (optional)",+ "include_text": "Include the text I entered",+ "disclosure": "Sends your reason, note, the app version and the model that made this to the VoiceStudio team. No audio, account or device ID is sent.",+ "send": "Send report",+ "sending": "Sending…",+ "sent": "Report sent. Thank you.",+ "failed": "Couldn't send the report. Check your connection and try again.",+ "retry": "Try again",+ "rate_limited": "Too many reports from this network. Try again later.",+ "invalid": "This report couldn't be sent. Update the app and try again."}}}diff --git a/mobile/ios/VoiceStudio/App/AppModel.swift b/mobile/ios/VoiceStudio/App/AppModel.swiftindex ea4edca91..d377182be 100644--- a/mobile/ios/VoiceStudio/App/AppModel.swift+++ b/mobile/ios/VoiceStudio/App/AppModel.swift@@ -17,6 +17,20 @@ import BackgroundTasksvar history: [HistoryItem] { get { hostState.history } set { hostState.history = newValue } }var dubHistory: [DubHistoryItem] { get { hostState.dubHistory } set { hostState.dubHistory = newValue } }var error: ClientError?+ /// A short confirmation key (e.g. `mobile.report.sent`) shown above the tabs.+ var notice: String?+ /// Content-report drafts per result, kept in memory until sent.+ let reports = ContentReports(client: ContentReportClient(baseURL: AppModel.reportBaseURL), appVersion: ContentReportClient.appVersion(info: Bundle.main.infoDictionary))+ /// Debug builds report to the development app API, release builds to production.+ static var reportBaseURL: URL {+ #if DEBUG+ ContentReportClient.baseURL(debug: true)+ #else+ ContentReportClient.baseURL(debug: false)+ #endif+ }+ /// The engine each computer take was generated with, from the host's engine inventory (memory only).+ @ObservationIgnored var computerEngines: [String: String] = [:]var busy = false@ObservationIgnored private var activityCount = 0var consentAnswered: Booldiff --git a/mobile/ios/VoiceStudio/App/ThemeUI.swift b/mobile/ios/VoiceStudio/App/ThemeUI.swiftindex ab1f3aedb..b8179aeec 100644--- a/mobile/ios/VoiceStudio/App/ThemeUI.swift+++ b/mobile/ios/VoiceStudio/App/ThemeUI.swift@@ -176,6 +176,18 @@ struct RootView: View {}}.padding(Theme.compactInset).background(theme.color("errorSurface")).environment(\.vsTheme,theme).studioButton(.tertiary)+ } else if let notice = model.notice {+ HStack(spacing: VSTokens.spacingGap) {+ Label(model.t(notice), systemImage: "checkmark.circle").frame(maxWidth: .infinity, alignment: .leading)+ .fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("notice")+ Button(model.t("common.close")) { model.notice = nil }+ }.padding(Theme.compactInset).background(theme.color("surfaceRaised"))+ .environment(\.vsTheme,theme).studioButton(.tertiary)+ .task(id: notice) {+ AccessibilityNotification.Announcement(model.t(notice)).post()+ try? await Task.sleep(for: .seconds(5))+ if model.notice == notice { model.notice = nil }+ }}}diff --git a/mobile/ios/VoiceStudio/Features/ContentReportSheet.swift b/mobile/ios/VoiceStudio/Features/ContentReportSheet.swiftnew file mode 100644index 000000000..1c3e61e35--- /dev/null+++ b/mobile/ios/VoiceStudio/Features/ContentReportSheet.swift@@ -0,0 +1,111 @@+import SwiftUI+import VoiceStudioKit++/// The Report action on a generated result (SPEC.md → Reporting generated content).+struct ReportButton: View {+ @Environment(AppModel.self) private var model+ let subject: ContentReportSubject+ @Binding var reporting: ContentReportSubject?+ /// The result's title, so VoiceOver says what is being reported.+ var context: String? = nil+ var body: some View {+ Button(model.t("mobile.report.action"), systemImage: "flag") {+ model.reports.open(subject); reporting = subject+ }+ .accessibilityLabel(context.map { model.t("mobile.report.action") + ": " + $0 } ?? model.t("mobile.report.action"))+ .accessibilityIdentifier("report." + subject.id)+ }+}++extension View {+ func contentReportSheet(_ subject: Binding<ContentReportSubject?>) -> some View {+ sheet(item: subject) { ContentReportSheet(subject: $0) }+ }+}++struct ContentReportSheet: View {+ @Environment(AppModel.self) private var model+ @Environment(\.vsTheme) private var theme+ @Environment(\.dismiss) private var dismiss+ let subject: ContentReportSubject+ private var phase: ContentReports.Phase { model.reports.phase(for: subject) }+ private var draft: ContentReportDraft { model.reports.draft(for: subject) ?? ContentReportDraft(idempotencyKey: "") }+ private var binding: Binding<ContentReportDraft> {+ Binding(get: { draft }, set: { model.reports.update($0, for: subject) })+ }+ private var statusKey: String? {+ switch phase {+ case .failed: ContentReportOutcome.failed.messageKey+ case .rateLimited: ContentReportOutcome.rateLimited.messageKey+ case .invalid: ContentReportOutcome.invalid.messageKey+ case .editing, .sending: nil+ }+ }+ var body: some View {+ NavigationStack {+ Form {+ Section {+ ForEach(ContentReportReason.allCases, id: \.self) { reason in+ let selected = draft.reason == reason+ Button { binding.wrappedValue.reason = reason } label: {+ HStack(spacing: VSTokens.spacingGap) {+ Text(model.t(reason.labelKey)).frame(maxWidth: .infinity, alignment: .leading)+ Image(systemName: "checkmark").foregroundStyle(theme.color("messageAction"))+ .opacity(selected ? 1 : 0).accessibilityHidden(true)+ }.frame(minHeight: 44).contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(selected ? [.isSelected] : [])+ .accessibilityIdentifier("report.reason." + reason.rawValue)+ }+ } header: { Text(model.t("mobile.report.reason")) }+ .listRowBackground(theme.color("surface"))+ Section {+ TextField(model.t("mobile.report.note"), text: binding.note, axis: .vertical)+ .lineLimit(3...8).textFieldStyle(.plain).frame(minHeight: 44)+ .accessibilityLabel(model.t("mobile.report.note"))+ .accessibilityIdentifier("report.note")+ if subject.hasTypedText {+ Toggle(model.t("mobile.report.include_text"), isOn: binding.includeText)+ .frame(minHeight: 44).accessibilityIdentifier("report.include_text")+ }+ } footer: { Text(model.t("mobile.report.disclosure")) }+ .listRowBackground(theme.color("surface"))+ if let statusKey {+ Section {+ Text(model.t(statusKey)).foregroundStyle(theme.color("error"))+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("report.status")+ }.listRowBackground(theme.color("errorSurface"))+ }+ }+ .disabled(phase == .sending)+ .scrollContentBackground(.hidden).background(theme.color("surfaceOverlay").ignoresSafeArea())+ .keyboardAccessible()+ .navigationTitle(model.t("mobile.report.title")).navigationBarTitleDisplayMode(.inline)+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button(model.t("common.cancel")) { dismiss() } } }+ .safeAreaInset(edge: .bottom, spacing: 0) {+ Button { send() } label: {+ Label(model.t(phase == .sending ? "mobile.report.sending" : (phase == .failed ? "mobile.report.retry" : "mobile.report.send")),+ systemImage: phase == .failed ? "arrow.clockwise" : "paperplane")+ .frame(maxWidth: .infinity)+ }+ .studioButton(.primary)+ .disabled(!draft.canSend || phase == .sending || phase == .invalid)+ .accessibilityIdentifier("report.send")+ .padding(.horizontal, Theme.compactInset).padding(.vertical, VSTokens.spacingGap / 2)+ }+ }+ .presentationDetents([.large]).presentationDragIndicator(.visible)+ .onAppear { model.reports.open(subject) }+ }+ private func send() {+ let reports = model.reports, report = subject, app = model, close = dismiss+ // Not tied to the sheet: if it is closed mid-send, the outcome still lands on the draft.+ Task { @MainActor in+ guard await reports.send(report) == .sent else { return }+ app.notice = ContentReportOutcome.sent.messageKey+ close()+ }+ }+}diff --git a/mobile/ios/VoiceStudio/Features/DubView.swift b/mobile/ios/VoiceStudio/Features/DubView.swiftindex dc4641c89..b8f61f706 100644--- a/mobile/ios/VoiceStudio/Features/DubView.swift+++ b/mobile/ios/VoiceStudio/Features/DubView.swift@@ -32,6 +32,7 @@ struct ComputerDubView: View {@State private var selectingLanguages = false@State private var shared: SharedFile?@State private var saved: SharedFile?+ @State private var reporting: ContentReportSubject?var languages: [DubLanguage] { model.languages.dubOptions }var body: some View {Page {@@ -66,7 +67,10 @@ struct ComputerDubView: View {if let cp = model.dub.checkpoint {DubJobCard(title: cp.title, stage: model.t("mobile.ios.dub_stages." + cp.stage.rawValue), fraction: model.dub.progress, running: model.dub.monitoring) {if cp.host != model.connection.active?.id { NavigationLink(model.t("mobile.simple.reconnect")) { ConnectView() } }- else if cp.stage == .done { Button(model.t("mobile.dub.download"), systemImage: "arrow.down.to.line") { Task { await download(cp.jobID, name: cp.title) } } }+ else if cp.stage == .done {+ Button(model.t("mobile.dub.download"), systemImage: "arrow.down.to.line") { Task { await download(cp.jobID, name: cp.title) } }+ ReportButton(subject: .computer(.dub, id: cp.jobID, engine: nil), reporting: $reporting, context: cp.title)+ }else if cp.stage != .cancelled {if !model.dub.monitoring { Button(model.t("mobile.ios.upload_resume"), systemImage: "play.fill") { model.monitor() } }Button(model.t("mobile.dub.abort"), systemImage: "xmark", role: .destructive) { Task { await model.perform { model.pauseMonitor(); try await model.dub.abort(api: model.api()) } } }@@ -101,6 +105,7 @@ struct ComputerDubView: View {.fileImporter(isPresented: $importing, allowedContentTypes: [.movie, .audio]) { result inswitch result { case .success(let url): selectedFile = SelectedMedia(url: url); sourceURL = ""; case .failure: model.error = ClientError("mobile.errors.file") }}+ .contentReportSheet($reporting).sheet(item: $shared) { file in ShareSheet(items: [file.url]) }.sheet(item: $saved) { file in SaveFileSheet(url: file.url) }.sheet(isPresented: $selectingLanguages) {@@ -155,6 +160,7 @@ struct ComputerDubView: View {Task { await download(item.job_id ?? item.id, name: item.title, share: true) }}.accessibilityIdentifier("dub.share." + item.id).accessibilityLabel(model.t("mobile.speak.share") + ": " + item.title)+ ReportButton(subject: .computer(.dub, id: item.job_id ?? item.id, engine: nil), reporting: $reporting, context: item.title)}.labelStyle(.iconOnly).studioButton(.tertiary).disabled(model.busy)}private func download(_ id: String, name: String, share: Bool = false) async {diff --git a/mobile/ios/VoiceStudio/Features/PhoneDubView.swift b/mobile/ios/VoiceStudio/Features/PhoneDubView.swiftindex df2af1bcf..4b91adfba 100644--- a/mobile/ios/VoiceStudio/Features/PhoneDubView.swift+++ b/mobile/ios/VoiceStudio/Features/PhoneDubView.swift@@ -22,6 +22,7 @@ struct PhoneDubView: View {@State private var playing: SharedFile?@State private var creating: Task<Void,Never>?@State private var copying = false+ @State private var reporting: ContentReportSubject?private var choices: [DubLanguage] { model.languages.dubOptions }private var ready: Bool { model.phone.dubReady && !connect }var body: some View {@@ -74,6 +75,7 @@ struct PhoneDubView: View {Button(model.t("common.play"),systemImage: "play.fill") { open(record,output,action: .play) }Button(model.t("mobile.speak.share"),systemImage: "square.and.arrow.up") { open(record,output,action: .share) }Button(model.t("common.save"),systemImage: "arrow.down.to.line") { open(record,output,action: .save) }+ ReportButton(subject: reportSubject(record,output), reporting: $reporting, context: record.request.title + " " + output.name)if record.checkpoint.done { Button(model.t("mobile.simple.remove_job"),systemImage: "trash",role: .destructive) { remove(record) } }}.labelStyle(.iconOnly).studioButton(.tertiary)}@@ -94,6 +96,7 @@ struct PhoneDubView: View {.sheet(isPresented: $languages) {LanguageSelectionSheet(selection: targets, includesUnavailable: false) { targets = $0 }}+ .contentReportSheet($reporting).sheet(item: $shared) { file in ShareSheet(items: [file.url]) }.sheet(item: $saved) { file in SaveFileSheet(url: file.url) }.sheet(item: $playing) { file in PhoneDubPlayback(url: file.url) }@@ -129,6 +132,11 @@ struct PhoneDubView: View {switch action { case .play: playing = file; case .share: shared = file; case .save: saved = file }} }}+ /// The dub's speech comes from its pinned voice (clone) model.+ private func reportSubject(_ record: PhoneDubRecord,_ output: PhoneDubOutput) -> ContentReportSubject {+ let voiceModel = model.phone.models.first { $0.capability == .clone && record.request.modelPins[$0.id] != nil }+ return .phone(.dub, id: record.id.uuidString + ":" + output.language, repo: voiceModel?.repo, revision: voiceModel?.revision)+ }private func remove(_ record: PhoneDubRecord) {Task { await model.performPhone { try await model.phone.dubStore?.delete(record.id); await model.phone.refresh() } }}diff --git a/mobile/ios/VoiceStudio/Features/SpeakView.swift b/mobile/ios/VoiceStudio/Features/SpeakView.swiftindex 649af750f..8b39b946f 100644--- a/mobile/ios/VoiceStudio/Features/SpeakView.swift+++ b/mobile/ios/VoiceStudio/Features/SpeakView.swift@@ -36,6 +36,9 @@ struct SpeakView: View {@State private var generating = false@State private var deleting: HistoryItem?@State private var hostScope: UUID?+ /// The take loaded in the player, for its Report action.+ @State private var result: ContentReportSubject?+ @State private var reporting: ContentReportSubject?private var engines: [SelectionOption] {(model.inventory?.tts.backends ?? []).map {SelectionOption(id: $0.id, title: $0.display_name,@@ -50,7 +53,10 @@ struct SpeakView: View {speechEditorspeechOptionsif route == .download { LocalDownloadPrompt(items: phoneModel.map { [$0] } ?? [], feature: "mobile.tabs.speak") }- if player.file != nil || player.playing { AudioPlayerView(player: player) }+ if player.file != nil || player.playing {+ AudioPlayerView(player: player)+ if let result { ReportButton(subject: result, reporting: $reporting).studioButton(.tertiary) }+ }recentGenerations}.navigationTitle(model.t("mobile.tabs.speak")).navigationBarTitleDisplayMode(.inline).safeAreaInset(edge: .bottom, spacing: 0) {@@ -59,6 +65,7 @@ struct SpeakView: View {.onChange(of: model.inventory?.tts.active, initial: true) { _, _ in selection.reconcile(inventory: model.inventory, profiles: model.profiles) }.onChange(of: model.profiles.map(\.id)) { _, _ in selection.reconcile(inventory: model.inventory, profiles: model.profiles) }.refreshable { if model.connection.client != nil { await model.perform { try await model.refresh() } }; await model.phone.refresh(); selection.reconcile(inventory: model.inventory, profiles: model.profiles) }+ .contentReportSheet($reporting).sheet(item: $deleting) { item inDeleteConfirmation(title: model.t("mobile.ios.delete_generation")) {Task { await model.perform { try await model.api().deleteHistory(item.id); model.history = try await model.api().history() } }@@ -144,7 +151,9 @@ struct SpeakView: View {Button(model.t("common.play"),systemImage: "play.fill") { Task { await model.performPhone {guard let store = model.phone.generationStore else { throw ClientError("mobile.errors.file") }try await player.load(Data(contentsOf: await store.file(item)),extension: "wav"); player.play()+ result = phoneSubject(item)} } }+ ReportButton(subject: phoneSubject(item), reporting: $reporting, context: item.text)Button(model.t("common.delete"),systemImage: "trash",role: .destructive) { Task { await model.performPhone { try await model.phone.generationStore?.delete(item); await model.phone.refresh() } } }}.labelStyle(.iconOnly).studioButton(.tertiary)}@@ -154,10 +163,11 @@ struct SpeakView: View {ForEach(model.history) { item inHStack(spacing: VSTokens.spacingGap) {Text(item.text).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)- Button(model.t("common.play"), systemImage: "play.fill") { Task { await model.perform { let api = try model.api(); try await player.stream(request: api.historyAudioRequest(item.id), api: api) } } }+ Button(model.t("common.play"), systemImage: "play.fill") { Task { await model.perform { let api = try model.api(); try await player.stream(request: api.historyAudioRequest(item.id), api: api); result = computerSubject(item.id, text: item.text) } } }.labelStyle(.iconOnly).studioButton(.tertiary)Menu {Button(model.t(item.starred ? "mobile.speak.unstar" : "mobile.speak.star"), systemImage: item.starred ? "star.fill" : "star") { Task { await model.perform { try await model.api().star(item); model.history = try await model.api().history() } } }+ ReportButton(subject: computerSubject(item.id, text: item.text), reporting: $reporting, context: item.text)Button(model.t("common.delete"), systemImage: "trash", role: .destructive) { deleting = item }} label: { Label(model.t("mobile.ios.more_actions"), systemImage: "ellipsis") }.labelStyle(.iconOnly).studioButton(.tertiary).frame(minWidth: 44, minHeight: 44)@@ -184,13 +194,17 @@ struct SpeakView: View {} else {audio = try await engine.synthesize(model: phoneModel.selectingLanguage(phoneLanguage),text: submittedText,speaker: Int(speakerID) ?? 0,speed: 1,progress: report)}- _ = try await model.phone.generationStore?.save(text: submittedText,audio: audio)+ let saved = try await model.phone.generationStore?.save(text: submittedText,audio: audio,model: phoneModel)await model.phone.refresh()try await player.load(audio.markSynthetic(), extension: "wav")+ self.result = saved.map(phoneSubject) ?? .phone(.speak, id: UUID().uuidString, repo: phoneModel.repo, revision: phoneModel.revision, typedText: submittedText)return}+ let hostEngine = selection.engineID.isEmpty ? model.inventory?.tts.active : selection.engineIDlet result = try await model.hostState.generate(api: model.api(), text: submittedText, profile: selection.profileID, engine: selection.engineID, language: selection.language)+ if let hostEngine { model.computerEngines[result.id] = hostEngine }try await player.load(result.audio, extension: "wav")+ self.result = computerSubject(result.id, text: submittedText)model.history = try await model.api().history()}}@@ -206,6 +220,12 @@ struct SpeakView: View {}}}+ private func phoneSubject(_ item: PhoneGeneration) -> ContentReportSubject {+ .phone(.speak, id: item.id.uuidString, repo: item.modelRepo, revision: item.modelRevision, typedText: item.text)+ }+ private func computerSubject(_ id: String, text: String) -> ContentReportSubject {+ .computer(.speak, id: id, engine: model.computerEngines[id], typedText: text)+ }private func reconcilePhone() {if phoneVoice != nil { phoneLanguage = "auto" }else {diff --git a/mobile/ios/VoiceStudio/Features/VoicesView.swift b/mobile/ios/VoiceStudio/Features/VoicesView.swiftindex a0b42586f..79f548ae1 100644--- a/mobile/ios/VoiceStudio/Features/VoicesView.swift+++ b/mobile/ios/VoiceStudio/Features/VoicesView.swift@@ -8,6 +8,11 @@ private struct VoiceEntry: Identifiable {let phone: PhoneVoice?init(_ voice: PhoneVoice) { id = "phone:"+voice.id.uuidString; name = voice.name; phone = voice }init(_ voice: Profile) { id = voice.id; name = voice.name; phone = nil }+ /// A phone voice reports the catalogue model that made it; the computer reports no engine for a clone.+ var reportSubject: ContentReportSubject {+ if let phone { return .phone(.clone, id: phone.id.uuidString, repo: phone.modelRepo, revision: phone.modelRevision) }+ return .computer(.clone, id: id, engine: nil)+ }}struct VoicesView: View {@Environment(AppModel.self) private var model@@ -19,6 +24,7 @@ struct VoicesView: View {@State private var deleting: VoiceEntry?@State private var name = ""@State private var hostScope: UUID?+ @State private var reporting: ContentReportSubject?private var entries: [VoiceEntry] { model.phone.voices.map(VoiceEntry.init) + model.profiles.map(VoiceEntry.init) }private var filtered: [VoiceEntry] { entries.filter { query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) } }var body: some View {@@ -52,6 +58,7 @@ struct VoicesView: View {}.labelStyle(.iconOnly).studioButton(.tertiary)Menu {Button(model.t("mobile.voices.rename"),systemImage: "pencil") { name = entry.name; renamed = entry }+ ReportButton(subject: entry.reportSubject, reporting: $reporting, context: entry.name)Button(model.t("common.delete"),systemImage: "trash",role: .destructive) { deleting = entry }} label: { Label(model.t("mobile.ios.more_actions"),systemImage: "ellipsis") }.labelStyle(.iconOnly).studioButton(.tertiary).frame(minWidth: 44,minHeight: 44).accessibilityIdentifier("voices.actions."+entry.id)@@ -77,6 +84,7 @@ struct VoicesView: View {}.task { await model.phone.refresh() }.refreshable { await model.phone.refresh(); if model.connection.client != nil { await model.perform { model.profiles = try await model.api().profiles() } } }+ .contentReportSheet($reporting).fullScreenCover(isPresented: $creating) { NavigationStack { CloneView() }.environment(model) }.sheet(item: $renamed) { entry inNavigationStack {diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneGenerations.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneGenerations.swiftindex dd80731da..b4c4d7a35 100644--- a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneGenerations.swift+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneGenerations.swift@@ -4,6 +4,9 @@ public struct PhoneGeneration: Codable, Sendable, Identifiable {public let id: UUIDpublic let text: Stringpublic let createdAt: Date+ /// The catalogue model that made this take, for content reports. Absent on takes saved before it was recorded.+ public let modelRepo: String?+ public let modelRevision: String?}public actor PhoneGenerationStore {private let root: URL@@ -11,8 +14,8 @@ public actor PhoneGenerationStore {public func list() throws -> [PhoneGeneration] {try FileManager.default.contentsOfDirectory(at: root,includingPropertiesForKeys: nil).filter { $0.pathExtension == "json" }.compactMap { try? PrivateFiles.read(PhoneGeneration.self,from: PrivateFiles.child(root,$0.lastPathComponent)) }.sorted { $0.createdAt > $1.createdAt }}- public func save(text: String, audio: LocalAudio) throws -> PhoneGeneration {- let item = PhoneGeneration(id: UUID(),text: text,createdAt: Date())+ public func save(text: String, audio: LocalAudio, model: PhoneModel? = nil) throws -> PhoneGeneration {+ let item = PhoneGeneration(id: UUID(),text: text,createdAt: Date(),modelRepo: model?.repo,modelRevision: model?.revision)let url = try file(item)do {try audio.markSynthetic().write(to: url,options: .atomic)diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneVoices.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneVoices.swiftindex fd442ddb1..14802a874 100644--- a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneVoices.swift+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Local/PhoneVoices.swift@@ -7,6 +7,9 @@ public struct PhoneVoice: Codable, Identifiable, Sendable, Equatable {public let createdAt: Datepublic let consentAt: Datepublic let sampleRate: Int+ /// The catalogue model that transcribed this voice, for content reports. Absent on voices made before it was recorded.+ public var modelRepo: String? = nil+ public var modelRevision: String? = nil}public protocol PhoneAudioDecoder: Sendable {func decode(source: URL, output: URL, maxSeconds: Double, progress: @escaping @Sendable (Double) async -> Void) async throws -> PCMFile@@ -44,7 +47,7 @@ public actor PhoneVoiceStore {// This is the user's reference, not synthesized output.try ReferenceWave.write(reference, to: actualDir.appendingPathComponent("reference.wav"))try Task.checkCancellation()- let voice = PhoneVoice(id: id,name: name.trimmingCharacters(in: .whitespacesAndNewlines),transcript: transcript,createdAt: now,consentAt: now,sampleRate: 24000)+ let voice = PhoneVoice(id: id,name: name.trimmingCharacters(in: .whitespacesAndNewlines),transcript: transcript,createdAt: now,consentAt: now,sampleRate: 24000,modelRepo: asr.repo,modelRevision: asr.revision)try PrivateFiles.write(voice,to: actualDir.appendingPathComponent("voice.json")); return voice} catch { try? FileManager.default.removeItem(at: actualDir); throw error }}diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Models/ContentReport.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Models/ContentReport.swiftnew file mode 100644index 000000000..120fe0e0f--- /dev/null+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Models/ContentReport.swift@@ -0,0 +1,171 @@+import Foundation+import Observation++/// Reporting generated content (contract: SPEC.md → Reporting generated content).+public enum ContentReportReason: String, CaseIterable, Codable, Sendable {+ case sexual, hateful, impersonation, misleading, other+ public var labelKey: String { "mobile.report.reasons." + rawValue }+}+public enum ContentReportTask: String, Codable, Sendable { case speak, clone, dub }+public enum ContentReportRunsOn: String, Codable, Sendable { case phone, computer }++/// One generated result the person can report, and what produced it.+public struct ContentReportSubject: Identifiable, Hashable, Sendable {+ /// Stable per result; drafts are kept under it until sent.+ public let id: String+ public let task: ContentReportTask+ public let runsOn: ContentReportRunsOn+ public let modelID: String+ public let modelRevision: String?+ /// Text the person typed for this result, offered only behind the "include text" checkbox.+ public let typedText: String?+ public init(id: String, task: ContentReportTask, runsOn: ContentReportRunsOn, modelID: String?, modelRevision: String? = nil, typedText: String? = nil) {+ self.id = id; self.task = task; self.runsOn = runsOn+ self.modelID = Self.sanitizeModelID(modelID)+ self.modelRevision = runsOn == .phone ? Self.sanitizeRevision(modelRevision) : nil+ self.typedText = typedText?.nilIfBlank+ }+ /// A result made on the phone: the catalogue model's `repo` and `revision`.+ public static func phone(_ task: ContentReportTask, id: String, repo: String?, revision: String?, typedText: String? = nil) -> Self {+ Self(id: task.rawValue + ":phone:" + id, task: task, runsOn: .phone, modelID: repo, modelRevision: revision, typedText: typedText)+ }+ /// A result made on the paired computer: the engine id the host reported, else `unknown`.+ public static func computer(_ task: ContentReportTask, id: String, engine: String?, typedText: String? = nil) -> Self {+ Self(id: task.rawValue + ":computer:" + id, task: task, runsOn: .computer, modelID: engine, typedText: typedText)+ }+ public var hasTypedText: Bool { typedText != nil }+ /// Characters outside `0-9A-Za-z._/:-` removed, at most 128; `unknown` when nothing is left.+ public static func sanitizeModelID(_ raw: String?) -> String {+ let kept = String(String.UnicodeScalarView((raw ?? "").unicodeScalars.filter { allowed($0, extra: "._/:-") }).prefix(128))+ return kept.isEmpty ? "unknown" : kept+ }+ /// Server pattern `^[0-9A-Za-z._-]{1,64}$`; omitted when nothing is left.+ public static func sanitizeRevision(_ raw: String?) -> String? {+ let kept = String(String.UnicodeScalarView((raw ?? "").unicodeScalars.filter { allowed($0, extra: "._-") }).prefix(64))+ return kept.isEmpty ? nil : kept+ }+ static func allowed(_ scalar: Unicode.Scalar, extra: String) -> Bool {+ scalar.isASCII && (CharacterSet.alphanumerics.contains(scalar) || extra.unicodeScalars.contains(scalar))+ }+}++/// What the person has entered so far; kept in memory per result until it is sent.+public struct ContentReportDraft: Equatable, Sendable {+ public static let noteLimit = 1000+ public static let promptLimit = 5000+ public var reason: ContentReportReason?+ public var note: String { didSet { let capped = note.prefix(utf16Limit: Self.noteLimit); if capped != note { note = capped } } }+ public var includeText: Bool+ /// Made when the sheet first opens and reused on Retry, so a retried report is stored once.+ public internal(set) var idempotencyKey: String+ public init(reason: ContentReportReason? = nil, note: String = "", includeText: Bool = false, idempotencyKey: String = IdempotencyKey.make()) {+ self.reason = reason; self.note = note.prefix(utf16Limit: Self.noteLimit); self.includeText = includeText; self.idempotencyKey = idempotencyKey+ }+ public var canSend: Bool { reason != nil }+}++/// The exact request body. Optional fields are omitted when empty (synthesized+/// `Encodable` skips nil optionals), so no other key can appear.+public struct ContentReportBody: Encodable, Equatable, Sendable {+ public let reason: String+ public let note: String?+ public let prompt_text: String?+ public let platform: String+ public let app_version: String+ public let task: String+ public let model_id: String+ public let model_revision: String?+ public let runs_on: String+ public init?(subject: ContentReportSubject, draft: ContentReportDraft, appVersion: String, platform: String = "ios") {+ guard let reason = draft.reason else { return nil }+ self.reason = reason.rawValue+ note = draft.note.trimmingCharacters(in: .whitespacesAndNewlines).prefix(utf16Limit: ContentReportDraft.noteLimit).nilIfBlank+ prompt_text = draft.includeText ? subject.typedText?.prefix(utf16Limit: ContentReportDraft.promptLimit).nilIfBlank : nil+ self.platform = platform+ app_version = appVersion+ task = subject.task.rawValue+ model_id = subject.modelID+ model_revision = subject.runsOn == .phone ? subject.modelRevision : nil+ runs_on = subject.runsOn.rawValue+ }+}++public enum IdempotencyKey {+ static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")+ /// 32 characters of `A-Za-z0-9` from the system CSPRNG.+ public static func make() -> String {+ var rng = SystemRandomNumberGenerator()+ return String((0..<32).map { _ in alphabet.randomElement(using: &rng)! })+ }+ public static func isValid(_ key: String) -> Bool {+ key.count == 32 && key.unicodeScalars.allSatisfy { $0.isASCII && CharacterSet.alphanumerics.contains($0) }+ }+}++public enum ContentReportOutcome: Equatable, Sendable {+ case sent, rateLimited, invalid, failed+ public var messageKey: String {+ switch self {+ case .sent: "mobile.report.sent"+ case .rateLimited: "mobile.report.rate_limited"+ case .invalid: "mobile.report.invalid"+ case .failed: "mobile.report.failed"+ }+ }+}++/// Drafts and send state per result. Nothing is sent until `send`.+@MainActor @Observable public final class ContentReports {+ public enum Phase: Equatable, Sendable { case editing, sending, failed, rateLimited, invalid }+ private var drafts: [String: ContentReportDraft] = [:]+ private var phases: [String: Phase] = [:]+ @ObservationIgnored private let client: ContentReportClient+ @ObservationIgnored private let appVersion: String+ public init(client: ContentReportClient, appVersion: String) { self.client = client; self.appVersion = appVersion }+ /// Returns the kept draft, or starts one (with a new idempotency key) when the sheet first opens.+ @discardableResult public func open(_ subject: ContentReportSubject) -> ContentReportDraft {+ if let draft = drafts[subject.id] { return draft }+ let draft = ContentReportDraft(idempotencyKey: client.makeKey())+ drafts[subject.id] = draft+ return draft+ }+ public func draft(for subject: ContentReportSubject) -> ContentReportDraft? { drafts[subject.id] }+ /// Applies the person's edits; the idempotency key stays the one this store holds.+ public func update(_ draft: ContentReportDraft, for subject: ContentReportSubject) {+ guard phase(for: subject) != .sending else { return }+ var next = draft+ next.includeText = subject.hasTypedText && draft.includeText+ if let current = drafts[subject.id] { next.idempotencyKey = current.idempotencyKey }+ drafts[subject.id] = next+ }+ public func phase(for subject: ContentReportSubject) -> Phase { phases[subject.id] ?? .editing }+ public func send(_ subject: ContentReportSubject) async -> ContentReportOutcome? {+ guard phase(for: subject) != .sending, let draft = drafts[subject.id],+ let body = ContentReportBody(subject: subject, draft: draft, appVersion: appVersion) else { return nil }+ phases[subject.id] = .sending+ let (outcome, key) = await client.submit(body, key: draft.idempotencyKey)+ if outcome == .sent { drafts[subject.id] = nil; phases[subject.id] = nil; return .sent }+ drafts[subject.id]?.idempotencyKey = key+ switch outcome {+ case .rateLimited: phases[subject.id] = .rateLimited+ case .invalid: phases[subject.id] = .invalid+ default: phases[subject.id] = .failed+ }+ return outcome+ }+}++extension String {+ /// The longest whole-character prefix of at most `limit` UTF-16 code units, the+ /// strictest of the length measures the server and the Android app use.+ func prefix(utf16Limit limit: Int) -> String {+ guard utf16.count > limit else { return self }+ var out = "", used = 0+ for character in self {+ let size = character.utf16.count+ if used + size > limit { break }+ out.append(character); used += size+ }+ return out+ }+}diff --git a/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Networking/ContentReportClient.swift b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Networking/ContentReportClient.swiftnew file mode 100644index 000000000..5106cda53--- /dev/null+++ b/mobile/ios/VoiceStudioKit/Sources/VoiceStudioKit/Networking/ContentReportClient.swift@@ -0,0 +1,56 @@+import Foundation++/// `POST /v1/content-reports` on VoiceStudio's app API. Deliberately separate from+/// `APIClient`: it never carries the paired host's PIN, session or any `Authorization`.+public struct ContentReportClient: Sendable {+ public static let releaseBaseURL = URL(string: "https://appapi.voicestudio.sh")!+ public static let debugBaseURL = URL(string: "https://dev-appapi.voicestudio.sh")!+ /// Info.plist key holding the root `package.json` version (written by prepare_resources.py).+ public static let appVersionInfoKey = "VoiceStudioAppVersion"+ public static func baseURL(debug: Bool) -> URL { debug ? debugBaseURL : releaseBaseURL }+ /// The full app version (`X.Y.Z` or `X.Y.Z-beta.N`), limited to the server's `^[0-9A-Za-z.+_-]{1,32}$`.+ public static func appVersion(info: [String: Any]?) -> String {+ let raw = (info?[appVersionInfoKey] as? String)?.nilIfBlank ?? (info?["CFBundleShortVersionString"] as? String) ?? ""+ let kept = String(String.UnicodeScalarView(raw.unicodeScalars.filter { ContentReportSubject.allowed($0, extra: ".+_-") }).prefix(32))+ return kept.isEmpty ? "unknown" : kept+ }++ public let baseURL: URL+ public let transport: any HTTPTransport+ public let makeKey: @Sendable () -> String+ public init(baseURL: URL, transport: any HTTPTransport = URLSessionTransport(), makeKey: @escaping @Sendable () -> String = IdempotencyKey.make) {+ self.baseURL = baseURL; self.transport = transport; self.makeKey = makeKey+ }+ public func request(_ body: ContentReportBody, key: String) throws -> URLRequest {+ var r = URLRequest(url: baseURL.appendingPathComponent("v1/content-reports"), cachePolicy: .reloadIgnoringLocalAndRemoteCacheData)+ r.httpMethod = "POST"+ r.httpShouldHandleCookies = false+ r.setValue("application/json", forHTTPHeaderField: "Content-Type")+ r.setValue("application/json", forHTTPHeaderField: "Accept")+ r.setValue(key, forHTTPHeaderField: "Idempotency-Key")+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]+ r.httpBody = try encoder.encode(body)+ return r+ }+ /// Sends once; on 409 makes a new key and sends once more. Returns the outcome+ /// and the key to reuse on Retry.+ public func submit(_ body: ContentReportBody, key: String) async -> (ContentReportOutcome, String) {+ var key = key+ for attempt in 0..<2 {+ let status: Int+ do { status = try await transport.send(request(body, key: key)).status }+ catch { return (.failed, key) }+ switch status {+ case 201: return (.sent, key)+ case 409:+ // The key was used with a different body; it can never succeed again.+ key = makeKey()+ if attempt == 1 { return (.failed, key) }+ case 429: return (.rateLimited, key)+ case 400: return (.invalid, key)+ default: return (.failed, key)+ }+ }+ return (.failed, key)+ }+}diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContentReportTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContentReportTests.swiftnew file mode 100644index 000000000..6f34f34f8--- /dev/null+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContentReportTests.swift@@ -0,0 +1,197 @@+import Foundation+import Testing+@testable import VoiceStudioKit++/// Mock app API: answers each request with the next queued status (or throws for `nil`).+private actor ReportServer: HTTPTransport {+ private(set) var requests: [URLRequest] = []+ private var statuses: [Int?]+ init(_ statuses: [Int?]) { self.statuses = statuses }+ func send(_ request: URLRequest) throws -> HTTPReply {+ requests.append(request)+ let status = statuses.isEmpty ? 201 : statuses.removeFirst()+ guard let status else { throw URLError(.notConnectedToInternet) }+ return HTTPReply(data: data(status == 201 ? #"{"report_id":"AAAAAAAAAAAAAAAA","received_at":"2026-10-24T00:00:00Z"}"# : #"{"error":"x"}"#), status: status)+ }+}+private final class KeySequence: @unchecked Sendable {+ private let lock = NSLock()+ private var next = 0+ func make() -> String { lock.withLock { next += 1; return String(repeating: "k", count: 31) + String(next) } }+}+private let base = URL(string: "https://dev-appapi.voicestudio.sh")!+private func body(_ request: URLRequest) throws -> [String: String] {+ let raw = try #require(request.httpBody)+ return try #require(JSONSerialization.jsonObject(with: raw) as? [String: String])+}+private let speak = ContentReportSubject.phone(.speak, id: "take", repo: "k2-fsa/sherpa-onnx", revision: "abc123", typedText: "Hello there")++@Test func contentReportBodyIsExactAndOmitsEmptyFields() throws {+ var draft = ContentReportDraft(idempotencyKey: IdempotencyKey.make())+ #expect(ContentReportBody(subject: speak, draft: draft, appVersion: "0.5.7-beta.2") == nil, "no reason, nothing to send")+ draft.reason = .hateful+ draft.note = " "+ let client = ContentReportClient(baseURL: base)+ let minimal = try client.request(#require(ContentReportBody(subject: speak, draft: draft, appVersion: "0.5.7-beta.2")), key: draft.idempotencyKey)+ #expect(try body(minimal) == ["reason": "hateful", "platform": "ios", "app_version": "0.5.7-beta.2", "task": "speak",+ "model_id": "k2-fsa/sherpa-onnx", "model_revision": "abc123", "runs_on": "phone"])++ draft.note = " rude words \n"+ draft.includeText = true+ let full = try client.request(#require(ContentReportBody(subject: speak, draft: draft, appVersion: "0.5.7")), key: draft.idempotencyKey)+ #expect(try body(full) == ["reason": "hateful", "note": "rude words", "prompt_text": "Hello there", "platform": "ios", "app_version": "0.5.7",+ "task": "speak", "model_id": "k2-fsa/sherpa-onnx", "model_revision": "abc123", "runs_on": "phone"])++ // Computer results never carry a revision; an unreported engine is `unknown`.+ let computer = ContentReportSubject.computer(.dub, id: "job", engine: nil)+ var dub = ContentReportDraft(reason: .other, includeText: true)+ dub.note = ""+ #expect(try body(client.request(#require(ContentReportBody(subject: computer, draft: dub, appVersion: "0.5.7")), key: dub.idempotencyKey))+ == ["reason": "other", "platform": "ios", "app_version": "0.5.7", "task": "dub", "model_id": "unknown", "runs_on": "computer"])+}++@Test func contentReportTextIsCappedAndOnlySentWhenTicked() throws {+ let long = String(repeating: "a", count: 6000)+ let subject = ContentReportSubject.computer(.speak, id: "1", engine: "omnivoice", typedText: long)+ var draft = ContentReportDraft(reason: .misleading)+ draft.note = String(repeating: "n", count: 1500)+ #expect(draft.note.count == ContentReportDraft.noteLimit)+ #expect(ContentReportBody(subject: subject, draft: draft, appVersion: "1")?.prompt_text == nil)+ draft.includeText = true+ #expect(ContentReportBody(subject: subject, draft: draft, appVersion: "1")?.prompt_text?.count == ContentReportDraft.promptLimit)+ // Never split a character across the limit.+ let emoji = String(repeating: "a", count: 4999) + "\u{1F600}"+ #expect(emoji.prefix(utf16Limit: 5000) == String(repeating: "a", count: 4999))+ // Without typed text the checkbox does not exist, and the store will not tick it.+ #expect(!ContentReportSubject.computer(.clone, id: "p", engine: nil, typedText: " ").hasTypedText)+}++@Test func contentReportModelIDIsSanitized() {+ #expect(ContentReportSubject.sanitizeModelID("Omni Voice/v2:large?x=1&é") == "OmniVoice/v2:largex1")+ #expect(ContentReportSubject.sanitizeModelID(nil) == "unknown")+ #expect(ContentReportSubject.sanitizeModelID(" ") == "unknown")+ #expect(ContentReportSubject.sanitizeModelID(String(repeating: "m", count: 200)).count == 128)+ #expect(ContentReportSubject.sanitizeRevision("a/b c") == "abc")+ #expect(ContentReportSubject.sanitizeRevision("///") == nil)+ #expect(ContentReportSubject.computer(.speak, id: "1", engine: "index-tts").modelRevision == nil)+}++@Test func contentReportHeadersCarryKeyAndNoHostCredentials() async throws {+ let server = ReportServer([201])+ let reports = await ContentReports(client: ContentReportClient(baseURL: base, transport: server), appVersion: "0.5.7")+ let draft = await reports.open(speak)+ #expect(IdempotencyKey.isValid(draft.idempotencyKey))+ var picked = draft; picked.reason = .sexual+ await reports.update(picked, for: speak)+ #expect(await reports.send(speak) == .sent)+ let request = try #require(await server.requests.first)+ #expect(request.url?.absoluteString == "https://dev-appapi.voicestudio.sh/v1/content-reports")+ #expect(request.httpMethod == "POST")+ #expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")+ #expect(request.value(forHTTPHeaderField: "Idempotency-Key") == draft.idempotencyKey)+ #expect(request.value(forHTTPHeaderField: "Authorization") == nil)+ #expect(request.value(forHTTPHeaderField: "X-OmniVoice-Pin") == nil)+ #expect(Set(request.allHTTPHeaderFields?.keys.map { $0.lowercased() } ?? []) == ["content-type", "accept", "idempotency-key"])+ // 201 discards the draft and its key.+ #expect(await reports.draft(for: speak) == nil)+ #expect(await reports.open(speak).idempotencyKey != draft.idempotencyKey)+}++@Test func idempotencyKeysAreRandomAlphanumeric() {+ let keys = (0..<200).map { _ in IdempotencyKey.make() }+ #expect(keys.allSatisfy(IdempotencyKey.isValid))+ #expect(Set(keys).count == keys.count)+ #expect(!IdempotencyKey.isValid("short"))+ #expect(!IdempotencyKey.isValid(String(repeating: "-", count: 32)))+}++@Test func contentReportRetryReusesKeyAndKeepsDraft() async throws {+ let server = ReportServer([nil, 503, 404, 201])+ let reports = await ContentReports(client: ContentReportClient(baseURL: base, transport: server), appVersion: "0.5.7")+ var draft = await reports.open(speak)+ draft.reason = .impersonation; draft.note = "kept"; draft.includeText = true+ await reports.update(draft, for: speak)+ #expect(await reports.send(speak) == .failed) // no connection+ #expect(await reports.phase(for: speak) == .failed)+ // Closing and reopening the sheet keeps the reason, note and checkbox.+ #expect(await reports.open(speak) == draft)+ #expect(await reports.send(speak) == .failed) // 503+ #expect(await reports.send(speak) == .failed) // 404+ #expect(await reports.send(speak) == .sent)+ let keys = await server.requests.map { $0.value(forHTTPHeaderField: "Idempotency-Key") }+ #expect(keys.count == 4 && Set(keys) == [draft.idempotencyKey])+}++@Test func contentReportConflictMakesNewKeyAndResendsOnce() async throws {+ let sequence = KeySequence()+ let server = ReportServer([409, 201])+ let reports = await ContentReports(client: ContentReportClient(baseURL: base, transport: server, makeKey: { sequence.make() }), appVersion: "0.5.7")+ var draft = await reports.open(speak); draft.reason = .other+ await reports.update(draft, for: speak)+ #expect(await reports.send(speak) == .sent)+ let keys = await server.requests.compactMap { $0.value(forHTTPHeaderField: "Idempotency-Key") }+ #expect(keys == [draft.idempotencyKey, String(repeating: "k", count: 31) + "2"])++ // Two conflicts: only one automatic resend, then Retry uses a fresh key.+ let twice = ReportServer([409, 409, 201])+ let client = ContentReportClient(baseURL: base, transport: twice, makeKey: { sequence.make() })+ let body = try #require(ContentReportBody(subject: speak, draft: draft, appVersion: "1"))+ let (outcome, key) = await client.submit(body, key: "first")+ #expect(outcome == .failed)+ #expect(await twice.requests.count == 2)+ #expect(await client.submit(body, key: key).0 == .sent)+ let sent = await twice.requests.compactMap { $0.value(forHTTPHeaderField: "Idempotency-Key") }+ #expect(sent[0] == "first" && sent[1] != sent[0] && sent[2] == key && sent[2] != sent[1])+}++@Test func contentReportRateLimitAndInvalidKeepTheDraft() async throws {+ let server = ReportServer([429, 400])+ let reports = await ContentReports(client: ContentReportClient(baseURL: base, transport: server), appVersion: "0.5.7")+ var draft = await reports.open(speak); draft.reason = .sexual+ await reports.update(draft, for: speak)+ #expect(await reports.send(speak) == .rateLimited)+ #expect(await reports.phase(for: speak) == .rateLimited)+ #expect(await reports.draft(for: speak) == draft)+ #expect(await reports.send(speak) == .invalid)+ #expect(await reports.phase(for: speak) == .invalid)+ #expect(await server.requests.count == 2, "400 is never retried automatically")+ #expect(ContentReportOutcome.rateLimited.messageKey == "mobile.report.rate_limited")+ #expect(ContentReportOutcome.invalid.messageKey == "mobile.report.invalid")+ #expect(ContentReportOutcome.failed.messageKey == "mobile.report.failed")+}++@Test func contentReportDraftsArePerResult() async {+ let reports = await ContentReports(client: ContentReportClient(baseURL: base, transport: ReportServer([])), appVersion: "0.5.7")+ let other = ContentReportSubject.phone(.speak, id: "other", repo: "r", revision: nil)+ var draft = await reports.open(speak); draft.reason = .hateful+ await reports.update(draft, for: speak)+ #expect(await reports.open(other).reason == nil)+ #expect(await reports.open(other).idempotencyKey != draft.idempotencyKey)+ // Edits never replace the key the store holds.+ var forged = draft; forged.idempotencyKey = "x"+ await reports.update(forged, for: speak)+ #expect(await reports.draft(for: speak)?.idempotencyKey == draft.idempotencyKey)+}++@Test func contentReportBaseURLAndAppVersionPerBuild() {+ #expect(ContentReportClient.baseURL(debug: true).absoluteString == "https://dev-appapi.voicestudio.sh")+ #expect(ContentReportClient.baseURL(debug: false).absoluteString == "https://appapi.voicestudio.sh")+ #expect(ContentReportClient.appVersion(info: ["VoiceStudioAppVersion": "0.5.7-beta.2", "CFBundleShortVersionString": "0.5.7"]) == "0.5.7-beta.2")+ #expect(ContentReportClient.appVersion(info: ["CFBundleShortVersionString": "0.5.7"]) == "0.5.7")+ #expect(ContentReportClient.appVersion(info: nil) == "unknown")+ #expect(ContentReportClient.appVersion(info: ["VoiceStudioAppVersion": "1.0 (beta)"]) == "1.0beta")+}++@Test func phoneTakesAndVoicesRecordTheirModel() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: root) }+ let store = try PhoneGenerationStore(root: root)+ // A take saved before the model was recorded still loads and reports `unknown`.+ let legacy = #"{"id":"6F9619FF-8B86-D011-B42D-00CF4FC964FF","text":"Old","createdAt":0}"#+ try data(legacy).write(to: root.appendingPathComponent("6F9619FF-8B86-D011-B42D-00CF4FC964FF.json"))+ let old = try #require(try await store.list().first)+ #expect(old.modelRepo == nil)+ #expect(ContentReportSubject.phone(.speak, id: old.id.uuidString, repo: old.modelRepo, revision: old.modelRevision).modelID == "unknown")+ let voice = try JSONDecoder().decode(PhoneVoice.self, from: data(#"{"id":"6F9619FF-8B86-D011-B42D-00CF4FC964FF","name":"V","transcript":"t","createdAt":0,"consentAt":0,"sampleRate":24000}"#))+ #expect(voice.modelRepo == nil)+}diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swiftindex ec91795cc..3f87777ae 100644--- a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/ContractTests.swift@@ -69,7 +69,8 @@ func catalogs() throws -> [String: Data] {"mobile.local.category.": ["commercial-ok", "conditional", "non-commercial", "unidentified"],"mobile.local.right_": ["commercial", "outputs", "redistribution", "voice", "unknown", "restricted"],"mobile.settings.mode_": ThemeMode.allCases.map(\.rawValue),- "mobile.ios.dub_stages.": ["preparing", "transcribing", "translating", "rendering", "done", "failed", "cancelled"]+ "mobile.ios.dub_stages.": ["preparing", "transcribing", "translating", "rendering", "done", "failed", "cancelled"],+ "mobile.report.reasons.": ContentReportReason.allCases.map(\.rawValue)]for case let file as URL in paths where file.pathExtension == "swift" && !file.path.contains("/.build/") && !file.path.contains("/.cache/") && !file.path.contains("/Tests/") && !file.path.contains("UITests/") {let source = try String(contentsOf: file, encoding: .utf8)diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/FixRegressionTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/FixRegressionTests.swiftindex 359f96c3a..4c3e4beb5 100644--- a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/FixRegressionTests.swift+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/FixRegressionTests.swift@@ -178,6 +178,9 @@ func playbackUsesMinutesAndSeconds(_ sample: (Double, String)) { #expect(Playbaclet info = try #require(PropertyListSerialization.propertyList(from: Data(contentsOf: output.appendingPathComponent("Info.plist")), format: nil) as? [String: Any])// App Store Connect takes only X.Y.Z, so a beta bundles as its release triple.#expect(info["CFBundleShortVersionString"] as? String == rootVersion.split(separator: "-").first.map(String.init))+ // Content reports send the full root version, beta suffix included.+ #expect(info[ContentReportClient.appVersionInfoKey] as? String == rootVersion)+ #expect(ContentReportClient.appVersion(info: info) == rootVersion)for locale in L10n.languages {let strings = try #require(PropertyListSerialization.propertyList(from: Data(contentsOf: output.appendingPathComponent(locale + ".lproj/InfoPlist.strings")), format: nil) as? [String: String])#expect(strings["NSMicrophoneUsageDescription"]?.isEmpty == false)diff --git a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/PhoneWorkflowTests.swift b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/PhoneWorkflowTests.swiftindex 86e7facd2..46dde8c5f 100644--- a/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/PhoneWorkflowTests.swift+++ b/mobile/ios/VoiceStudioKit/Tests/VoiceStudioKitTests/PhoneWorkflowTests.swift@@ -108,6 +108,7 @@ private actor FixtureEngine: LocalEngine {#expect(await engine.transcriptions == 0)let voice = try await store.create(name: " Voice ",source: root,consent: true,asr: asr,engine: engine,decoder: FixtureDecoder())#expect(voice.name == "Voice"); #expect(voice.transcript == "A reference voice"); #expect(voice.sampleRate == 24000)+ #expect(voice.modelRepo == asr.repo); #expect(voice.modelRevision == asr.revision)#expect(try await store.reference(voice).samples.count == 24000)#expect(try Data(contentsOf: await store.preview(voice)).range(of: Data("synthetic".utf8)) == nil)let restored = try PhoneVoiceStore(root: root)@@ -130,10 +131,13 @@ private actor FixtureEngine: LocalEngine {@Test func phoneRecentAudioPersistsMarkedAndCanBeRemoved() async throws {let root = try fixtureRoot(); defer { try? FileManager.default.removeItem(at: root) }let store = try PhoneGenerationStore(root: root)- let item = try await store.save(text: "Hello",audio: LocalAudio(samples: [0.2,-0.2],sampleRate: 24000))+ let tts = try fixtureModel(.tts)+ let item = try await store.save(text: "Hello",audio: LocalAudio(samples: [0.2,-0.2],sampleRate: 24000),model: tts)#expect(try Data(contentsOf: await store.file(item)).range(of: Data("VoiceStudio synthetic audio".utf8)) != nil)let restored = try PhoneGenerationStore(root: root)#expect(try await restored.list().first?.text == "Hello")+ #expect(try await restored.list().first?.modelRepo == tts.repo)+ #expect(try await restored.list().first?.modelRevision == tts.revision)try await restored.delete(item); #expect(try await restored.list().isEmpty)}@Test func phoneAVExtractionResamplesAndRejectsLongReference() async throws {diff --git a/mobile/ios/scripts/prepare_resources.py b/mobile/ios/scripts/prepare_resources.pyindex 3b00da0c0..9d9cc587d 100644--- a/mobile/ios/scripts/prepare_resources.py+++ b/mobile/ios/scripts/prepare_resources.py@@ -123,6 +123,8 @@ def prepare(output, info):version = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))["version"]data = plistlib.loads((IOS / "VoiceStudio/Info.plist").read_bytes())data["CFBundleShortVersionString"] = marketing_version(version)+ # The full root version (X.Y.Z or X.Y.Z-beta.N), which content reports send as app_version.+ data["VoiceStudioAppVersion"] = versiondata["CFBundleVersion"] = build_number(os.environ.get("VOICESTUDIO_IOS_BUILD_NUMBER", "1"))data["CFBundleLocalizations"] = sorted(path.stem for path in source.glob("*.json"))for field, keys in permissions.items():diff --git a/mobile/ios/scripts/test_resources.py b/mobile/ios/scripts/test_resources.pyindex aa54cf98d..732032f79 100644--- a/mobile/ios/scripts/test_resources.py+++ b/mobile/ios/scripts/test_resources.py@@ -54,6 +54,12 @@ class BrandResources(unittest.TestCase):for index, channel in enumerate(["red", "green", "blue", "alpha"]):self.assertAlmostEqual(float(actual[channel]), int(expected[2 * index:2 * index + 2], 16) / 255)+ def test_info_plist_carries_full_root_version_for_content_reports(self):+ info = plistlib.loads((self.root / "Info.plist").read_bytes())+ version = json.loads((resources.ROOT / "package.json").read_text())["version"]+ self.assertEqual(info["VoiceStudioAppVersion"], version)+ self.assertEqual(info["CFBundleShortVersionString"], resources.marketing_version(version))+def test_catalogue_bundles_names_and_phone_consent_note(self):catalogue = json.loads((self.root / "bundle/Catalogs/models.json").read_text())self.assertTrue(all(model["name"].strip() for model in catalogue["models"]))diff --git a/store/google-play.md b/store/google-play.mdindex 5a178768e..e57e158c1 100644--- a/store/google-play.md+++ b/store/google-play.md@@ -30,9 +30,10 @@ every permission in the Android manifest has a declaration here.## Before production-- **AI-generated content:** Play requires an in-app way to report or flag- offensive generated content. The app does not have one yet; it ships on both- phone apps or neither (`mobile/contract/SPEC.md`).+- **Report endpoint live:** the in-app Report action posts to+ `appapi.voicestudio.sh/v1/content-reports`; it must be deployed before the+ first Play review, or reviewers' test reports fail.- **Privacy policy:** `https://voicestudio.sh/privacy` should describe the phone- apps (what leaves the phone: model downloads and requests to the paired computer).+ apps: what leaves the phone (model downloads, reports the user sends and+ requests to the paired computer) and that reports are kept 180 days.- **Screenshots:** capture from a release build on a phone or emulator.diff --git a/store/google-play/listing.json b/store/google-play/listing.jsonindex 60932ff67..166dd7759 100644--- a/store/google-play/listing.json+++ b/store/google-play/listing.json@@ -24,7 +24,7 @@"If you run VoiceStudio on your computer, scan its QR code to pair. Heavy jobs can then run on your computer's engines, chosen per task. The phone talks only to your own computer; there is no cloud relay.","","PRIVACY",- "On-device tasks send nothing anywhere. The only network requests are model downloads you start and, if you pair, requests to your own computer. Analytics are off unless you say yes, and this version sends none.",+ "On-device tasks send nothing anywhere. The only network requests are model downloads you start, reports you choose to send about a result and, if you pair, requests to your own computer. Analytics are off unless you say yes, and this version sends none.","","OPEN SOURCE","VoiceStudio is free and open source (AGPL-3.0): https://github.com/debpalash/VoiceStudio",@@ -45,9 +45,21 @@"phoneScreenshots": "Capture 2 to 8 from a release build (Home, Speak, Voices, Dub, Dictate, Models); 9:16, 1080x1920 or larger"},"dataSafety": {- "collectsData": false,+ "collectsData": true,"sharesData": false,- "rationale": "Models run on the device. Model downloads are user-started requests to Hugging Face, and pairing sends requests only to the user's own computer; neither reaches the developer. The first-run analytics choice is stored on the device and this version transmits no analytics.",+ "collected": [+ {+ "type": "App activity → Other user-generated content",+ "what": "A content report the user chooses to send: reason, optional note, optionally the text they entered, app version and the model that made the result",+ "optional": true,+ "purposes": ["Fraud prevention, security, and compliance"],+ "ephemeral": false,+ "linkedToIdentity": false+ }+ ],+ "encryptedInTransit": true,+ "deletionRequests": "Not offered: reports carry no account, device or install identifier to match a request to, and the server deletes them after 180 days.",+ "rationale": "Models run on the device. Model downloads are user-started requests to Hugging Face, and pairing sends requests only to the user's own computer; neither reaches the developer. Reports reach VoiceStudio only when the user taps Send, and the server stores no IP address with them. The first-run analytics choice is stored on the device and this version transmits no analytics.","reviewWhen": "Re-answer before shipping phone analytics or any new network destination (mobile/contract/SPEC.md → Privacy)."},"permissions": {@@ -80,7 +92,7 @@"generatesContent": true,"kinds": ["Synthetic speech", "Voice clones", "Translated dubbing"],"consentBeforeCloning": true,- "inAppReporting": "Required by Play's AI-generated content policy; not in the app yet (see store/google-play.md)."+ "inAppReporting": "Report action on every generated result sends a report inside the app (mobile/contract/SPEC.md → Reporting generated content)."},"newsApp": false,"healthApp": false,diff --git a/tests/test_google_play_listing.py b/tests/test_google_play_listing.pyindex e3975640f..b5618c57a 100644--- a/tests/test_google_play_listing.py+++ b/tests/test_google_play_listing.py@@ -56,3 +56,13 @@ def test_store_languages_match_the_phone_models():assert languages("asr-stream") == {"en"}, "phone dictation gained languages; update the listing"assert "Dictation on the phone is English" in descriptionassert languages("tts") == {"en", "zh"} and "Preset voices are English and Chinese" in description+++def test_data_safety_declares_the_report_the_app_sends():+ # The Report sheet sends user-written text to VoiceStudio (mobile/contract/SPEC.md).+ spec = (ROOT / "mobile/contract/SPEC.md").read_text()+ assert "## Reporting generated content" in spec+ safety = LISTING["dataSafety"]+ assert safety["collectsData"] and not safety["sharesData"] and safety["encryptedInTransit"]+ assert [item["optional"] for item in safety["collected"]] == [True]+ assert "reports you choose to send" in "\n".join(LISTING["listing"]["fullDescription"])