From be382a9a3a5c776e7e61ab2ec4f197f0e56f3dc8 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sat, 28 Nov 2026 14:18:17 -0500
Subject: [PATCH 1/7] feat(ios): My scenes on iPad, the scenes store in Swift
and scenes in Recently Deleted
---
ios/Engine/ScenesRoutes.swift | 162 ++++++++++++++++++++++++++++++++++
ios/Engine/TrashRoutes.swift | 5 +-
2 files changed, 166 insertions(+), 1 deletion(-)
create mode 100644 ios/Engine/ScenesRoutes.swift
diff --git a/ios/Engine/ScenesRoutes.swift b/ios/Engine/ScenesRoutes.swift
new file mode 100644
index 0000000..3b1131b
--- /dev/null
+++ b/ios/Engine/ScenesRoutes.swift
@@ -0,0 +1,162 @@
+// ScenesRoutes.swift
+// /api/scenes: the person's own scenery, one .fmo each in Documents/Scenes, beside Characters.
+// A port of backend/app/routers/scenes.py and services/scenes.py, which mirror the Characters library: the same entry
+// shape, the zip check, the part file and atomic replace, rename with {to}, and delete to Recently Deleted (restored to Scenes).
+
+import Foundation
+
+final class ScenesStore {
+ static let shared = ScenesStore()
+
+ let lock = NSRecursiveLock()
+
+ static let ext = EngineConfig.projectExt
+ static let kind = "scene"
+
+ private init() {}
+
+ var root: URL { return EngineConfig.folder("Scenes") }
+
+ func cleanName(_ name: String) throws -> String {
+ var stem = name
+ if name.lowercased().hasSuffix(ScenesStore.ext) { stem = String(name.dropLast(ScenesStore.ext.count)) }
+ stem = EngineText.stripDots(EngineText.strip(EngineText.replaceBad(stem, with: "-")))
+ if stem.isEmpty || EngineText.length(stem) > 180 {
+ throw EngineError(400, "That scene name cannot be used.")
+ }
+ return stem
+ }
+
+ func stem(_ url: URL) -> String {
+ return String(url.lastPathComponent.dropLast(ScenesStore.ext.count))
+ }
+
+ func files() -> [URL] {
+ let folder = root
+ return EngineFS.names(folder)
+ .filter { $0.hasSuffix(ScenesStore.ext) && !$0.hasPrefix(".") }
+ .sorted()
+ .map { folder.appendingPathComponent($0) }
+ .filter { EngineFS.isFile($0) }
+ }
+
+ func find(_ stem: String) -> URL? {
+ let p = root.appendingPathComponent(stem + ScenesStore.ext)
+ return EngineFS.isFile(p) ? p : nil
+ }
+
+ func path(_ name: String) throws -> URL {
+ let s = try cleanName(name)
+ return root.appendingPathComponent(s + ScenesStore.ext)
+ }
+
+ func entry(_ url: URL) -> [String: Any] {
+ let st = EngineFS.stat(url)
+ return [
+ "name": stem(url),
+ "file": url.lastPathComponent,
+ "path": url.path,
+ "size": st?.size ?? 0,
+ "modified": st?.modified ?? 0,
+ "created": st?.created ?? 0,
+ ]
+ }
+}
+
+final class ScenesRoutes: APIRoutes {
+ let prefix = "/scenes"
+ private let table = RouteTable()
+ private let store = ScenesStore.shared
+
+ init() {
+ table.add("GET", "/scenes") { [unowned self] c in try self.list(c) }
+ table.add("GET", "/scenes/{name}") { [unowned self] c in try self.read(c) }
+ table.add("GET", "/scenes/{name}/poster") { [unowned self] c in try self.poster(c) }
+ table.add("PUT", "/scenes/{name}") { [unowned self] c in try self.write(c) }
+ table.add("POST", "/scenes/{name}/rename") { [unowned self] c in try self.rename(c) }
+ table.add("DELETE", "/scenes/{name}") { [unowned self] c in try self.delete(c) }
+ }
+
+ func handle(_ request: APIRequest) async -> APIResponse? {
+ if !table.handles(request) { return nil }
+ return await EngineWork.run { return self.table.dispatch(request) }
+ }
+
+ private func list(_ c: RouteContext) throws -> APIResponse {
+ var items = store.files().map { store.entry($0) }
+ items.sort { (($0["modified"] as? Double) ?? 0) > (($1["modified"] as? Double) ?? 0) }
+ return APIResponse.json(["folder": store.root.path, "items": items])
+ }
+
+ private func existing(_ c: RouteContext) throws -> URL {
+ let path = try store.path(c.param("name"))
+ if !EngineFS.isFile(path) { throw EngineError(404, "No scene by that name.") }
+ return path
+ }
+
+ private func read(_ c: RouteContext) throws -> APIResponse {
+ let path = try existing(c)
+ guard let data = try? Data(contentsOf: path, options: .mappedIfSafe) else {
+ throw EngineError(404, "No scene by that name.")
+ }
+ return APIResponse.data(data, contentType: "application/octet-stream")
+ }
+
+ /// poster.png from inside the file; none is an empty 204, as the library answers.
+ private func poster(_ c: RouteContext) throws -> APIResponse {
+ let path = try existing(c)
+ guard let zip = try? ZipReader(url: path), let e = zip.entry(named: "poster.png"),
+ let data = try? zip.read(e, limit: 64 * 1024 * 1024) else {
+ return EngineHTTP.noContent(contentType: "image/png")
+ }
+ var r = APIResponse.data(data, contentType: "image/png")
+ let v = c.query("v")
+ r.headers["Cache-Control"] = (v != nil && !(v ?? "").isEmpty) ? "private, max-age=300" : "no-store"
+ return r
+ }
+
+ private func write(_ c: RouteContext) throws -> APIResponse {
+ let path = try store.path(c.param("name"))
+ let body = try c.limited(EngineConfig.maxCharacterBytes, "The scene is too large to save.")
+ if body.count < 4 || Array(body.prefix(4)) != [0x50, 0x4B, 0x03, 0x04] {
+ throw EngineError(400, "That is not a FormMorpheus scene.")
+ }
+ let tmp = EngineFS.tempBeside(path)
+ defer { EngineFS.remove(tmp) }
+ try EngineFS.writeFile(body, to: tmp)
+ store.lock.lock()
+ defer { store.lock.unlock() }
+ try EngineFS.replace(tmp, path)
+ return APIResponse.json(store.entry(path))
+ }
+
+ private func rename(_ c: RouteContext) throws -> APIResponse {
+ let src = try existing(c)
+ let to = try c.json().string("to")
+ let stem = try store.cleanName(to)
+ let dst = store.root.appendingPathComponent(stem + ScenesStore.ext)
+ store.lock.lock()
+ defer { store.lock.unlock() }
+ if let other = store.find(stem), !(EngineFS.exists(other) && EngineFS.exists(src) && EngineFS.sameFile(other, src)) {
+ throw EngineError(409, "A scene with that name already exists.")
+ }
+ try EngineFS.replace(src, dst)
+ return APIResponse.json(store.entry(dst))
+ }
+
+ private func delete(_ c: RouteContext) throws -> APIResponse {
+ let src = try existing(c)
+ let stamp = EngineText.stamp()
+ store.lock.lock()
+ defer { store.lock.unlock() }
+ var dst = EngineConfig.trashDir.appendingPathComponent("\(store.stem(src)) \(stamp)\(ScenesStore.ext)")
+ var n = 2
+ while EngineFS.exists(dst) {
+ dst = EngineConfig.trashDir.appendingPathComponent("\(store.stem(src)) \(stamp) \(n)\(ScenesStore.ext)")
+ n += 1
+ }
+ try EngineFS.safeMove(src, dst)
+ TrashStore.shared.record(dst, original: src.lastPathComponent, kind: ScenesStore.kind)
+ return APIResponse.json(["deleted": store.stem(src), "kept": dst.path])
+ }
+}
diff --git a/ios/Engine/TrashRoutes.swift b/ios/Engine/TrashRoutes.swift
index 4685e2d..8f50bf0 100644
--- a/ios/Engine/TrashRoutes.swift
+++ b/ios/Engine/TrashRoutes.swift
@@ -77,7 +77,7 @@ final class TrashStore {
deleted = EngineJSON.number(rec["deleted"], fallback: deleted)
}
var name = original
- if (kind == "movie" || kind == CharacterStore.kind) && original.lowercased().hasSuffix(EngineConfig.projectExt) {
+ if (kind == "movie" || kind == CharacterStore.kind || kind == ScenesStore.kind) && original.lowercased().hasSuffix(EngineConfig.projectExt) {
name = String(original.dropLast(EngineConfig.projectExt.count))
}
let age = Date().timeIntervalSince1970 - deleted
@@ -167,6 +167,9 @@ final class TrashRoutes: APIRoutes {
} else if meta.kind == CharacterStore.kind {
let stem = parts.ext.lowercased() == EngineConfig.projectExt ? parts.stem : meta.original
dst = EngineFS.freePath(EngineConfig.charactersDir, stem: stem, ext: EngineConfig.projectExt)
+ } else if meta.kind == ScenesStore.kind {
+ let stem = parts.ext.lowercased() == EngineConfig.projectExt ? parts.stem : meta.original
+ dst = EngineFS.freePath(ScenesStore.shared.root, stem: stem, ext: EngineConfig.projectExt)
} else {
dst = EngineFS.freePath(EngineConfig.exportsDir, stem: parts.stem, ext: parts.ext)
}
From bd38b769990b9dba7153807f18126a14b16dc945 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sat, 28 Nov 2026 14:18:17 -0500
Subject: [PATCH 2/7] feat(ios): AI Voice on iPad with the key in the Keychain
and a speech server on the network, and listening with on-device speech
recognition
---
ios/App/Info.plist | 9 +
ios/App/ar.lproj/InfoPlist.strings | 2 +
ios/App/cs.lproj/InfoPlist.strings | 2 +
ios/App/da.lproj/InfoPlist.strings | 2 +
ios/App/de.lproj/InfoPlist.strings | 2 +
ios/App/el.lproj/InfoPlist.strings | 2 +
ios/App/en.lproj/InfoPlist.strings | 2 +
ios/App/es-MX.lproj/InfoPlist.strings | 2 +
ios/App/es.lproj/InfoPlist.strings | 2 +
ios/App/fi.lproj/InfoPlist.strings | 2 +
ios/App/fr-CA.lproj/InfoPlist.strings | 2 +
ios/App/fr.lproj/InfoPlist.strings | 2 +
ios/App/hi.lproj/InfoPlist.strings | 2 +
ios/App/hu.lproj/InfoPlist.strings | 2 +
ios/App/id.lproj/InfoPlist.strings | 2 +
ios/App/it.lproj/InfoPlist.strings | 2 +
ios/App/ja.lproj/InfoPlist.strings | 2 +
ios/App/ko.lproj/InfoPlist.strings | 2 +
ios/App/nb.lproj/InfoPlist.strings | 2 +
ios/App/nl.lproj/InfoPlist.strings | 2 +
ios/App/pl.lproj/InfoPlist.strings | 2 +
ios/App/pt-BR.lproj/InfoPlist.strings | 2 +
ios/App/ru.lproj/InfoPlist.strings | 2 +
ios/App/sr-Latn.lproj/InfoPlist.strings | 2 +
ios/App/sv.lproj/InfoPlist.strings | 2 +
ios/App/th.lproj/InfoPlist.strings | 2 +
ios/App/tr.lproj/InfoPlist.strings | 2 +
ios/App/uk.lproj/InfoPlist.strings | 2 +
ios/App/vi.lproj/InfoPlist.strings | 2 +
ios/App/zh-Hans.lproj/InfoPlist.strings | 2 +
ios/App/zh-Hant.lproj/InfoPlist.strings | 2 +
ios/Engine/EngineRouter.swift | 6 +-
ios/Engine/VoiceKeychain.swift | 49 +++
ios/Engine/VoiceListen.swift | 503 ++++++++++++++++++++++++
ios/Engine/VoiceRemote.swift | 403 +++++++++++++++++++
ios/Engine/VoiceRoutes.swift | 225 +++++++++++
setup/api_contract_check | 5 +-
37 files changed, 1256 insertions(+), 4 deletions(-)
create mode 100644 ios/Engine/VoiceKeychain.swift
create mode 100644 ios/Engine/VoiceListen.swift
create mode 100644 ios/Engine/VoiceRemote.swift
create mode 100644 ios/Engine/VoiceRoutes.swift
diff --git a/ios/App/Info.plist b/ios/App/Info.plist
index 22b7df2..f7a8497 100644
--- a/ios/App/Info.plist
+++ b/ios/App/Info.plist
@@ -155,6 +155,15 @@
FormMorpheus uses the microphone only when you record narration or sound into a movie.NSPhotoLibraryAddUsageDescriptionFormMorpheus saves the movies and images you export to your photo library when you choose to.
+ NSSpeechRecognitionUsageDescription
+ FormMorpheus uses speech recognition on this iPad only when you ask it to write subtitles from a sound. The sound stays on this iPad.
+ NSLocalNetworkUsageDescription
+ FormMorpheus uses your local network only to reach the speech server you name for AI Voice.
+ NSAppTransportSecurity
+
+ NSAllowsLocalNetworking
+
+ UIApplicationSceneManifestUIApplicationSupportsMultipleScenes
diff --git a/ios/App/ar.lproj/InfoPlist.strings b/ios/App/ar.lproj/InfoPlist.strings
index a407748..5430718 100644
--- a/ios/App/ar.lproj/InfoPlist.strings
+++ b/ios/App/ar.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "يستخدم FormMorpheus الميكروفون فقط عندما تسجّل تعليقًا صوتيًا أو صوتًا داخل فيلم.";
"NSPhotoLibraryAddUsageDescription" = "يحفظ FormMorpheus الأفلام والصور التي تصدّرها في مكتبة الصور لديك عندما تختار ذلك.";
+"NSSpeechRecognitionUsageDescription" = "يستخدم FormMorpheus التعرّف على الكلام على هذا الـ iPad فقط عندما تطلب منه كتابة ترجمة من صوت. يبقى الصوت على هذا الـ iPad.";
+"NSLocalNetworkUsageDescription" = "يستخدم FormMorpheus شبكتك المحلية فقط للوصول إلى خادم الكلام الذي تحدده للصوت بالذكاء الاصطناعي.";
diff --git a/ios/App/cs.lproj/InfoPlist.strings b/ios/App/cs.lproj/InfoPlist.strings
index e9cb57e..647d18f 100644
--- a/ios/App/cs.lproj/InfoPlist.strings
+++ b/ios/App/cs.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus používá mikrofon pouze tehdy, když nahráváte vyprávění nebo zvuk do filmu.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus ukládá filmy a obrázky, které exportujete, do vaší knihovny fotek, když to zvolíte.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus používá rozpoznávání řeči na tomto iPadu pouze tehdy, když jej požádáte o vytvoření titulků ze zvuku. Zvuk zůstává na tomto iPadu.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus používá vaši místní síť pouze k připojení k řečovému serveru, který zadáte pro Hlas AI.";
diff --git a/ios/App/da.lproj/InfoPlist.strings b/ios/App/da.lproj/InfoPlist.strings
index 31e2333..de906e2 100644
--- a/ios/App/da.lproj/InfoPlist.strings
+++ b/ios/App/da.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus bruger kun mikrofonen, når du optager fortælling eller lyd til en film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus gemmer de film og billeder, du eksporterer, i dit fotobibliotek, når du vælger det.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus bruger kun talegenkendelse på denne iPad, når du beder den skrive undertekster ud fra en lyd. Lyden bliver på denne iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus bruger kun dit lokale netværk til at nå den taleserver, du angiver til AI-stemme.";
diff --git a/ios/App/de.lproj/InfoPlist.strings b/ios/App/de.lproj/InfoPlist.strings
index dc386eb..8ff6cbd 100644
--- a/ios/App/de.lproj/InfoPlist.strings
+++ b/ios/App/de.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus verwendet das Mikrofon nur, wenn du eine Sprecherspur oder einen Ton in einen Film aufnimmst.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus sichert die Filme und Bilder, die du exportierst, in deiner Fotomediathek, wenn du das auswählst.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus verwendet die Spracherkennung auf diesem iPad nur, wenn du Untertitel aus einem Ton schreiben lässt. Der Ton bleibt auf diesem iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus verwendet dein lokales Netzwerk nur, um den Sprachserver zu erreichen, den du für KI-Stimme angibst.";
diff --git a/ios/App/el.lproj/InfoPlist.strings b/ios/App/el.lproj/InfoPlist.strings
index 551da10..d99448f 100644
--- a/ios/App/el.lproj/InfoPlist.strings
+++ b/ios/App/el.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "Το FormMorpheus χρησιμοποιεί το μικρόφωνο μόνο όταν ηχογραφείτε αφήγηση ή ήχο σε μια ταινία.";
"NSPhotoLibraryAddUsageDescription" = "Το FormMorpheus αποθηκεύει στη βιβλιοθήκη φωτογραφιών σας τις ταινίες και τις εικόνες που εξάγετε, όταν το επιλέξετε.";
+"NSSpeechRecognitionUsageDescription" = "Το FormMorpheus χρησιμοποιεί την αναγνώριση ομιλίας σε αυτό το iPad μόνο όταν του ζητάτε να γράψει υπότιτλους από έναν ήχο. Ο ήχος παραμένει σε αυτό το iPad.";
+"NSLocalNetworkUsageDescription" = "Το FormMorpheus χρησιμοποιεί το τοπικό σας δίκτυο μόνο για να φτάσει στον διακομιστή ομιλίας που ορίζετε για τη Φωνή AI.";
diff --git a/ios/App/en.lproj/InfoPlist.strings b/ios/App/en.lproj/InfoPlist.strings
index f6db630..3ebc2e9 100644
--- a/ios/App/en.lproj/InfoPlist.strings
+++ b/ios/App/en.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus uses the microphone only when you record narration or sound into a movie.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus saves the movies and images you export to your photo library when you choose to.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus uses speech recognition on this iPad only when you ask it to write subtitles from a sound. The sound stays on this iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus uses your local network only to reach the speech server you name for AI Voice.";
diff --git a/ios/App/es-MX.lproj/InfoPlist.strings b/ios/App/es-MX.lproj/InfoPlist.strings
index 3971d93..f23a64d 100644
--- a/ios/App/es-MX.lproj/InfoPlist.strings
+++ b/ios/App/es-MX.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus usa el micrófono solo cuando grabas narración o sonido en una película.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus guarda en tu biblioteca de fotos las películas e imágenes que exportas cuando tú lo decides.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus usa el reconocimiento de voz en este iPad solo cuando le pides que escriba subtítulos a partir de un sonido. El sonido se queda en este iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus usa tu red local solo para conectarse con el servidor de voz que indicas para Voz de IA.";
diff --git a/ios/App/es.lproj/InfoPlist.strings b/ios/App/es.lproj/InfoPlist.strings
index 354c764..af0ae32 100644
--- a/ios/App/es.lproj/InfoPlist.strings
+++ b/ios/App/es.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus usa el micrófono solo cuando grabas narración o sonido en una película.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus guarda en tu fototeca las películas e imágenes que exportas cuando así lo eliges.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus usa el reconocimiento de voz en este iPad solo cuando le pides que escriba subtítulos a partir de un sonido. El sonido no sale de este iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus usa tu red local solo para llegar al servidor de voz que indiques para Voz de IA.";
diff --git a/ios/App/fi.lproj/InfoPlist.strings b/ios/App/fi.lproj/InfoPlist.strings
index d7c8ca0..02f577e 100644
--- a/ios/App/fi.lproj/InfoPlist.strings
+++ b/ios/App/fi.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus käyttää mikrofonia vain, kun äänität selostusta tai ääntä elokuvaan.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus tallentaa viemäsi elokuvat ja kuvat kuvakirjastoosi, kun valitset sen.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus käyttää tämän iPadin puheentunnistusta vain, kun pyydät sitä kirjoittamaan tekstitykset äänestä. Ääni pysyy tässä iPadissa.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus käyttää lähiverkkoasi vain tavoittaakseen puhepalvelimen, jonka annat Tekoälyäänelle.";
diff --git a/ios/App/fr-CA.lproj/InfoPlist.strings b/ios/App/fr-CA.lproj/InfoPlist.strings
index 5eb950f..ceef1b4 100644
--- a/ios/App/fr-CA.lproj/InfoPlist.strings
+++ b/ios/App/fr-CA.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus utilise le microphone uniquement lorsque vous enregistrez une narration ou du son dans un film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus enregistre dans votre photothèque les films et les images que vous exportez, lorsque vous le choisissez.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus utilise la reconnaissance vocale sur cet iPad uniquement lorsque vous lui demandez d'écrire des sous-titres à partir d'un son. Le son reste sur cet iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus utilise votre réseau local uniquement pour joindre le serveur vocal que vous indiquez pour Voix IA.";
diff --git a/ios/App/fr.lproj/InfoPlist.strings b/ios/App/fr.lproj/InfoPlist.strings
index 80d3e24..95b6973 100644
--- a/ios/App/fr.lproj/InfoPlist.strings
+++ b/ios/App/fr.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus utilise le micro uniquement lorsque vous enregistrez une narration ou un son dans un film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus enregistre dans votre photothèque les films et les images que vous exportez, lorsque vous le choisissez.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus utilise la reconnaissance vocale sur cet iPad uniquement lorsque vous lui demandez d'écrire des sous-titres à partir d'un son. Le son reste sur cet iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus utilise votre réseau local uniquement pour joindre le serveur vocal que vous indiquez pour Voix IA.";
diff --git a/ios/App/hi.lproj/InfoPlist.strings b/ios/App/hi.lproj/InfoPlist.strings
index 1fa84b4..6f55345 100644
--- a/ios/App/hi.lproj/InfoPlist.strings
+++ b/ios/App/hi.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus माइक्रोफ़ोन का उपयोग केवल तब करता है जब आप किसी फ़िल्म में नैरेशन या ध्वनि रिकॉर्ड करते हैं।";
"NSPhotoLibraryAddUsageDescription" = "जब आप चुनते हैं, तब FormMorpheus आपकी एक्सपोर्ट की हुई फ़िल्में और छवियाँ आपकी फ़ोटो लाइब्रेरी में सहेजता है।";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus इस iPad पर वाक् पहचान का उपयोग केवल तब करता है जब आप उससे किसी ध्वनि से सबटाइटल लिखने को कहते हैं। ध्वनि इसी iPad पर रहती है।";
+"NSLocalNetworkUsageDescription" = "FormMorpheus आपके लोकल नेटवर्क का उपयोग केवल उस स्पीच सर्वर तक पहुँचने के लिए करता है जिसे आप AI आवाज़ के लिए बताते हैं।";
diff --git a/ios/App/hu.lproj/InfoPlist.strings b/ios/App/hu.lproj/InfoPlist.strings
index 7153fcc..ad3d5df 100644
--- a/ios/App/hu.lproj/InfoPlist.strings
+++ b/ios/App/hu.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "A FormMorpheus csak akkor használja a mikrofont, amikor narrációt vagy hangot rögzít egy filmbe.";
"NSPhotoLibraryAddUsageDescription" = "A FormMorpheus az exportált filmeket és képeket a fotókönyvtárba menti, ha Ön ezt választja.";
+"NSSpeechRecognitionUsageDescription" = "A FormMorpheus csak akkor használja ezen az iPaden a beszédfelismerést, amikor arra kéri, hogy feliratot írjon egy hangból. A hang ezen az iPaden marad.";
+"NSLocalNetworkUsageDescription" = "A FormMorpheus csak arra használja a helyi hálózatot, hogy elérje a MI-hanghoz megadott beszédszervert.";
diff --git a/ios/App/id.lproj/InfoPlist.strings b/ios/App/id.lproj/InfoPlist.strings
index 3546326..69fbb25 100644
--- a/ios/App/id.lproj/InfoPlist.strings
+++ b/ios/App/id.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus hanya menggunakan mikrofon saat Anda merekam narasi atau suara ke dalam film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus menyimpan film dan gambar yang Anda ekspor ke pustaka foto Anda saat Anda memilihnya.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus hanya menggunakan pengenalan ucapan di iPad ini saat Anda memintanya menulis subjudul dari suara. Suara tetap berada di iPad ini.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus hanya menggunakan jaringan lokal Anda untuk menjangkau server ucapan yang Anda tentukan untuk Suara AI.";
diff --git a/ios/App/it.lproj/InfoPlist.strings b/ios/App/it.lproj/InfoPlist.strings
index 5afc42f..53b81aa 100644
--- a/ios/App/it.lproj/InfoPlist.strings
+++ b/ios/App/it.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus usa il microfono solo quando registri una narrazione o un suono in un film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus salva nella tua libreria foto i film e le immagini che esporti, quando lo scegli.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus usa il riconoscimento vocale su questo iPad solo quando gli chiedi di scrivere i sottotitoli da un suono. Il suono resta su questo iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus usa la tua rete locale solo per raggiungere il server vocale che indichi per Voce IA.";
diff --git a/ios/App/ja.lproj/InfoPlist.strings b/ios/App/ja.lproj/InfoPlist.strings
index 0d1b7b5..edf686f 100644
--- a/ios/App/ja.lproj/InfoPlist.strings
+++ b/ios/App/ja.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus は、ムービーにナレーションや音声を録音するときにのみマイクを使用します。";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus は、あなたが選択したときに、書き出したムービーと画像を写真ライブラリに保存します。";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus は、音声から字幕を書くよう指示したときにのみ、この iPad の音声認識を使用します。音声はこの iPad の外に出ません。";
+"NSLocalNetworkUsageDescription" = "FormMorpheus は、AI ボイス用に指定した音声サーバーに接続するためにのみ、ローカルネットワークを使用します。";
diff --git a/ios/App/ko.lproj/InfoPlist.strings b/ios/App/ko.lproj/InfoPlist.strings
index cdc9365..f251ad5 100644
--- a/ios/App/ko.lproj/InfoPlist.strings
+++ b/ios/App/ko.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus는 영화에 내레이션이나 소리를 녹음할 때만 마이크를 사용합니다.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus는 사용자가 선택할 때 내보낸 영화와 이미지를 사진 보관함에 저장합니다.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus는 소리에서 자막을 만들도록 요청할 때만 이 iPad의 음성 인식을 사용합니다. 소리는 이 iPad에 그대로 남습니다.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus는 AI 음성에 지정한 음성 서버에 연결할 때만 로컬 네트워크를 사용합니다.";
diff --git a/ios/App/nb.lproj/InfoPlist.strings b/ios/App/nb.lproj/InfoPlist.strings
index 7a609d2..109e133 100644
--- a/ios/App/nb.lproj/InfoPlist.strings
+++ b/ios/App/nb.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus bruker bare mikrofonen når du tar opp fortellerstemme eller lyd i en film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus lagrer filmene og bildene du eksporterer i bildebiblioteket ditt når du velger det.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus bruker bare talegjenkjenning på denne iPaden når du ber den skrive undertekster fra en lyd. Lyden blir på denne iPaden.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus bruker bare det lokale nettverket ditt for å nå taleserveren du oppgir for KI-stemme.";
diff --git a/ios/App/nl.lproj/InfoPlist.strings b/ios/App/nl.lproj/InfoPlist.strings
index 44d9682..ca0ca93 100644
--- a/ios/App/nl.lproj/InfoPlist.strings
+++ b/ios/App/nl.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus gebruikt de microfoon alleen wanneer je een voice-over of geluid in een film opneemt.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus bewaart de films en afbeeldingen die je exporteert in je fotobibliotheek wanneer je daarvoor kiest.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus gebruikt spraakherkenning op deze iPad alleen wanneer je vraagt om ondertitels uit een geluid te schrijven. Het geluid blijft op deze iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus gebruikt je lokale netwerk alleen om de spraakserver te bereiken die je voor AI-stem opgeeft.";
diff --git a/ios/App/pl.lproj/InfoPlist.strings b/ios/App/pl.lproj/InfoPlist.strings
index b3669f1..4d17408 100644
--- a/ios/App/pl.lproj/InfoPlist.strings
+++ b/ios/App/pl.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus używa mikrofonu tylko wtedy, gdy nagrywasz narrację lub dźwięk do filmu.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus zapisuje w Twojej fototece filmy i obrazy, które eksportujesz, gdy tak zdecydujesz.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus używa rozpoznawania mowy na tym iPadzie tylko wtedy, gdy poprosisz o napisanie napisów z dźwięku. Dźwięk pozostaje na tym iPadzie.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus używa Twojej sieci lokalnej tylko do połączenia z serwerem mowy, który podasz dla funkcji Głos AI.";
diff --git a/ios/App/pt-BR.lproj/InfoPlist.strings b/ios/App/pt-BR.lproj/InfoPlist.strings
index 2196b91..a2a3a13 100644
--- a/ios/App/pt-BR.lproj/InfoPlist.strings
+++ b/ios/App/pt-BR.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "O FormMorpheus usa o microfone somente quando você grava narração ou som em um filme.";
"NSPhotoLibraryAddUsageDescription" = "O FormMorpheus salva na sua biblioteca de fotos os filmes e as imagens que você exporta, quando você escolhe.";
+"NSSpeechRecognitionUsageDescription" = "O FormMorpheus usa o reconhecimento de fala neste iPad somente quando você pede que ele escreva legendas a partir de um som. O som fica neste iPad.";
+"NSLocalNetworkUsageDescription" = "O FormMorpheus usa sua rede local somente para acessar o servidor de fala que você indicar para Voz de IA.";
diff --git a/ios/App/ru.lproj/InfoPlist.strings b/ios/App/ru.lproj/InfoPlist.strings
index 3d50c32..8e01af4 100644
--- a/ios/App/ru.lproj/InfoPlist.strings
+++ b/ios/App/ru.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus использует микрофон только тогда, когда вы записываете закадровый голос или звук в фильм.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus сохраняет в вашей медиатеке экспортируемые фильмы и изображения, когда вы этого хотите.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus использует распознавание речи на этом iPad только тогда, когда вы просите создать субтитры по звуку. Звук остаётся на этом iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus использует локальную сеть только для связи с речевым сервером, который вы указали для ИИ-голоса.";
diff --git a/ios/App/sr-Latn.lproj/InfoPlist.strings b/ios/App/sr-Latn.lproj/InfoPlist.strings
index acefac7..901ff99 100644
--- a/ios/App/sr-Latn.lproj/InfoPlist.strings
+++ b/ios/App/sr-Latn.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus koristi mikrofon samo kada snimate naraciju ili zvuk u film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus čuva filmove i slike koje izvezete u vašu biblioteku fotografija kada to izaberete.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus koristi prepoznavanje govora na ovom iPadu samo kada zatražite da napiše titlove iz zvuka. Zvuk ostaje na ovom iPadu.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus koristi vašu lokalnu mrežu samo da bi došao do servera za govor koji navedete za AI glas.";
diff --git a/ios/App/sv.lproj/InfoPlist.strings b/ios/App/sv.lproj/InfoPlist.strings
index 1848dfe..9d48e0d 100644
--- a/ios/App/sv.lproj/InfoPlist.strings
+++ b/ios/App/sv.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus använder bara mikrofonen när du spelar in berättarröst eller ljud i en film.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus sparar de filmer och bilder du exporterar i ditt fotobibliotek när du väljer det.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus använder bara taligenkänning på den här iPaden när du ber den skriva undertexter från ett ljud. Ljudet stannar på den här iPaden.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus använder bara ditt lokala nätverk för att nå den talserver du anger för AI-röst.";
diff --git a/ios/App/th.lproj/InfoPlist.strings b/ios/App/th.lproj/InfoPlist.strings
index 8cc823a..9eb1981 100644
--- a/ios/App/th.lproj/InfoPlist.strings
+++ b/ios/App/th.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus ใช้ไมโครโฟนเฉพาะเมื่อคุณบันทึกเสียงบรรยายหรือเสียงลงในภาพยนตร์เท่านั้น";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus จะบันทึกภาพยนตร์และรูปภาพที่คุณส่งออกลงในคลังรูปภาพของคุณเมื่อคุณเลือกเท่านั้น";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus ใช้การรู้จำเสียงพูดบน iPad เครื่องนี้เฉพาะเมื่อคุณสั่งให้เขียนคำบรรยายจากเสียงเท่านั้น เสียงจะอยู่บน iPad เครื่องนี้";
+"NSLocalNetworkUsageDescription" = "FormMorpheus ใช้เครือข่ายท้องถิ่นของคุณเพื่อเชื่อมต่อกับเซิร์ฟเวอร์เสียงพูดที่คุณระบุสำหรับเสียง AI เท่านั้น";
diff --git a/ios/App/tr.lproj/InfoPlist.strings b/ios/App/tr.lproj/InfoPlist.strings
index e59d8de..3a4e221 100644
--- a/ios/App/tr.lproj/InfoPlist.strings
+++ b/ios/App/tr.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus mikrofonu yalnızca bir filme anlatım veya ses kaydettiğinizde kullanır.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus, siz seçtiğinizde dışa aktardığınız filmleri ve görüntüleri fotoğraf kitaplığınıza kaydeder.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus, bu iPad'deki konuşma tanımayı yalnızca bir sesten altyazı yazmasını istediğinizde kullanır. Ses bu iPad'de kalır.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus, yerel ağınızı yalnızca Yapay zekâ sesi için belirttiğiniz konuşma sunucusuna ulaşmak için kullanır.";
diff --git a/ios/App/uk.lproj/InfoPlist.strings b/ios/App/uk.lproj/InfoPlist.strings
index 44b0d15..8eeadd9 100644
--- a/ios/App/uk.lproj/InfoPlist.strings
+++ b/ios/App/uk.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus використовує мікрофон лише тоді, коли ви записуєте закадровий голос або звук у фільм.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus зберігає у вашу фотобібліотеку фільми й зображення, які ви експортуєте, коли ви цього захочете.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus використовує розпізнавання мовлення на цьому iPad лише тоді, коли ви просите створити субтитри зі звуку. Звук залишається на цьому iPad.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus використовує вашу локальну мережу лише для зв’язку з мовним сервером, який ви вказали для Голосу ШІ.";
diff --git a/ios/App/vi.lproj/InfoPlist.strings b/ios/App/vi.lproj/InfoPlist.strings
index 4ad1038..7fe0e17 100644
--- a/ios/App/vi.lproj/InfoPlist.strings
+++ b/ios/App/vi.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "FormMorpheus chỉ dùng micrô khi bạn ghi âm lời dẫn hoặc âm thanh vào phim.";
"NSPhotoLibraryAddUsageDescription" = "FormMorpheus lưu các phim và hình ảnh bạn xuất vào thư viện ảnh của bạn khi bạn chọn làm vậy.";
+"NSSpeechRecognitionUsageDescription" = "FormMorpheus chỉ dùng tính năng nhận dạng giọng nói trên iPad này khi bạn yêu cầu viết phụ đề từ âm thanh. Âm thanh được giữ trên iPad này.";
+"NSLocalNetworkUsageDescription" = "FormMorpheus chỉ dùng mạng cục bộ của bạn để kết nối với máy chủ giọng nói mà bạn chỉ định cho Giọng AI.";
diff --git a/ios/App/zh-Hans.lproj/InfoPlist.strings b/ios/App/zh-Hans.lproj/InfoPlist.strings
index dd3d163..eaa600f 100644
--- a/ios/App/zh-Hans.lproj/InfoPlist.strings
+++ b/ios/App/zh-Hans.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "仅当你在影片中录制旁白或声音时,FormMorpheus 才会使用麦克风。";
"NSPhotoLibraryAddUsageDescription" = "当你选择时,FormMorpheus 会将你导出的影片和图像存储到你的照片图库。";
+"NSSpeechRecognitionUsageDescription" = "仅当你要求根据声音生成字幕时,FormMorpheus 才会在此 iPad 上使用语音识别。声音会保留在此 iPad 上。";
+"NSLocalNetworkUsageDescription" = "FormMorpheus 仅使用本地网络连接你为 AI 语音指定的语音服务器。";
diff --git a/ios/App/zh-Hant.lproj/InfoPlist.strings b/ios/App/zh-Hant.lproj/InfoPlist.strings
index ea967c9..523e679 100644
--- a/ios/App/zh-Hant.lproj/InfoPlist.strings
+++ b/ios/App/zh-Hant.lproj/InfoPlist.strings
@@ -1,2 +1,4 @@
"NSMicrophoneUsageDescription" = "只有在你於影片中錄製旁白或聲音時,FormMorpheus 才會使用麥克風。";
"NSPhotoLibraryAddUsageDescription" = "當你選擇時,FormMorpheus 會將你匯出的影片和影像儲存到你的照片圖庫。";
+"NSSpeechRecognitionUsageDescription" = "只有在你要求根據聲音產生字幕時,FormMorpheus 才會在此 iPad 上使用語音辨識。聲音會保留在此 iPad 上。";
+"NSLocalNetworkUsageDescription" = "FormMorpheus 只會使用區域網路連線到你為 AI 語音指定的語音伺服器。";
diff --git a/ios/Engine/EngineRouter.swift b/ios/Engine/EngineRouter.swift
index b892b90..7439005 100644
--- a/ios/Engine/EngineRouter.swift
+++ b/ios/Engine/EngineRouter.swift
@@ -10,6 +10,7 @@
// SystemRoutes "" /health /capabilities /system/library
// LibraryRoutes /library list, open, save, rename, duplicate, copy-to, delete, poster, preview, tags, stacks
// CharactersRoutes /characters saved characters: list, open, save, rename, delete, poster
+// ScenesRoutes /scenes saved scenes: list, open, save, rename, delete, poster
// BrushesRoutes /brushes libraries as folders, .order.json, import and export files, the migration
// FontsRoutes /fonts imported fonts with the signature check
// TrashRoutes /trash Recently Deleted (30 days)
@@ -21,12 +22,13 @@
// ExportsRoutes /exports (ios/Export) the Exports folder
// AudioEncodeRoutes /audio-encode (ios/Export) sound encoders
// TranscodeRoutes /transcode video the window cannot decode, converted with AVFoundation
+// VoiceRoutes /voice AI Voice: status, the voice app on the network, the online key, speak and sounds, listening (on-device speech recognition)
// Not ported, on purpose: /proxy (a desktop-only ffmpeg and network helper), /penlink
// (Pen Link is hidden on iPad), /files/stat and /files/source (the source link's automatic update; the
// window offers Update from Source... instead). Those requests answer 404, as the desktop does for an unknown route.
//
// Storage root: EngineConfig.dataDir, the Documents folder, so the Files app shows
-// Library, Characters, Brushes, Fonts, Ideas, Recently Deleted, Recovery and Exports like the desktop data folder.
+// Library, Characters, Scenes, Brushes, Fonts, Ideas, Recently Deleted, Recovery and Exports like the desktop data folder.
// Nothing is seeded: the backend seeds no stock brushes or example movies (starter brushes are built into the interface).
import Foundation
@@ -47,6 +49,7 @@ final class EngineRouter {
SystemRoutes(),
LibraryRoutes(),
CharactersRoutes(),
+ ScenesRoutes(),
BrushesRoutes(),
FontsRoutes(),
TrashRoutes(),
@@ -58,6 +61,7 @@ final class EngineRouter {
ExportsRoutes(),
AudioEncodeRoutes(),
TranscodeRoutes(),
+ VoiceRoutes(),
]
EngineMaintenance.start()
}
diff --git a/ios/Engine/VoiceKeychain.swift b/ios/Engine/VoiceKeychain.swift
new file mode 100644
index 0000000..610b5b2
--- /dev/null
+++ b/ios/Engine/VoiceKeychain.swift
@@ -0,0 +1,49 @@
+// VoiceKeychain.swift
+// The AI Voice keys on iPad: one generic password per account in the Keychain, under the service name the desktop's
+// keyring uses (FormMorpheus). Kept on this device only, readable after the first unlock, never in UserDefaults.
+
+import Foundation
+import Security
+
+enum VoiceKeychain {
+ static let service = "FormMorpheus"
+
+ private static func query(_ account: String) -> [String: Any] {
+ return [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ ]
+ }
+
+ static func get(_ account: String) -> String? {
+ var q = query(account)
+ q[kSecReturnData as String] = true
+ q[kSecMatchLimit as String] = kSecMatchLimitOne
+ var item: CFTypeRef? = nil
+ let status = SecItemCopyMatching(q as CFDictionary, &item)
+ guard status == errSecSuccess, let data = item as? Data,
+ let text = String(data: data, encoding: .utf8), !text.isEmpty else { return nil }
+ return text
+ }
+
+ /// False when the Keychain refused the key.
+ static func set(_ account: String, _ value: String) -> Bool {
+ let data = Data(value.utf8)
+ let changes: [String: Any] = [
+ kSecValueData as String: data,
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
+ ]
+ let updated = SecItemUpdate(query(account) as CFDictionary, changes as CFDictionary)
+ if updated == errSecSuccess { return true }
+ if updated != errSecItemNotFound { _ = SecItemDelete(query(account) as CFDictionary) }
+ var add = query(account)
+ add[kSecValueData as String] = data
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
+ }
+
+ static func delete(_ account: String) {
+ _ = SecItemDelete(query(account) as CFDictionary)
+ }
+}
diff --git a/ios/Engine/VoiceListen.swift b/ios/Engine/VoiceListen.swift
new file mode 100644
index 0000000..00ac853
--- /dev/null
+++ b/ios/Engine/VoiceListen.swift
@@ -0,0 +1,503 @@
+// VoiceListen.swift
+// Listening on iPad: the words of a sound with their times, heard by the iPad's own speech recognition (Speech
+// framework, on the device only, never the network). Answers in the shape of backend/app/services/voice_transcribe.py:
+// {language, seconds, cues}, the word times grouped into short phrases by the same rules as the desktop's worker.
+
+import Foundation
+import Speech
+
+struct VoiceWord {
+ var text: String
+ var start: Double
+ var end: Double
+}
+
+struct VoiceListenLook {
+ let authorization: String
+ let authorized: Bool
+ let locale: String
+ let onDevice: Bool
+ let available: Bool
+ let reason: String
+}
+
+enum VoiceListenOutcome {
+ case heard([VoiceWord])
+ case nothing
+ case failed(String)
+ case timedOut
+}
+
+/// One recognition of one file. The delegate hears each final utterance; the task's end resumes the caller once.
+final class VoiceListenTask: NSObject, SFSpeechRecognitionTaskDelegate, @unchecked Sendable {
+ private let lock = NSLock()
+ private var words: [VoiceWord] = []
+ private var lastEnd = -1.0
+ private var cont: CheckedContinuation? = nil
+ private var done = false
+ private var recognizer: SFSpeechRecognizer? = nil
+ private var task: SFSpeechRecognitionTask? = nil
+
+ func run(file: URL, locale: String, timeout: Double) async -> VoiceListenOutcome {
+ return await withCheckedContinuation { (c: CheckedContinuation) in
+ lock.withLock { cont = c }
+ DispatchQueue.main.async {
+ guard let r = SFSpeechRecognizer(locale: Locale(identifier: locale)) else {
+ self.finish(.failed(VoiceListen.noLanguage))
+ return
+ }
+ let request = SFSpeechURLRecognitionRequest(url: file)
+ request.requiresOnDeviceRecognition = true
+ request.shouldReportPartialResults = false
+ request.addsPunctuation = true
+ self.recognizer = r
+ self.task = r.recognitionTask(with: request, delegate: self)
+ }
+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) {
+ if self.finish(.timedOut) {
+ DispatchQueue.main.async { self.task?.cancel() }
+ }
+ }
+ }
+ }
+
+ @discardableResult
+ private func finish(_ outcome: VoiceListenOutcome) -> Bool {
+ let c: CheckedContinuation? = lock.withLock {
+ if done { return nil }
+ done = true
+ let pending = cont
+ cont = nil
+ return pending
+ }
+ guard let resume = c else { return false }
+ resume.resume(returning: outcome)
+ return true
+ }
+
+ func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishRecognition recognitionResult: SFSpeechRecognitionResult) {
+ let segments = recognitionResult.bestTranscription.segments
+ lock.withLock {
+ for s in segments {
+ let text = EngineText.strip(s.substring)
+ let start = Double(s.timestamp)
+ if text.isEmpty || start < lastEnd - 0.001 { continue }
+ let end = start + max(0, Double(s.duration))
+ words.append(VoiceWord(text: text, start: start, end: end))
+ lastEnd = max(lastEnd, end)
+ }
+ }
+ }
+
+ func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) {
+ let heard = lock.withLock { words }
+ if successfully {
+ finish(heard.isEmpty ? .nothing : .heard(heard))
+ return
+ }
+ if !heard.isEmpty {
+ finish(.heard(heard))
+ return
+ }
+ let error = task.error.map { $0 as NSError }
+ if let e = error, e.code == 1110 {
+ finish(.nothing)
+ return
+ }
+ let said = error?.localizedDescription ?? ""
+ finish(.failed(EngineText.strip("Listening to this sound failed. \(said)")))
+ }
+
+ func speechRecognitionTaskWasCancelled(_ task: SFSpeechRecognitionTask) {
+ finish(.failed("Listening to this sound was stopped."))
+ }
+}
+
+enum VoiceListen {
+ static let rate = 16000
+ static let maxBytes = 256 * 1024 * 1024
+ static let name = "iPad speech recognition"
+ static let noLanguage = "This iPad cannot listen in that language on the device. Choose another language."
+
+ private static let lock = NSLock()
+ private static var busy = false
+ private static var job: [String: Any]? = nil
+
+ // MARK: permission and languages
+
+ static func authorizationName(_ s: SFSpeechRecognizerAuthorizationStatus) -> String {
+ switch s {
+ case .authorized: return "authorized"
+ case .denied: return "denied"
+ case .restricted: return "restricted"
+ case .notDetermined: return "notDetermined"
+ @unknown default: return "denied"
+ }
+ }
+
+ static let askSentence = "Listening uses this iPad's own speech recognition. Allow it when the iPad asks."
+ static let deniedSentence = "Speech recognition is turned off for FormMorpheus. Turn it on in Settings, under Privacy & Security, Speech Recognition."
+ static let restrictedSentence = "Speech recognition is not allowed on this iPad."
+
+ private static func dashed(_ id: String) -> String {
+ let plain = id.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false).first.map { String($0) } ?? id
+ return plain.replacingOccurrences(of: "_", with: "-")
+ }
+
+ private static func languagePart(_ id: String) -> String {
+ return dashed(id).lowercased().split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false).first.map { String($0) } ?? ""
+ }
+
+ /// The identifier of the recognizer's locale for a code: an exact match ("en-gb"), else the code's language in a
+ /// region the person prefers, else the first supported region of that language. "" or "auto" is the iPad's own language.
+ static func localeFor(_ asked: String) -> String? {
+ let ids = SFSpeechRecognizer.supportedLocales().map { dashed($0.identifier) }.sorted()
+ let lowered = ids.map { $0.lowercased() }
+ let want = dashed(EngineText.strip(asked)).lowercased()
+ if want.isEmpty || want == "auto" {
+ for pref in Locale.preferredLanguages {
+ let code = languagePart(pref)
+ if code.isEmpty || code == "auto" { continue }
+ if let found = localeFor(code) { return found }
+ }
+ return nil
+ }
+ if let i = lowered.firstIndex(of: want) { return ids[i] }
+ let code = languagePart(want)
+ if code.isEmpty { return nil }
+ var tries: [String] = Locale.preferredLanguages.map { dashed($0).lowercased() }
+ tries.append(dashed(Locale.current.identifier).lowercased())
+ if let region = Locale.current.region?.identifier { tries.append(code + "-" + region.lowercased()) }
+ for t in tries where languagePart(t) == code {
+ if let i = lowered.firstIndex(of: t) { return ids[i] }
+ let parts = t.split(separator: "-").map { String($0) }
+ if let last = parts.last, parts.count > 1, let i = lowered.firstIndex(of: code + "-" + last) { return ids[i] }
+ }
+ if let i = lowered.firstIndex(where: { $0 == code || $0.hasPrefix(code + "-") }) { return ids[i] }
+ return nil
+ }
+
+ static func look(_ asked: String) -> VoiceListenLook {
+ let auth = SFSpeechRecognizer.authorizationStatus()
+ let authName = authorizationName(auth)
+ let authorized = auth == .authorized
+ guard let id = localeFor(asked), let r = SFSpeechRecognizer(locale: Locale(identifier: id)) else {
+ let reason = authorized ? noLanguage : sentence(authName)
+ return VoiceListenLook(authorization: authName, authorized: authorized, locale: "", onDevice: false, available: false, reason: reason)
+ }
+ let onDevice = r.supportsOnDeviceRecognition
+ var reason = ""
+ if !authorized { reason = sentence(authName) } else if !onDevice { reason = noLanguage }
+ return VoiceListenLook(authorization: authName, authorized: authorized, locale: id, onDevice: onDevice, available: r.isAvailable, reason: reason)
+ }
+
+ private static func sentence(_ auth: String) -> String {
+ switch auth {
+ case "denied": return deniedSentence
+ case "restricted": return restrictedSentence
+ case "authorized": return ""
+ default: return askSentence
+ }
+ }
+
+ static func status(_ asked: String) -> [String: Any] {
+ let l = look(asked)
+ let r: [String: Any] = [
+ "ready": l.authorized && l.onDevice,
+ "runtime": l.authorized,
+ "model": l.onDevice,
+ "name": name,
+ "bytes": 0,
+ "job": currentJob(),
+ "platform": "ipad",
+ "authorization": l.authorization,
+ "language": l.locale,
+ "available": l.available,
+ "reason": l.reason,
+ ]
+ return r
+ }
+
+ static func currentJob() -> Any {
+ let j: [String: Any]? = lock.withLock { job }
+ if let found = j { return found }
+ return NSNull()
+ }
+
+ private static func setJob(_ state: String, _ error: String) -> [String: Any] {
+ let j: [String: Any] = ["state": state, "step": "model", "done": 0, "total": 0, "error": error]
+ lock.withLock { job = j }
+ return j
+ }
+
+ /// Asks the iPad for the permission; the page polls the job, as it does the desktop's model download.
+ static func startSetup() throws -> [String: Any] {
+ switch SFSpeechRecognizer.authorizationStatus() {
+ case .authorized:
+ return setJob("done", "")
+ case .denied:
+ throw EngineError(409, deniedSentence)
+ case .restricted:
+ throw EngineError(409, restrictedSentence)
+ default:
+ break
+ }
+ let previous: [String: Any]? = lock.withLock { job }
+ if let running = previous, (running["state"] as? String) == "running" {
+ throw EngineError(409, "FormMorpheus is already asking for permission to use speech recognition.")
+ }
+ let j = setJob("running", "")
+ DispatchQueue.main.async {
+ SFSpeechRecognizer.requestAuthorization { answer in
+ switch answer {
+ case .authorized: _ = VoiceListen.setJob("done", "")
+ case .restricted: _ = VoiceListen.setJob("failed", VoiceListen.restrictedSentence)
+ default: _ = VoiceListen.setJob("failed", VoiceListen.deniedSentence)
+ }
+ }
+ }
+ return j
+ }
+
+ // MARK: the sound
+
+ private static func ascii(_ d: Data, _ o: Int, _ n: Int) -> String {
+ if o + n > d.count { return "" }
+ let s = d.startIndex + o
+ return String(decoding: d[s..<(s + n)], as: UTF8.self)
+ }
+
+ private static func u16(_ d: Data, _ o: Int) -> Int {
+ let i = d.startIndex + o
+ return Int(d[i]) | (Int(d[i + 1]) << 8)
+ }
+
+ private static func u32(_ d: Data, _ o: Int) -> Int {
+ return u16(d, o) | (u16(d, o + 2) << 16)
+ }
+
+ /// Frames and where they start, for a 16 kHz mono 16-bit PCM WAV; nil for anything else.
+ static func wav(_ d: Data) -> (frames: Int, offset: Int)? {
+ guard ascii(d, 0, 4) == "RIFF", ascii(d, 8, 4) == "WAVE" else { return nil }
+ var at = 12
+ var format = false
+ while at + 8 <= d.count {
+ let id = ascii(d, at, 4)
+ let size = u32(d, at + 4)
+ let body = at + 8
+ if id == "fmt " {
+ guard size >= 16, body + 16 <= d.count else { return nil }
+ format = u16(d, body) == 1 && u16(d, body + 2) == 1 && u32(d, body + 4) == rate && u16(d, body + 14) == 16
+ if !format { return nil }
+ } else if id == "data" {
+ guard format else { return nil }
+ return (max(0, min(size, d.count - body)) / 2, body)
+ }
+ at = body + size + (size & 1)
+ }
+ return nil
+ }
+
+ static func level(_ d: Data, _ offset: Int, _ frames: Int) -> Double {
+ if frames <= 0 { return 0 }
+ var sum = 0.0
+ d.withUnsafeBytes { (p: UnsafeRawBufferPointer) in
+ var i = offset
+ let end = offset + frames * 2
+ while i + 1 < end {
+ let v = Int16(bitPattern: UInt16(p[i]) | (UInt16(p[i + 1]) << 8))
+ let x = Double(v) / 32768.0
+ sum += x * x
+ i += 2
+ }
+ }
+ return (sum / Double(frames)).squareRoot()
+ }
+
+ // MARK: phrases (the desktop worker's rules)
+
+ static let maxWords = 7
+ static let maxChars = 42
+ static let maxPhrase = 3.5
+ static let maxGap = 0.7
+ private static let ends: Set = [".", "!", "?", "\u{3002}", "\u{FF01}", "\u{FF1F}"]
+ private static let unspaced: Set = ["zh", "ja", "yue", "th"]
+
+ private static func splitLong(_ words: [VoiceWord]) -> [VoiceWord] {
+ var out: [VoiceWord] = []
+ for w in words {
+ let chars = Array(w.text)
+ if chars.count <= maxChars {
+ out.append(w)
+ continue
+ }
+ let n = (chars.count + maxChars - 1) / maxChars
+ let span = (w.end - w.start) / Double(n)
+ for k in 0.. Bool {
+ guard let first = g.first, let last = g.last else { return true }
+ let text = g.map { $0.text }.joined(separator: sep)
+ return g.count <= maxWords && text.count <= maxChars && (g.count == 1 || last.end - first.start <= maxPhrase)
+ }
+
+ private static func balance(_ run: [VoiceWord], _ sep: String) -> [[VoiceWord]] {
+ let lengths = run.map { Double($0.text.count + 1) }
+ let total = lengths.reduce(0, +)
+ if run.isEmpty || total <= 0 { return run.map { [$0] } }
+ for n in 1...run.count {
+ var groups = [[VoiceWord]](repeating: [], count: n)
+ var at = 0.0
+ for (word, length) in zip(run, lengths) {
+ let index = min(n - 1, Int((at + length / 2) / total * Double(n)))
+ groups[index].append(word)
+ at += length
+ }
+ let kept = groups.filter { !$0.isEmpty }
+ if kept.allSatisfy({ fits($0, sep) }) { return kept }
+ }
+ return run.map { [$0] }
+ }
+
+ private static func round3(_ x: Double) -> Double {
+ return (x * 1000).rounded() / 1000
+ }
+
+ static func phrases(_ heard: [VoiceWord], language: String) -> [[String: Any]] {
+ let sep = unspaced.contains(language) ? "" : " "
+ var runs: [[VoiceWord]] = []
+ var run: [VoiceWord] = []
+ for raw in splitLong(heard) {
+ let word = VoiceWord(text: raw.text, start: raw.start, end: max(raw.end, raw.start + 0.05))
+ let ended = run.last?.text.last.map({ ends.contains($0) }) ?? false
+ if let prev = run.last, word.start - prev.end > maxGap || ended {
+ runs.append(run)
+ run = []
+ }
+ run.append(word)
+ }
+ if !run.isEmpty { runs.append(run) }
+ var out: [[String: Any]] = []
+ for r in runs {
+ for g in balance(r, sep) {
+ guard let first = g.first else { continue }
+ let end = g.map { $0.end }.max() ?? first.end
+ out.append(["start": round3(first.start), "end": round3(end), "text": g.map { $0.text }.joined(separator: sep)])
+ }
+ }
+ return out
+ }
+
+ /// The service's _clean: in order, inside the sound, never overlapping.
+ static func clean(_ cues: [[String: Any]], _ seconds: Double) -> [[String: Any]] {
+ var kept: [(start: Double, end: Double, text: String)] = []
+ for cue in cues {
+ guard let s = cue["start"] as? Double, let e = cue["end"] as? Double, let t = cue["text"] as? String else { continue }
+ let start = max(0, min(s, seconds))
+ let end = max(0, min(e, seconds))
+ let text = t.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ")
+ if !text.isEmpty && end > start { kept.append((start: start, end: end, text: text)) }
+ }
+ kept.sort { $0.start != $1.start ? $0.start < $1.start : $0.end < $1.end }
+ var out: [[String: Any]] = []
+ var lastEnd: Double? = nil
+ for index in 0.. [VoiceWord] {
+ let weights = heard.map { Double($0.text.count + 1) }
+ let total = weights.reduce(0, +)
+ if total <= 0 || seconds <= 0 { return heard }
+ var at = 0.0
+ var out: [VoiceWord] = []
+ for (w, weight) in zip(heard, weights) {
+ let span = seconds * weight / total
+ out.append(VoiceWord(text: w.text, start: at, end: at + span))
+ at += span
+ }
+ return out
+ }
+
+ // MARK: listening
+
+ static func transcribe(_ body: Data, language: String) async throws -> [String: Any] {
+ if body.count > maxBytes {
+ throw EngineError(413, "That sound is too long to listen to in one go. Split the block and try each part.")
+ }
+ if body.count < 44 { throw EngineError(422, "There is no sound to listen to.") }
+ switch SFSpeechRecognizer.authorizationStatus() {
+ case .authorized: break
+ case .denied: throw EngineError(409, deniedSentence)
+ case .restricted: throw EngineError(409, restrictedSentence)
+ default: throw EngineError(409, "Allow FormMorpheus to use speech recognition first.")
+ }
+ let asked = EngineText.strip(language).lowercased()
+ let askedCode = (asked.isEmpty || asked == "auto") ? "" : languagePart(asked)
+ guard let locale = localeFor(asked) else {
+ if askedCode.isEmpty { throw EngineError(409, noLanguage) }
+ let shown = EngineText.prefix(EngineText.replaceBad(asked, with: ""), 12)
+ throw EngineError(422, "This iPad cannot listen in the language \(shown). Choose another language.")
+ }
+ if let r = SFSpeechRecognizer(locale: Locale(identifier: locale)), !r.supportsOnDeviceRecognition {
+ throw EngineError(409, noLanguage)
+ }
+ guard let sound = wav(body) else { throw EngineError(422, "The sound must be a 16 kHz mono 16-bit WAV.") }
+ let seconds = Double(sound.frames) / Double(rate)
+ if seconds < 0.1 || level(body, sound.offset, sound.frames) < 1e-3 {
+ let r: [String: Any] = ["language": askedCode, "seconds": round3(seconds), "cues": [[String: Any]]()]
+ return r
+ }
+ let taken: Bool = lock.withLock {
+ if busy { return false }
+ busy = true
+ return true
+ }
+ if !taken { throw EngineError(409, "Another sound is being listened to. Wait for it to finish, then try again.") }
+ defer { lock.withLock { busy = false } }
+
+ let folder = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Voice", isDirectory: true)
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ let file = folder.appendingPathComponent(".listen-\(EngineText.hex(12)).wav")
+ do {
+ try EngineFS.writeFile(body, to: file)
+ } catch {
+ EngineFS.remove(file)
+ throw EngineError(500, "The sound could not be stored for listening.")
+ }
+ defer { EngineFS.remove(file) }
+
+ let token = await TranscodeBackground.begin()
+ let outcome = await VoiceListenTask().run(file: file, locale: locale, timeout: min(7200, max(300, 10 * seconds)))
+ await TranscodeBackground.end(token)
+
+ let code = languagePart(locale)
+ var heard: [VoiceWord] = []
+ switch outcome {
+ case .heard(let words): heard = words
+ case .nothing: heard = []
+ case .timedOut: throw EngineError(502, "Listening to this sound took too long. Try a shorter part.")
+ case .failed(let said): throw EngineError(502, said)
+ }
+ let latest = heard.map({ $0.end }).max() ?? 0
+ if !heard.isEmpty && latest <= 0 { heard = spread(heard, seconds) }
+ let cues = clean(phrases(heard, language: code), seconds)
+ let r: [String: Any] = ["language": cues.isEmpty ? askedCode : code, "seconds": round3(seconds), "cues": cues]
+ return r
+ }
+}
diff --git a/ios/Engine/VoiceRemote.swift b/ios/Engine/VoiceRemote.swift
new file mode 100644
index 0000000..fd8765c
--- /dev/null
+++ b/ios/Engine/VoiceRemote.swift
@@ -0,0 +1,403 @@
+// VoiceRemote.swift
+// The voices that are not built in, on iPad: a voice app (a speech server on a computer on the same network that
+// answers the common speech API) and an online voice with the person's own key. A port of
+// backend/app/services/voice_remote.py: the same requests, headers, limits and sentences. Keys live in the Keychain
+// (VoiceKeychain.swift), the voice app's address, model and voice in UserDefaults.
+
+import Foundation
+
+struct VoiceReply {
+ let status: Int
+ let data: Data
+ let contentType: String
+}
+
+/// The voice app may not send the request anywhere else: a redirect is answered as it stands, never followed.
+final class VoiceNoRedirect: NSObject, URLSessionTaskDelegate {
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
+ completionHandler(nil)
+ }
+}
+
+enum VoiceHTTP {
+ static let local: URLSession = {
+ let config = URLSessionConfiguration.ephemeral
+ config.connectionProxyDictionary = [:]
+ config.urlCache = nil
+ config.requestCachePolicy = .reloadIgnoringLocalCacheData
+ return URLSession(configuration: config, delegate: VoiceNoRedirect(), delegateQueue: nil)
+ }()
+
+ static let online: URLSession = {
+ let config = URLSessionConfiguration.ephemeral
+ config.urlCache = nil
+ config.requestCachePolicy = .reloadIgnoringLocalCacheData
+ return URLSession(configuration: config)
+ }()
+
+ static func fetch(_ session: URLSession, _ request: URLRequest) async throws -> VoiceReply {
+ return try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in
+ let task = session.dataTask(with: request) { data, response, error in
+ if let error = error {
+ cont.resume(throwing: error)
+ return
+ }
+ guard let http = response as? HTTPURLResponse else {
+ cont.resume(throwing: URLError(.badServerResponse))
+ return
+ }
+ let ctype = http.value(forHTTPHeaderField: "Content-Type") ?? ""
+ cont.resume(returning: VoiceReply(status: http.statusCode, data: data ?? Data(), contentType: ctype))
+ }
+ task.resume()
+ }
+ }
+}
+
+/// Which addresses the voice app may have on iPad: the desktop's loopback names, private and link-local IPv4 and
+/// IPv6 addresses, and .local names. Never a name or address on the open internet.
+enum VoiceAddress {
+ static func allowed(_ host: String) -> Bool {
+ if host == "localhost" || host == "127.0.0.1" || host == "::1" { return true }
+ if let quad = ipv4(host) {
+ let a = quad[0], b = quad[1]
+ if a == 10 { return true }
+ if a == 172 && b >= 16 && b <= 31 { return true }
+ if a == 192 && b == 168 { return true }
+ if a == 169 && b == 254 { return true }
+ return false
+ }
+ if host.contains(":") {
+ if !EngineText.matches("^[0-9a-f:.]+$", host) { return false }
+ let first = host.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false).first.map { String($0) } ?? ""
+ guard !first.isEmpty, first.count <= 4, let v = Int(first, radix: 16) else { return false }
+ return (v & 0xffc0) == 0xfe80 || (v & 0xfe00) == 0xfc00
+ }
+ return EngineText.matches("^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+local$", host)
+ }
+
+ private static func ipv4(_ host: String) -> [Int]? {
+ let parts = host.split(separator: ".", omittingEmptySubsequences: false).map { String($0) }
+ if parts.count != 4 { return nil }
+ var out: [Int] = []
+ for p in parts {
+ guard !p.isEmpty, p.count <= 3, EngineText.matches("^[0-9]+$", p), let n = Int(p), n <= 255 else { return nil }
+ out.append(n)
+ }
+ return out
+ }
+}
+
+enum VoiceRemote {
+ static let localAccount = "voice-local-key"
+ static let onlineAccount = "voice-online-key"
+ static let settingsKey = "formmorpheus.voice.local"
+ static let onlineBase = "https://api.elevenlabs.io"
+ static let defaultOnlineVoice = "21m00Tcm4TlvDq8ikWAM"
+ static let defaultOnlineModel = "eleven_multilingual_v2"
+ static let maxOnlineText = 2000
+ static let maxBytes = 200 * 1024 * 1024
+ static let speechTimeout: TimeInterval = 300
+ static let probeTimeout: TimeInterval = 5
+ static let onlineTimeout: TimeInterval = 120
+
+ static let addressSorry = "Only an address on the same network is allowed, such as http://192.168.1.20:8080 or http://my-computer.local:8080."
+ static let noKeyStore = "This iPad could not keep the key in its Keychain, so it was not saved."
+
+ private static let mimes: [String: String] = [
+ "audio/wav": "audio/wav", "audio/x-wav": "audio/wav", "audio/wave": "audio/wav", "audio/vnd.wave": "audio/wav",
+ "audio/mpeg": "audio/mpeg", "audio/mp3": "audio/mpeg", "audio/ogg": "audio/ogg", "application/ogg": "audio/ogg",
+ "audio/flac": "audio/flac", "audio/x-flac": "audio/flac",
+ ]
+ private static let generic: Set = ["", "application/octet-stream", "binary/octet-stream", "text/plain", "audio/basic"]
+
+ struct Spoken {
+ let audio: Data
+ let mime: String
+ let voice: String
+ }
+
+ // MARK: settings
+
+ static func storedLocal() -> (base: String, model: String, voice: String) {
+ let raw = UserDefaults.standard.dictionary(forKey: settingsKey) ?? [:]
+ return ((raw["base"] as? String) ?? "", (raw["model"] as? String) ?? "", (raw["voice"] as? String) ?? "")
+ }
+
+ static func localSettings() -> [String: Any] {
+ let s = storedLocal()
+ return ["base": s.base, "model": s.model, "voice": s.voice, "hasKey": VoiceKeychain.get(localAccount) != nil]
+ }
+
+ static func normalizeBase(_ base: String) throws -> String {
+ let sorry = EngineError(422, addressSorry)
+ let text = EngineText.strip(base)
+ if text.isEmpty { throw sorry }
+ guard let parts = URLComponents(string: text) else { throw sorry }
+ let scheme = (parts.scheme ?? "").lowercased()
+ var host = (parts.host ?? "").lowercased()
+ if host.hasPrefix("[") && host.hasSuffix("]") { host = String(host.dropFirst().dropLast()) }
+ if scheme != "http" && scheme != "https" { throw sorry }
+ if parts.user != nil || parts.password != nil || parts.query != nil || parts.fragment != nil { throw sorry }
+ var path = parts.path
+ while path.hasSuffix("/") { path.removeLast() }
+ if path != "" && path != "/v1" { throw sorry }
+ if host.isEmpty || !VoiceAddress.allowed(host) { throw sorry }
+ var out = scheme + "://" + (host.contains(":") ? "[\(host)]" : host)
+ if let port = parts.port {
+ if port < 0 || port > 65535 { throw sorry }
+ out += ":\(port)"
+ }
+ return out
+ }
+
+ static func saveLocal(base: String, model: String, voice: String, key: String?) throws -> [String: Any] {
+ var clean = ""
+ if !EngineText.strip(base).isEmpty { clean = try normalizeBase(base) }
+ if let k = key {
+ let trimmed = EngineText.strip(k)
+ if trimmed.isEmpty {
+ VoiceKeychain.delete(localAccount)
+ } else if !VoiceKeychain.set(localAccount, trimmed) {
+ throw EngineError(503, noKeyStore)
+ }
+ }
+ let stored: [String: String] = ["base": clean, "model": EngineText.strip(model), "voice": EngineText.strip(voice)]
+ UserDefaults.standard.set(stored, forKey: settingsKey)
+ return localSettings()
+ }
+
+ // MARK: replies
+
+ private static func replyText(_ data: Data) -> String {
+ let said = EngineText.strip(String(decoding: data.prefix(150), as: UTF8.self))
+ return EngineText.prefix(said, 150)
+ }
+
+ private static func sniff(_ d: Data) -> String? {
+ let b = [UInt8](d.prefix(12))
+ func at(_ i: Int, _ s: String) -> Bool {
+ let want = [UInt8](s.utf8)
+ return b.count >= i + want.count && Array(b[i..<(i + want.count)]) == want
+ }
+ if at(0, "RIFF") && at(8, "WAVE") { return "audio/wav" }
+ if at(0, "ID3") || (b.count > 1 && b[0] == 0xFF && (b[1] & 0xE0) == 0xE0) { return "audio/mpeg" }
+ if at(0, "OggS") { return "audio/ogg" }
+ if at(0, "fLaC") { return "audio/flac" }
+ return nil
+ }
+
+ private static func mimeOf(_ contentType: String, _ data: Data) throws -> String {
+ let declared = EngineText.strip(contentType.split(separator: ";", maxSplits: 1, omittingEmptySubsequences: false).first.map { String($0) } ?? "").lowercased()
+ if let m = mimes[declared] { return m }
+ if generic.contains(declared), let found = sniff(data) { return found }
+ throw EngineError(502, "The voice app answered with something that is not a sound.")
+ }
+
+ private static func isOK(_ status: Int) -> Bool {
+ return status >= 200 && status < 300
+ }
+
+ // MARK: the voice app
+
+ private static func localGet(_ base: String, _ path: String, _ key: String?) async -> Any? {
+ guard let url = URL(string: base + path) else { return nil }
+ var req = URLRequest(url: url)
+ req.timeoutInterval = probeTimeout
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+ if let k = key { req.setValue("Bearer " + k, forHTTPHeaderField: "Authorization") }
+ guard let reply = try? await VoiceHTTP.fetch(VoiceHTTP.local, req), isOK(reply.status), reply.data.count <= maxBytes else {
+ return nil
+ }
+ guard let value = EngineJSON.any(reply.data), !(value is NSNull) else { return nil }
+ return value
+ }
+
+ private static func truthy(_ v: Any?) -> Bool {
+ guard let v = v, !(v is NSNull) else { return false }
+ if let s = v as? String { return !s.isEmpty }
+ if let n = v as? NSNumber { return n.doubleValue != 0 }
+ if let a = v as? [Any] { return !a.isEmpty }
+ if let o = v as? [String: Any] { return !o.isEmpty }
+ return true
+ }
+
+ private static func text(_ v: Any) -> String {
+ if let s = v as? String { return s }
+ return "\(v)"
+ }
+
+ static func probeLocal(_ base: String) async throws -> [String: Any] {
+ let clean = try normalizeBase(base)
+ let key = VoiceKeychain.get(localAccount)
+ let listed = await localGet(clean, "/v1/models", key)
+ let voiced = await localGet(clean, "/v1/audio/voices", key)
+ if listed == nil && voiced == nil {
+ guard let url = URL(string: clean + "/") else { throw EngineError(422, addressSorry) }
+ var req = URLRequest(url: url)
+ req.timeoutInterval = probeTimeout
+ do {
+ _ = try await VoiceHTTP.fetch(VoiceHTTP.local, req)
+ } catch {
+ let r: [String: Any] = ["ok": false, "models": [String](), "voices": [[String: Any]](),
+ "error": "No voice app answered at that address. Check that it is running and that the address is right."]
+ return r
+ }
+ }
+ var models: [String] = []
+ let items: Any? = (listed as? [String: Any])?["data"] ?? listed
+ for item in (items as? [Any]) ?? [] {
+ let name: Any? = (item as? [String: Any])?["id"] ?? item
+ if let n = name as? String, !n.isEmpty { models.append(n) }
+ }
+ var voices: [[String: Any]] = []
+ let raw: Any? = (voiced as? [String: Any])?["voices"] ?? voiced
+ for item in (raw as? [Any]) ?? [] {
+ var vid: Any? = nil
+ var name: Any? = nil
+ if let s = item as? String {
+ vid = s
+ name = s
+ } else if let o = item as? [String: Any] {
+ for k in ["id", "voice_id", "name"] where vid == nil && truthy(o[k]) { vid = o[k] }
+ name = truthy(o["name"]) ? o["name"] : vid
+ } else {
+ continue
+ }
+ if let v = vid as? String, !v.isEmpty {
+ voices.append(["id": v, "name": text(name ?? v)])
+ }
+ }
+ let r: [String: Any] = ["ok": true, "models": models, "voices": voices, "error": ""]
+ return r
+ }
+
+ static func speakLocal(text: String, voice: String, model: String, speed: Double) async throws -> Spoken {
+ let stored = storedLocal()
+ if EngineText.strip(stored.base).isEmpty {
+ throw EngineError(422, "There is no voice app address yet. Add the address of the speech server in the AI Voice card.")
+ }
+ let base = try normalizeBase(stored.base)
+ let useModel = EngineText.strip(model).isEmpty ? stored.model : EngineText.strip(model)
+ let useVoice = EngineText.strip(voice).isEmpty ? stored.voice : EngineText.strip(voice)
+ var body: [String: Any] = ["input": text, "speed": speed, "response_format": "wav"]
+ if !useModel.isEmpty { body["model"] = useModel }
+ if !useVoice.isEmpty { body["voice"] = useVoice }
+ guard let url = URL(string: base + "/v1/audio/speech") else { throw EngineError(422, addressSorry) }
+ var req = URLRequest(url: url)
+ req.httpMethod = "POST"
+ req.timeoutInterval = speechTimeout
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ if let k = VoiceKeychain.get(localAccount) { req.setValue("Bearer " + k, forHTTPHeaderField: "Authorization") }
+ req.httpBody = EngineJSON.encode(body)
+ let reply: VoiceReply
+ do {
+ reply = try await VoiceHTTP.fetch(VoiceHTTP.local, req)
+ } catch {
+ throw EngineError(502, "The voice app did not answer. Check that it is running and that its address is right.")
+ }
+ if !isOK(reply.status) {
+ let said = replyText(reply.data)
+ throw EngineError(502, "The voice app refused the request (error \(reply.status))" + (said.isEmpty ? "." : ": \(said)"))
+ }
+ if reply.data.count > maxBytes {
+ throw EngineError(502, "The voice sent back a sound larger than 200 MB, so it was dropped.")
+ }
+ if reply.data.isEmpty { throw EngineError(502, "The voice app answered with an empty sound.") }
+ return Spoken(audio: reply.data, mime: try mimeOf(reply.contentType, reply.data), voice: useVoice)
+ }
+
+ // MARK: online
+
+ static func onlineStatus() -> [String: Any] {
+ return ["hasKey": VoiceKeychain.get(onlineAccount) != nil, "canStore": true]
+ }
+
+ static func setOnlineKey(_ key: String) throws {
+ let clean = EngineText.strip(key)
+ if clean.isEmpty { throw EngineError(422, "There is no key to save.") }
+ if !VoiceKeychain.set(onlineAccount, clean) { throw EngineError(503, noKeyStore) }
+ }
+
+ static func clearOnlineKey() {
+ VoiceKeychain.delete(onlineAccount)
+ }
+
+ private static func needKey() throws -> String {
+ guard let key = VoiceKeychain.get(onlineAccount) else {
+ throw EngineError(503, "There is no online voice key yet. Add your key in the AI Voice card's Online tab.")
+ }
+ return key
+ }
+
+ private static func onlineCall(_ req: URLRequest) async throws -> VoiceReply {
+ let reply: VoiceReply
+ do {
+ reply = try await VoiceHTTP.fetch(VoiceHTTP.online, req)
+ } catch {
+ throw EngineError(502, "The online voice service could not be reached. Check the internet connection.")
+ }
+ if reply.status == 401 {
+ throw EngineError(502, "The online voice service did not accept the key (error 401). Check the key in the Online tab.")
+ }
+ if !isOK(reply.status) {
+ let said = replyText(reply.data)
+ throw EngineError(502, "The online voice service refused the request (error \(reply.status))" + (said.isEmpty ? "." : ": \(said)"))
+ }
+ if reply.data.count > maxBytes {
+ throw EngineError(502, "The voice sent back a sound larger than 200 MB, so it was dropped.")
+ }
+ return reply
+ }
+
+ static func onlineVoices() async throws -> [[String: Any]] {
+ let key = try needKey()
+ guard let url = URL(string: onlineBase + "/v1/voices") else { throw EngineError(502, "The online voice service could not be reached. Check the internet connection.") }
+ var req = URLRequest(url: url)
+ req.timeoutInterval = onlineTimeout
+ req.setValue(key, forHTTPHeaderField: "xi-api-key")
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+ let reply = try await onlineCall(req)
+ guard let top = EngineJSON.any(reply.data) as? [String: Any] else {
+ throw EngineError(502, "The online voice service answered with something unreadable.")
+ }
+ var out: [[String: Any]] = []
+ for item in (top["voices"] as? [Any]) ?? [] {
+ guard let o = item as? [String: Any], truthy(o["voice_id"]), let vidRaw = o["voice_id"] else { continue }
+ let vid = text(vidRaw)
+ let labels = (o["labels"] as? [String: Any]) ?? [:]
+ var group = ""
+ if truthy(labels["accent"]), let a = labels["accent"] { group = text(a) }
+ else if truthy(o["category"]), let c = o["category"] { group = text(c) }
+ let name = truthy(o["name"]) ? text(o["name"] ?? vid) : vid
+ out.append(["id": vid, "name": name, "group": group])
+ }
+ return out
+ }
+
+ static func speakOnline(text spoken: String, voice: String, model: String) async throws -> Spoken {
+ let key = try needKey()
+ if EngineText.length(spoken) > maxOnlineText {
+ throw EngineError(422, "The online voice takes at most \(maxOnlineText) characters at a time. Shorten the text.")
+ }
+ let useVoice = EngineText.strip(voice).isEmpty ? defaultOnlineVoice : EngineText.strip(voice)
+ if !EngineText.matches("^[A-Za-z0-9]+$", useVoice) {
+ throw EngineError(422, "That voice id is not valid. It may hold only letters and digits.")
+ }
+ let useModel = EngineText.strip(model).isEmpty ? defaultOnlineModel : EngineText.strip(model)
+ let body: [String: Any] = ["text": spoken, "model_id": useModel]
+ guard let url = URL(string: "\(onlineBase)/v1/text-to-speech/\(useVoice)") else {
+ throw EngineError(422, "That voice id is not valid. It may hold only letters and digits.")
+ }
+ var req = URLRequest(url: url)
+ req.httpMethod = "POST"
+ req.timeoutInterval = onlineTimeout
+ req.setValue(key, forHTTPHeaderField: "xi-api-key")
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ req.httpBody = EngineJSON.encode(body)
+ let reply = try await onlineCall(req)
+ if reply.data.isEmpty { throw EngineError(502, "The online voice service answered with an empty sound.") }
+ return Spoken(audio: reply.data, mime: "audio/mpeg", voice: useVoice)
+ }
+}
diff --git a/ios/Engine/VoiceRoutes.swift b/ios/Engine/VoiceRoutes.swift
new file mode 100644
index 0000000..b8732d0
--- /dev/null
+++ b/ios/Engine/VoiceRoutes.swift
@@ -0,0 +1,225 @@
+// VoiceRoutes.swift
+// /api/voice on iPad: the paths, JSON shapes and status codes of backend/app/routers/voice.py, so the interface's
+// io/voice-api.ts works unchanged. The built-in voice (a Python runtime) cannot exist here and says so; the voice
+// app is a speech server on the same network and the online voice uses the Keychain (VoiceRemote.swift); listening
+// is the iPad's own on-device speech recognition (VoiceListen.swift). A spoken sound waits in Caches/Voice/out until
+// the page fetches it, swept after an hour, as the desktop keeps it in its data folder.
+
+import Foundation
+
+final class VoiceRoutes: APIRoutes, @unchecked Sendable {
+ let prefix = "/voice"
+ private let table = RouteTable()
+
+ typealias AsyncHandler = (RouteContext) async throws -> APIResponse
+
+ private struct AsyncRoute {
+ let method: String
+ let parts: [String]
+ let handler: AsyncHandler
+ }
+
+ private var asyncRoutes: [AsyncRoute] = []
+
+ static let engines: Set = ["builtin", "local", "online"]
+ static let maxText = 10000
+ static let keepSeconds: TimeInterval = 3600
+ static let ext: [String: String] = ["audio/wav": ".wav", "audio/mpeg": ".mp3", "audio/ogg": ".ogg", "audio/flac": ".flac", "audio/aac": ".aac"]
+ static let noBuiltin = "The built-in voice is not available on iPad."
+ static let noSound = "There is no spoken sound with that id."
+
+ init() {
+ table.add("GET", "/voice/status") { [unowned self] c in try self.status(c) }
+ table.add("POST", "/voice/builtin/setup") { _ in throw EngineError(409, VoiceRoutes.noBuiltin) }
+ table.add("GET", "/voice/builtin/job") { _ in APIResponse.json(["job": NSNull()]) }
+ table.add("DELETE", "/voice/builtin/job") { _ in APIResponse.json(["cancelled": false]) }
+ table.add("DELETE", "/voice/builtin") { _ in APIResponse.json(["removed": false]) }
+ table.add("GET", "/voice/builtin/voices") { _ in throw EngineError(409, VoiceRoutes.noBuiltin) }
+ table.add("PUT", "/voice/local") { [unowned self] c in try self.localSave(c) }
+ table.add("PUT", "/voice/online/key") { [unowned self] c in try self.onlineKey(c) }
+ table.add("DELETE", "/voice/online/key") { _ in
+ VoiceRemote.clearOnlineKey()
+ return APIResponse.json(VoiceRemote.onlineStatus())
+ }
+ table.add("GET", "/voice/audio/{sid}") { [unowned self] c in try self.audio(c) }
+ table.add("DELETE", "/voice/audio/{sid}") { [unowned self] c in try self.audioDrop(c) }
+ table.add("GET", "/voice/transcribe/status") { c in APIResponse.json(VoiceListen.status(c.query("language") ?? "auto")) }
+ table.add("POST", "/voice/transcribe/setup") { _ in APIResponse.json(try VoiceListen.startSetup(), status: 202) }
+ table.add("GET", "/voice/transcribe/job") { _ in APIResponse.json(["job": VoiceListen.currentJob()]) }
+ table.add("DELETE", "/voice/transcribe/job") { _ in APIResponse.json(["cancelled": false]) }
+ table.add("DELETE", "/voice/transcribe") { _ in APIResponse.json(["removed": false]) }
+
+ addAsync("POST", "/voice/local/probe") { [unowned self] c in try await self.localProbe(c) }
+ addAsync("GET", "/voice/online/voices") { _ in
+ let voices = try await VoiceRemote.onlineVoices()
+ return APIResponse.json(["voices": voices])
+ }
+ addAsync("POST", "/voice/speak") { [unowned self] c in try await self.speak(c) }
+ addAsync("POST", "/voice/transcribe") { c in
+ let language = EngineText.prefix(c.query("language") ?? "auto", 12)
+ return APIResponse.json(try await VoiceListen.transcribe(c.body, language: language))
+ }
+ }
+
+ private func addAsync(_ method: String, _ pattern: String, _ handler: @escaping AsyncHandler) {
+ asyncRoutes.append(AsyncRoute(method: method, parts: EngineHTTP.split(pattern), handler: handler))
+ }
+
+ func handle(_ request: APIRequest) async -> APIResponse? {
+ let segs = EngineHTTP.segments(request.path)
+ let method = request.method.uppercased()
+ var asyncPath = false
+ for route in asyncRoutes where route.parts == segs {
+ asyncPath = true
+ if route.method != method { continue }
+ do {
+ return try await route.handler(RouteContext(request: request, params: [:]))
+ } catch let e as EngineError {
+ return APIResponse.error(e.status, e.detail)
+ } catch {
+ return APIResponse.error(500, "Internal Server Error")
+ }
+ }
+ if table.handles(request) {
+ return await EngineWork.run { return self.table.dispatch(request) }
+ }
+ return asyncPath ? APIResponse.error(405, "Method Not Allowed") : nil
+ }
+
+ // MARK: status
+
+ private func status(_ c: RouteContext) throws -> APIResponse {
+ let builtin: [String: Any] = ["ready": false, "runtime": false, "model": false, "python": NSNull(), "folder": "", "bytes": 0,
+ "job": NSNull(), "available": false, "reason": VoiceRoutes.noBuiltin]
+ let r: [String: Any] = ["builtin": builtin, "local": VoiceRemote.localSettings(), "online": VoiceRemote.onlineStatus(), "platform": "ipad"]
+ return APIResponse.json(r)
+ }
+
+ // MARK: the voice app and the online key
+
+ private func limitedString(_ b: JSONBody, _ key: String, max: Int, required: Bool = false) throws -> String? {
+ guard let v = try b.optString(key) else {
+ if required { throw EngineError(422, "Field required: \(key)") }
+ return nil
+ }
+ if EngineText.length(v) > max { throw EngineError(422, "String should have at most \(max) characters: \(key)") }
+ if required && v.isEmpty { throw EngineError(422, "String should have at least 1 character: \(key)") }
+ return v
+ }
+
+ private func localSave(_ c: RouteContext) throws -> APIResponse {
+ let b = try c.json()
+ let base = try limitedString(b, "base", max: 200) ?? ""
+ let model = try limitedString(b, "model", max: 120) ?? ""
+ let voice = try limitedString(b, "voice", max: 120) ?? ""
+ let key = try limitedString(b, "key", max: 400)
+ return APIResponse.json(try VoiceRemote.saveLocal(base: base, model: model, voice: voice, key: key))
+ }
+
+ private func localProbe(_ c: RouteContext) async throws -> APIResponse {
+ let b = try c.json()
+ let base = try limitedString(b, "base", max: 200, required: true) ?? ""
+ return APIResponse.json(try await VoiceRemote.probeLocal(base))
+ }
+
+ private func onlineKey(_ c: RouteContext) throws -> APIResponse {
+ let b = try c.json()
+ let key = try limitedString(b, "key", max: 400, required: true) ?? ""
+ try VoiceRemote.setOnlineKey(key)
+ return APIResponse.json(VoiceRemote.onlineStatus())
+ }
+
+ // MARK: speaking
+
+ static var outDir: URL {
+ let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ let u = caches.appendingPathComponent("Voice", isDirectory: true).appendingPathComponent("out", isDirectory: true)
+ try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)
+ return u
+ }
+
+ @discardableResult
+ static func sweep(now: Date = Date()) -> Int {
+ let limit = now.timeIntervalSince1970 - keepSeconds
+ let dir = outDir
+ var gone = 0
+ for n in EngineFS.names(dir) {
+ let u = dir.appendingPathComponent(n)
+ if EngineFS.isFile(u), let st = EngineFS.stat(u), st.modified < limit {
+ EngineFS.remove(u)
+ gone += 1
+ }
+ }
+ return gone
+ }
+
+ private func speak(_ c: RouteContext) async throws -> APIResponse {
+ let b = try c.json()
+ let engine = try b.optString("engine") ?? "builtin"
+ guard let raw = try b.optString("text") else { throw EngineError(422, "Field required: text") }
+ if raw.isEmpty { throw EngineError(422, "String should have at least 1 character: text") }
+ if EngineText.length(raw) > VoiceRoutes.maxText {
+ throw EngineError(422, "String should have at most \(VoiceRoutes.maxText) characters: text")
+ }
+ let voice = try b.optString("voice") ?? ""
+ let model = try b.optString("model") ?? ""
+ var speed = 1.0
+ if let s = b.dict["speed"], !(s is NSNull) {
+ guard let n = s as? NSNumber else { throw EngineError(422, "Input should be a valid number: speed") }
+ speed = n.doubleValue
+ }
+ if !(speed >= 0.5 && speed <= 2.0) { throw EngineError(422, "Input should be between 0.5 and 2.0: speed") }
+ if !VoiceRoutes.engines.contains(engine) { throw EngineError(422, "There is no voice engine named \(engine).") }
+ let text = EngineText.strip(raw)
+ if text.isEmpty { throw EngineError(422, "There is no text to speak.") }
+ VoiceRoutes.sweep()
+ let spoken: VoiceRemote.Spoken
+ switch engine {
+ case "local": spoken = try await VoiceRemote.speakLocal(text: text, voice: voice, model: model, speed: speed)
+ case "online": spoken = try await VoiceRemote.speakOnline(text: text, voice: voice, model: model)
+ default: throw EngineError(409, VoiceRoutes.noBuiltin)
+ }
+ guard let suffix = VoiceRoutes.ext[spoken.mime], !spoken.audio.isEmpty else {
+ throw EngineError(502, "The voice answered with something that is not a sound.")
+ }
+ let sid = EngineText.hex(32)
+ let dir = VoiceRoutes.outDir
+ let info: [String: Any] = [
+ "id": sid, "mime": spoken.mime, "engine": engine, "voice": spoken.voice.isEmpty ? voice : spoken.voice,
+ "seconds": NSNull(), "cues": [[String: Any]](), "text": text, "bytes": spoken.audio.count,
+ ]
+ do {
+ try EngineFS.atomicWrite(spoken.audio, to: dir.appendingPathComponent(sid + suffix))
+ try EngineFS.atomicWrite(EngineJSON.encode(info), to: dir.appendingPathComponent(sid + ".json"))
+ } catch {
+ throw EngineError(500, "The spoken sound could not be kept for the window.")
+ }
+ return APIResponse.json(info, status: 201)
+ }
+
+ private func sound(_ sid: String) throws -> (URL, String) {
+ if !EngineText.matches("^[0-9a-f]{32}$", sid) { throw EngineError(404, VoiceRoutes.noSound) }
+ let dir = VoiceRoutes.outDir
+ guard let info = EngineJSON.readObject(dir.appendingPathComponent(sid + ".json")),
+ let mime = info["mime"] as? String, let suffix = VoiceRoutes.ext[mime] else {
+ throw EngineError(404, VoiceRoutes.noSound)
+ }
+ let path = dir.appendingPathComponent(sid + suffix)
+ if !EngineFS.isFile(path) { throw EngineError(404, VoiceRoutes.noSound) }
+ return (path, mime)
+ }
+
+ private func audio(_ c: RouteContext) throws -> APIResponse {
+ let (path, mime) = try sound(c.param("sid"))
+ guard let data = try? Data(contentsOf: path, options: .mappedIfSafe) else { throw EngineError(404, VoiceRoutes.noSound) }
+ return APIResponse.data(data, contentType: mime)
+ }
+
+ private func audioDrop(_ c: RouteContext) throws -> APIResponse {
+ let sid = c.param("sid")
+ let (path, _) = try sound(sid)
+ EngineFS.remove(path)
+ EngineFS.remove(VoiceRoutes.outDir.appendingPathComponent(sid + ".json"))
+ return APIResponse.json(["removed": true])
+ }
+}
diff --git a/setup/api_contract_check b/setup/api_contract_check
index cc4806b..dcbbf61 100755
--- a/setup/api_contract_check
+++ b/setup/api_contract_check
@@ -15,7 +15,6 @@ have: ffmpeg, a socket server, or a folder dialog onto the file system.
/api/files/stat watches a linked SVG by its path; the iPad picks the file again instead
/api/files/source reads a linked SVG by its path; the iPad picks the file again instead
/api/video-tools* finds, downloads and removes ffmpeg; the iPad encodes with its own video encoders
- /api/voice/* AI voices run a Python runtime, a voice app on this computer or the keychain; off on iPad
/api/agents*, /api/agent/*, /api/terminal*, /api/mcp/*, /mcp
outside agents and the terminal panel are desktop only
/api/window/* the window key guards a loopback server other programs can reach; the iPad's scheme
@@ -25,6 +24,7 @@ Everything else is required.
How routes are found in Swift:
table.add("GET", "/library/{name}") exact: the method and the path are written out
+ addAsync("POST", "/voice/speak") exact as well: a group's own list of routes that wait (VoiceRoutes)
a group that parses request.path by hand (prefix "/jobs" and tests such as rest[1] == "audio"): matched by
heuristic, shown as "~" in the lists: the group's prefix, every literal segment of the route and its method
must all appear in the group's file.
@@ -54,7 +54,6 @@ DESKTOP_ONLY = [
("*", "/api/terminal"),
("*", "/api/terminal/*"),
("*", "/api/mcp/*"),
- ("*", "/api/voice/*"),
("*", "/api/video-tools"),
("*", "/api/video-tools/*"),
("*", "/api/window/*"),
@@ -78,7 +77,7 @@ def is_desktop_only(method: str, path: str) -> bool:
return False
-ADD = re.compile(r'\.add\(\s*"([A-Za-z]+)"\s*,\s*"([^"]+)"')
+ADD = re.compile(r'(?:\.add|\baddAsync)\(\s*"([A-Za-z]+)"\s*,\s*"([^"]+)"')
PREFIX = re.compile(r'\bprefix\s*=\s*"(/[^"]*)"')
FIRST = re.compile(r'parts\.first\s*==\s*"([^"]+)"')
From 59c7bfeb995ffc2544e0c7eccfed7bf7ad4b5591 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sat, 28 Nov 2026 14:18:17 -0500
Subject: [PATCH 3/7] feat(ipad): AI Voice and listening in the interface on
iPad, touch targets for the new panels, an upright Timeline top row, Walk To
Here by touch and hold
---
frontend/src/app/app.ts | 14 +++++++++---
frontend/src/styles/ipad-window.css | 30 ++++++++++++++++++++++++++
frontend/src/ui/ai-voice-panel.ts | 31 ++++++++++++++++++++-------
frontend/src/ui/subtitles-panel.ts | 33 +++++++++++++++++++++++------
4 files changed, 91 insertions(+), 17 deletions(-)
diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts
index 095b30d..d584a28 100644
--- a/frontend/src/app/app.ts
+++ b/frontend/src/app/app.ts
@@ -226,13 +226,21 @@ export function startApp(): void {
engine.select([id]);
commands.run('character.walk-here');
});
+ // iPad: a touch and hold opens the menu, but its touch already changed the selection when it went down
+ let touchedFrom: { id: string | null; at: number } | null = null;
+ if (platform.kind === 'ipad') stage.root.addEventListener('pointerdown', (e) => {
+ if (e.pointerType !== 'mouse') touchedFrom = { id: selectedCharacter(engine)?.id ?? null, at: performance.now() };
+ }, true);
stage.nav.onContext = (x, y) => {
lastContext = { x, y };
// over content, the right-click is about that content: select it and open its menu; over empty Stage, the Stage's own
const hit = stage?.contentAt(x, y) ?? null;
- const was = selectedCharacter(engine);
- walker = hit && was && was.id !== hit ? was.id : null;
+ const held = touchedFrom && performance.now() - touchedFrom.at < 2000 ? touchedFrom.id : undefined;
+ touchedFrom = null;
+ const was = held === undefined ? selectedCharacter(engine)?.id ?? null : held;
+ walker = hit && was && was !== hit ? was : null;
if (hit) { if (!engine.selection.content.includes(hit)) engine.select([hit]); contentMenu.open(x, y); return; }
+ if (held && !selectedCharacter(engine) && engine.movie && findContent(engine.movie, held)) engine.select([held]);
stageMenu.setItems(['character.walk-here', '-', 'stage-options', 'stage-background', '-', 'stage-fit', 'stage-zoom-100', '-', 'stage-timecode', 'stage-fullscreen']); stageMenu.openAt(x, y); };
const newMovie = new NewMovieDialog(engine);
// like New: the movie opens unnamed and the library adopts it under a free "Untitled Movie" name
@@ -720,7 +728,7 @@ export function startApp(): void {
{ id: 'import-video', label: 'Video...', icon: 'video', enabled: has, run: () => pickFor('video/*') },
{ id: 'import-audio', label: 'Audio...', icon: 'audio', enabled: has, run: () => pickFor('audio/*,.flac,.ogg,.opus,.m4a,.aif,.aiff,.caf,.ac3,.mp2') },
{ id: 'record-audio', label: 'Record sound...', icon: 'audio', enabled: has, run: () => { aiVoice.close(); subtitlesPanel.close(); voicePanel.show(); } },
- { id: 'ai-voice', label: 'AI Voice...', icon: 'audio', enabled: () => has() && platform.kind !== 'ipad', run: () => { voicePanel.close(); subtitlesPanel.close(); aiVoice.show(); } },
+ { id: 'ai-voice', label: 'AI Voice...', icon: 'audio', enabled: () => has(), run: () => { voicePanel.close(); subtitlesPanel.close(); aiVoice.show(); } },
{ id: 'subtitles', label: 'Subtitles...', icon: 'text', enabled: has, run: () => { voicePanel.close(); aiVoice.close(); subtitlesPanel.show(); } },
{ id: 'sound-card', label: 'Sound options...', enabled: () => engine.selected.some((c) => c.kind === 'audio'), run: () => soundCard.show() },
{ id: 'import-file', label: 'File...', icon: 'upload', enabled: has, run: () => pickFor(MEDIA_ACCEPT) },
diff --git a/frontend/src/styles/ipad-window.css b/frontend/src/styles/ipad-window.css
index babc785..c4e44a2 100644
--- a/frontend/src/styles/ipad-window.css
+++ b/frontend/src/styles/ipad-window.css
@@ -15,6 +15,36 @@ html.is-ipad body {
html.fm-kb-open .cv-scrim { padding-bottom: var(--fm-kb-inset, 0px); box-sizing: border-box; }
html.fm-kb-open .cv-dialog { max-height: calc(100vh - 64px - var(--fm-kb-inset, 0px)); }
+/* The Build panel, the scene strip and the cards of 0.32.0 to 0.37.0 size their controls from the --ctl tokens: on
+ iPad those read as a finger's target inside them, as gestures.css does for the older controls. */
+html.is-ipad :is(.fm-build, .fm-scenes, .fm-aiv, .fm-sub, .fm-ms-trks, .fm-ms-bg) {
+ --ctl-sm: var(--touch-target);
+ --ctl-md: var(--touch-target);
+ --ctl: var(--touch-target);
+}
+html.is-ipad .fm-props-chip { min-inline-size: var(--touch-target); }
+/* the Character Builder's view switch and Flip above its preview */
+html.is-ipad .fm-cb-viewbar { block-size: auto; min-block-size: var(--touch-target); }
+html.is-ipad :is(.fm-cb-views button, .fm-cb-flip) { justify-content: center; min-inline-size: var(--touch-target); min-block-size: var(--touch-target); }
+html.is-ipad :is(.fm-aiv-x, .fm-sub-x) { display: inline-flex; align-items: center; justify-content: center; min-inline-size: var(--touch-target); min-block-size: var(--touch-target); }
+html.is-ipad .fm-aiv-link { min-block-size: var(--touch-target); }
+/* with 44 px rows the AI Voice card outgrows a landscape iPad's room above its bottom edge: it scrolls inside that room,
+ as the Subtitles card does */
+html.is-ipad .fm-aiv { max-block-size: calc(100vh - var(--space-4) * 2 - var(--cv-row-h) * 5.5); }
+/* the AI Voice and Subtitles cards stand above the on-screen keyboard while it is up */
+html.fm-kb-open.is-ipad :is(.fm-aiv, .fm-sub) { inset-block-end: calc(var(--fm-kb-inset, 0px) + var(--space-2)); max-block-size: calc(100vh - var(--fm-kb-inset, 0px) - var(--space-6)); }
+
+/* The Timeline's head row with 44 px buttons runs out of room before the window is compact (an upright iPad): the
+ side columns take what they need and the level meter goes, as under 720 px. The Timeline is measured, not the
+ window, so an open Build panel counts. */
+html.is-ipad .fm-timeline { container: fm-tl / inline-size; }
+@container fm-tl (max-width: 979px) {
+ html.is-ipad .fm-transport { grid-template-columns: auto minmax(0, 1fr) auto; }
+ html.is-ipad .fm-transport-mid { justify-content: center; }
+ html.is-ipad .fm-master-meter { display: none; }
+ html.is-ipad .fm-frame-readout { min-inline-size: 0; }
+}
+
/* The compact windows: under 720 px the layout in shell.css already turns the panels into sheets; this keeps the
Timeline's bars and the status bar from running into each other. */
@media (max-width: 719px) {
diff --git a/frontend/src/ui/ai-voice-panel.ts b/frontend/src/ui/ai-voice-panel.ts
index 4146853..e7c4b76 100644
--- a/frontend/src/ui/ai-voice-panel.ts
+++ b/frontend/src/ui/ai-voice-panel.ts
@@ -9,8 +9,15 @@ import { confirmAction } from './dialogs';
import { el, patchList, q, setClass, setDisabled, setHidden, setStyleVar, setText, setValue } from './dom';
import { enhanceSelect } from './dropdown';
import { t } from './i18n';
+import { platform } from '../platform';
import '../styles/ai-voice.css';
+// the built-in voice is a Python runtime the iPad cannot run: there the offline voice is a speech server on the network
+const IPAD = platform.kind === 'ipad';
+const KEY_NOTE = IPAD
+ ? 'Your own ElevenLabs key. It is kept in this iPad\'s keychain and sent only to that service.'
+ : 'Your own ElevenLabs key. It is kept in this computer\'s keychain and sent only to that service.';
+
type Tab = 'offline' | 'online';
type Source = 'builtin' | 'local';
@@ -26,8 +33,8 @@ const X = '
-
+
@@ -120,10 +120,10 @@
- **Perform:** drag a block on the Stage while the movie plays and the gesture becomes keys at the movie's frame rate.
- **Characters:** build one in the Character Builder by choosing a kind, body, face, hair and outfit, start from one of 26 original starter characters, or open an SVG with one group per body part. Every character has named parts, pivots and parenting, and a built one has a part for every joint, from hip and forearm to shin, foot, eyes, brows, hair and tail, with a mouth ready for lip-sync. Save it to the Characters library, apply the 12 starter actions or your own, change a built one again with Edit in Character Builder and keep its animation, and send any character to a vector app and back, where it updates by part name and keeps its animation. A built character turns to the front, three-quarter, side or back view and can walk to a spot. Ten starter scenes and 49 props are included, and you can save your own scenes.
- **Agents:** an MCP server at `/mcp` with a small core tool list, and a terminal panel for Claude Code, Codex, Cursor and Antigravity. A change waits for your yes in the window unless you allow agents; see [`.docs/wiki/Agents.md`](.docs/wiki/Agents.md).
-- **AI Voice:** type what to say and the spoken sound lands on the Timeline like any sound, ready for fades, pan, lip-sync and export. A built-in offline voice (Kokoro, 54 voices, set up once from the card), a voice app on this computer for a cloned voice, or an online voice with your own key. Each spoken sound keeps its words and sentence timing, and adds its subtitles by itself. See `docs/MANUAL.md`.
-- **Subtitles:** tick one box and the lines are drawn on the Stage and in every export, in one look for all of them: font, size, position, color and a dark band. AI voices add theirs when they speak; for a recording or a sound file, listening runs on this computer with its own model, a one-time download of about 80 MB, and sends nothing anywhere. Edit the lines in the card, and import or export `.srt` and `.vtt`. See `docs/MANUAL.md`.
+- **AI Voice:** type what to say and the spoken sound lands on the Timeline like any sound, ready for fades, pan, lip-sync and export. A built-in offline voice (Kokoro, 54 voices, set up once from the card), a voice app on this computer for a cloned voice, or an online voice with your own key. On iPad: the online voice, or a speech server on a computer on the same network; the built-in voice needs a computer. Each spoken sound keeps its words and sentence timing, and adds its subtitles by itself. See `docs/MANUAL.md`.
+- **Subtitles:** tick one box and the lines are drawn on the Stage and in every export, in one look for all of them: font, size, position, color and a dark band. AI voices add theirs when they speak; for a recording or a sound file, listening runs on this computer with its own model, a one-time download of about 80 MB, and sends nothing anywhere (on iPad it uses the iPad's own speech recognition instead, with no download). Edit the lines in the card, and import or export `.srt` and `.vtt`. See `docs/MANUAL.md`.
- **In your language:** the interface ships in 30 languages, right to left included, with a manual on F1.
-- **iPad:** the iPad app in `ios/` wraps the same interface in a Swift shell with Apple Pencil, Files and AVFoundation export. It is built and runs on an iPad Pro 13-inch (M5) with Apple Pencil Pro on iPadOS 26.3, where drawing, squeeze, barrel roll and hover were checked. It is a beta that you build yourself on a Mac with Xcode: see [`docs/ios/BUILD.md`](docs/ios/BUILD.md). An App Store version is planned only if the iPad app gets real adoption.
+- **iPad:** the iPad app in `ios/` wraps the same interface in a Swift shell with Apple Pencil, Files and AVFoundation export. It is built and runs on an iPad Pro 13-inch (M5) with Apple Pencil Pro on iPadOS 26.3, where drawing, squeeze, barrel roll and hover were checked. Version 0.38.0 adds AI Voice, listening for subtitles and My scenes to the iPad app; these are new there and wait for their check on the device (the list is in the build guide). The iPad app has no built-in voice, no Save to a chosen folder in Export, no outside agents or terminal panel and no Pen Link. It is a beta that you build yourself on a Mac with Xcode: see [`docs/ios/BUILD.md`](docs/ios/BUILD.md). An App Store version is planned only if the iPad app gets real adoption.
## Download
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 2d93b0c..978180b 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -1 +1 @@
-__version__ = "0.37.0"
+__version__ = "0.38.0"
diff --git a/docs/api-contract.json b/docs/api-contract.json
index 145f0cd..1ececd8 100644
--- a/docs/api-contract.json
+++ b/docs/api-contract.json
@@ -1,5 +1,5 @@
{
-"info":{"title":"formmorpheus","version":"0.37.0"},
+"info":{"title":"formmorpheus","version":"0.38.0"},
"openapi":"3.1.0",
"paths":{
"/api/agent/claude/open":{"post":{"operationId":"claude_open_api_agent_claude_open_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ClaudeBody"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":true,"title":"Response Claude Open Api Agent Claude Open Post","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":"Claude Open","tags":["terminal"]}},
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 1e81311..82c895e 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formmorpheus",
- "version": "0.37.0",
+ "version": "0.38.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formmorpheus",
- "version": "0.37.0",
+ "version": "0.38.0",
"license": "Apache-2.0",
"dependencies": {
"@fontsource/anton": "5.3.0",
diff --git a/frontend/package.json b/frontend/package.json
index c763b82..1b0b48b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "formmorpheus",
"private": true,
- "version": "0.37.0",
+ "version": "0.38.0",
"description": "FormMorpheus · animation studio in the Form family",
"license": "Apache-2.0",
"type": "module",
diff --git a/frontend/src/version.ts b/frontend/src/version.ts
index b209abe..655668e 100644
--- a/frontend/src/version.ts
+++ b/frontend/src/version.ts
@@ -1 +1 @@
-export const VERSION = '0.37.0';
+export const VERSION = '0.38.0';
diff --git a/ios/project.yml b/ios/project.yml
index 0684f5a..dbcecc0 100644
--- a/ios/project.yml
+++ b/ios/project.yml
@@ -27,7 +27,7 @@ settings:
TARGETED_DEVICE_FAMILY: "2"
SUPPORTS_MACCATALYST: NO
SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD: NO
- MARKETING_VERSION: "0.37.0"
+ MARKETING_VERSION: "0.38.0"
CURRENT_PROJECT_VERSION: "1"
configs:
Debug:
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 30a7c64..3bc82de 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1047,7 +1047,7 @@ dependencies = [
[[package]]
name = "formmorpheus"
-version = "0.37.0"
+version = "0.38.0"
dependencies = [
"gtk",
"objc2",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index c2435c2..93b310c 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formmorpheus"
-version = "0.37.0"
+version = "0.38.0"
description = "FormMorpheus desktop shell"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index f0e83b1..86916cb 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "FormMorpheus",
- "version": "0.37.0",
+ "version": "0.38.0",
"identifier": "ai.nodemode.formmorpheus",
"build": {
"frontendDist": "../frontend/dist"