Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(podcast): synthesize_podcast, script-to-speech via the TTS API
Durganshu Mishrad4cf98210188
diff --git a/app/src/main/java/com/gotcha/data/GotchaStorage.kt b/app/src/main/java/com/gotcha/data/GotchaStorage.ktindex a629e67..d4ea5ba 100644--- a/app/src/main/java/com/gotcha/data/GotchaStorage.kt+++ b/app/src/main/java/com/gotcha/data/GotchaStorage.kt@@ -15,6 +15,7 @@ import java.io.IOException* Single source of truth for every path Gotcha reads or writes under shared* storage.*/+@Suppress("TooManyFunctions") // one accessor per well-known directory, plus the MediaStore plumbingobject GotchaStorage {private var overrideRootPath: String? = null@@ -41,6 +42,7 @@ object GotchaStorage {fun archiveRoot(): File = File(root(), "old_chats")fun screenshotsRoot(): File = File(root(), "Screenshots")fun downloadsRoot(): File = File(root(), "Downloads")+ fun podcastsRoot(): File = File(root(), "Podcasts")/*** Non-alphanumeric runs collapse to a single '-'; leading/trailing '-' trimmed;diff --git a/app/src/main/java/com/gotcha/tools/PodcastAudio.kt b/app/src/main/java/com/gotcha/tools/PodcastAudio.ktnew file mode 100644index 0000000..dba4d99--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/PodcastAudio.kt@@ -0,0 +1,143 @@+package com.gotcha.tools++import java.io.File++/**+ * Pure helpers for podcast synthesis: script chunking and WAV header parsing.+ *+ * Kept free of Android types so the logic that decides how a script is split+ * and how long the synthesized audio actually is can be tested on the JVM.+ * [PodcastTool] owns everything with side effects.+ */+object PodcastAudio {++ /** RIFF header (12) + minimal fmt chunk (24) + data chunk header (8). */+ private const val MIN_WAV_BYTES = 44+ private const val RIFF_HEADER_BYTES = 12+ private const val CHUNK_HEADER_BYTES = 8+ private const val FMT_CHUNK_MIN_BYTES = 16+ private const val MILLIS_PER_SECOND = 1000L++ private val SENTENCE_BREAK = Regex("(?<=[.!?])\\s+")++ /**+ * Splits [text] into chunks of at most [maxChars], breaking at sentence+ * boundaries so the TTS engine never receives a half sentence — a cut+ * mid-sentence is audible as a dropped word at every segment join.+ *+ * A single sentence longer than [maxChars] (rare, but a model can produce+ * one) is split at the last word boundary that fits, and as a hard cut only+ * when even one word does not fit.+ */+ fun chunk(text: String, maxChars: Int): List<String> {+ require(maxChars > 0) { "maxChars must be positive" }+ val sentences = text.trim().split(SENTENCE_BREAK).filter { it.isNotBlank() }+ val chunks = mutableListOf<String>()+ val current = StringBuilder()+ for (sentence in sentences) {+ for (piece in splitOversize(sentence, maxChars)) {+ if (current.isNotEmpty() && current.length + 1 + piece.length > maxChars) {+ chunks.add(current.toString())+ current.setLength(0)+ }+ if (current.isNotEmpty()) current.append(' ')+ current.append(piece)+ }+ }+ if (current.isNotEmpty()) chunks.add(current.toString())+ return chunks+ }++ /** [sentence] as-is when it fits, otherwise word-boundary pieces of at most [maxChars]. */+ private fun splitOversize(sentence: String, maxChars: Int): List<String> {+ if (sentence.length <= maxChars) return listOf(sentence)+ val pieces = mutableListOf<String>()+ var rest = sentence+ while (rest.length > maxChars) {+ val cut = rest.lastIndexOf(' ', maxChars).takeIf { it > 0 } ?: maxChars+ pieces.add(rest.take(cut).trim())+ rest = rest.substring(cut).trim()+ }+ if (rest.isNotEmpty()) pieces.add(rest)+ return pieces+ }++ /**+ * What a WAV header says about its audio. Parsed from the file itself+ * rather than assumed, because TTS providers return whatever sample rate+ * they like (16, 24 or 44.1 kHz have all been seen) and a guessed rate+ * would make every duration estimate off by that ratio.+ */+ data class WavInfo(+ val sampleRate: Int,+ val channels: Int,+ val bitsPerSample: Int,+ val byteRate: Int,+ val dataBytes: Long+ ) {+ val durationMs: Long get() = if (byteRate > 0) dataBytes * MILLIS_PER_SECOND / byteRate else 0L+ }++ /**+ * Parses [bytes] as a RIFF/WAVE file by walking its chunks — the fmt and+ * data chunks are not at fixed offsets in every real-world WAV (a LIST or+ * fact chunk can precede them). Returns null for anything that is not a+ * well-formed WAV, which is how [PodcastTool] detects a TTS endpoint that+ * answered with JSON, MP3 or an HTML error page instead of the requested+ * WAV.+ */+ @Suppress("ReturnCount")+ fun wavInfo(bytes: ByteArray): WavInfo? {+ if (bytes.size < MIN_WAV_BYTES) return null+ if (!bytes.ascii(0, "RIFF") || !bytes.ascii(8, "WAVE")) return null++ var offset = RIFF_HEADER_BYTES+ var info: WavInfo? = null+ var dataBytes = -1L+ while (offset + CHUNK_HEADER_BYTES <= bytes.size) {+ val chunkSize = bytes.leInt(offset + 4).toLong() and 0xFFFFFFFFL+ when {+ bytes.ascii(offset, "fmt ") && chunkSize >= FMT_CHUNK_MIN_BYTES &&+ offset + CHUNK_HEADER_BYTES + FMT_CHUNK_MIN_BYTES <= bytes.size -> {+ val body = offset + CHUNK_HEADER_BYTES+ info = WavInfo(+ sampleRate = bytes.leInt(body + 4),+ channels = bytes.leShort(body + 2),+ bitsPerSample = bytes.leShort(body + 14),+ byteRate = bytes.leInt(body + 8),+ dataBytes = 0L+ )+ }+ bytes.ascii(offset, "data") -> {+ // A streamed WAV may declare a bogus size (0 or 0xFFFFFFFF);+ // what actually arrived is the honest answer.+ val remaining = (bytes.size - offset - CHUNK_HEADER_BYTES).toLong()+ dataBytes = if (chunkSize in 1..remaining) chunkSize else remaining+ }+ }+ // Chunks are word-aligned: an odd-sized chunk is padded by one byte.+ offset += CHUNK_HEADER_BYTES + chunkSize.toInt() + (chunkSize % 2).toInt()+ if (offset < 0) return null // overflow from a hostile size field+ }+ val fmt = info ?: return null+ if (dataBytes < 0 || fmt.byteRate <= 0 || fmt.sampleRate <= 0) return null+ return fmt.copy(dataBytes = dataBytes)+ }++ /** [wavInfo] for a file already on disk. */+ fun wavInfo(file: File): WavInfo? = runCatching { wavInfo(file.readBytes()) }.getOrNull()++ private fun ByteArray.ascii(offset: Int, expected: String): Boolean {+ if (offset + expected.length > size) return false+ return expected.withIndex().all { (i, c) -> this[offset + i] == c.code.toByte() }+ }++ private fun ByteArray.leShort(offset: Int): Int =+ (this[offset].toInt() and 0xFF) or ((this[offset + 1].toInt() and 0xFF) shl 8)++ private fun ByteArray.leInt(offset: Int): Int =+ (this[offset].toInt() and 0xFF) or+ ((this[offset + 1].toInt() and 0xFF) shl 8) or+ ((this[offset + 2].toInt() and 0xFF) shl 16) or+ ((this[offset + 3].toInt() and 0xFF) shl 24)+}diff --git a/app/src/main/java/com/gotcha/tools/PodcastTool.kt b/app/src/main/java/com/gotcha/tools/PodcastTool.ktnew file mode 100644index 0000000..22d0e03--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/PodcastTool.kt@@ -0,0 +1,346 @@+package com.gotcha.tools++import android.content.Context+import com.gotcha.audio.AudioApi+import com.gotcha.audio.AudioModel+import com.gotcha.audio.AudioProvider+import com.gotcha.audio.ModelCategory+import com.gotcha.audio.SpeechTextSanitizer+import com.gotcha.data.GotchaStorage+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import kotlinx.coroutines.ensureActive+import java.io.File+import kotlin.coroutines.coroutineContext++/**+ * Turns a written script into a spoken audio file — a single-voice podcast.+ *+ * The synthesis reuses the same OpenAI-compatible `/audio/speech` endpoint the+ * voice features already talk through, but deliberately not via+ * [com.gotcha.audio.TtsEngine]: that class is hardwired to play what it+ * fetches, while this one needs the raw WAV bytes on disk. The script is+ * sanitized exactly as spoken replies are, split at sentence boundaries (the+ * endpoint has input-length limits a whole script would blow through),+ * synthesized segment by segment into the cache dir, and joined on-device by+ * [MediaExport] into an `.m4a` under `Gotcha/Podcasts`.+ *+ * `.m4a` is the canonical output because it needs nothing beyond what ships in+ * the app. MP3 exists only through Termux's ffmpeg ([MediaConvertTool]), so a+ * requested `.mp3` quietly degrades to `.m4a` when Termux is unavailable — a+ * finished podcast in the wrong container beats no podcast.+ *+ * Requires an API-based TTS provider: Android's built-in engine has no+ * file-output path here. Only available to Operator (writes files).+ */+class PodcastTool(+ private val context: Context,+ private val loadSettings: () -> Settings = { SettingsRepository(context).load() },+ private val ttsBackendFactory: (baseUrl: String, apiKey: String) -> TtsBackend = { url, key ->+ ApiTtsBackend(AudioApi(url, key, timeoutSeconds = TTS_TIMEOUT_SECONDS))+ },+ private val mediaExport: MediaExport = MediaExport(context),+ private val mediaConvert: MediaConvertTool = MediaConvertTool(context),+ private val termuxUsable: () -> Boolean = { DeviceCapabilities.termuxUsable(context) }+) {++ /** The two calls synthesis needs from the TTS API, extracted for tests. */+ interface TtsBackend {+ fun listModels(): List<AudioModel>+ fun synthesize(text: String, model: String, voice: String): Result<ByteArray>+ }++ private class ApiTtsBackend(private val api: AudioApi) : TtsBackend {+ override fun listModels(): List<AudioModel> = api.listAudioModels()+ override fun synthesize(text: String, model: String, voice: String): Result<ByteArray> =+ api.synthesize(text, model, voice)+ }++ private val resolver = FileResolver(context)++ companion object {+ /**+ * Script ceiling. At a typical ~15 chars/second of speech this is+ * ~25 minutes of audio, safely inside [MAX_TOTAL_DURATION_MS] — the+ * cap that actually matters is on the audio, this one just refuses the+ * obviously hopeless script before any API spend.+ */+ const val MAX_SCRIPT_CHARS = 24_000++ /**+ * Per-request text limit. OpenAI-compatible speech endpoints cap+ * `input` around 4096 chars; staying well under leaves room for+ * providers that count differently.+ */+ const val MAX_CHUNK_CHARS = 3_000++ /** Same ceiling as media_edit's re-encode guard — assembly re-encodes everything. */+ const val MAX_TOTAL_DURATION_MS = MediaEditTool.MAX_REENCODE_DURATION_MS++ private const val TTS_TIMEOUT_SECONDS = 120L+ private const val FORMAT_M4A = "m4a"+ private const val FORMAT_MP3 = "mp3"++ /** Intermediate for the MP3 detour. Ends in `.m4a` so ffmpeg and the salvage rename both see AAC. */+ private const val TMP_SUFFIX = ".podcast-tmp.m4a"++ private const val ERROR_DETAIL_CHARS = 200+ }++ private sealed interface Resolved {+ data class Ok(val file: File) : Resolved+ data class Failed(val result: ToolResult) : Resolved+ }++ /** Everything one synthesis run carries between its stages. */+ private data class Job(+ val backend: TtsBackend,+ val text: String,+ val model: String,+ val voice: String,+ val tempDir: File,+ val destination: File,+ val wantMp3: Boolean,+ val baseName: String,+ val overwrite: Boolean,+ val degradeNote: String+ )++ @Suppress("ReturnCount", "LongParameterList")+ suspend fun synthesize(+ script: String,+ outputName: String,+ model: String? = null,+ voice: String? = null,+ format: String? = null,+ overwrite: Boolean = false+ ): ToolResult {+ val settings = loadSettings()+ credentialError(settings)?.let { return it }++ val requestedFormat = normaliseFormat(format, outputName) ?: return unsupportedFormat(format, outputName)+ val resolvedModel = (model ?: settings.ttsApiModel).trim()+ if (resolvedModel.isBlank()) return noModelConfigured()++ val text = SpeechTextSanitizer.sanitize(script)+ if (text.isBlank()) {+ return ToolResult.error(+ "The script is empty once markdown, code and emoji are stripped for speech. " ++ "Write the narration as plain prose and try again."+ )+ }+ if (text.length > MAX_SCRIPT_CHARS) {+ return ToolResult.error(+ "The script is ${text.length} characters; the limit is $MAX_SCRIPT_CHARS (~25 minutes of " ++ "speech). Split it into parts and synthesize each as its own file."+ )+ }++ val wantMp3 = requestedFormat == FORMAT_MP3 && termuxUsable()+ val degradeNote = if (requestedFormat == FORMAT_MP3 && !wantMp3) {+ " MP3 was requested, but that conversion runs through Termux's ffmpeg, which is not available on " ++ "this device — the podcast was written as .m4a instead, which plays everywhere on Android."+ } else {+ ""+ }+ val baseName = GotchaStorage.slugify(File(outputName).nameWithoutExtension)+ val extension = if (wantMp3) FORMAT_MP3 else FORMAT_M4A+ val destination = when (val r = resolveDestination(baseName, extension, overwrite)) {+ is Resolved.Failed -> return r.result+ is Resolved.Ok -> r.file+ }++ val backend = ttsBackendFactory(settings.effectiveTtsBaseUrl, settings.effectiveTtsApiKey)+ val resolvedVoice = resolveVoice(voice, settings, backend, resolvedModel)+ ?: return ToolResult.error(+ "No TTS voice is set and the API's voice list for '$resolvedModel' could not be fetched. " ++ "Pass voice explicitly, or ask the user to pick one in Settings → Speech."+ )++ val tempDir = File(context.cacheDir, "podcast_${System.currentTimeMillis()}")+ return try {+ produce(+ Job(+ backend = backend, text = text, model = resolvedModel, voice = resolvedVoice,+ tempDir = tempDir, destination = destination, wantMp3 = wantMp3,+ baseName = baseName, overwrite = overwrite, degradeNote = degradeNote+ )+ )+ } finally {+ tempDir.deleteRecursively()+ }+ }++ // ---- the pipeline ----++ @Suppress("ReturnCount")+ private suspend fun produce(job: Job): ToolResult {+ job.tempDir.mkdirs()+ val chunks = PodcastAudio.chunk(job.text, MAX_CHUNK_CHARS)+ val wavs = mutableListOf<File>()+ var totalMs = 0L+ for ((index, chunk) in chunks.withIndex()) {+ coroutineContext.ensureActive()+ val bytes = job.backend.synthesize(chunk, job.model, job.voice).getOrElse { e ->+ return ToolResult.error(+ "The TTS request failed on segment ${index + 1} of ${chunks.size}: " ++ "${e.message?.take(ERROR_DETAIL_CHARS) ?: "no detail"}. Nothing was written."+ )+ }+ val info = PodcastAudio.wavInfo(bytes) ?: return ToolResult.error(+ "The TTS endpoint returned something that is not WAV audio for segment ${index + 1}. " ++ "The model name or voice may be wrong for this provider — check them against the " ++ "provider's model list."+ )+ totalMs += info.durationMs+ if (totalMs > MAX_TOTAL_DURATION_MS) {+ return ToolResult.error(+ "The synthesized audio passed ${MediaTimeSpec.format(MAX_TOTAL_DURATION_MS)} before the " ++ "script was finished. Shorten the script or split it into parts."+ )+ }+ wavs += File(job.tempDir, "segment_%03d.wav".format(index)).apply { writeBytes(bytes) }+ }++ val m4aOut = if (job.wantMp3) {+ File(job.destination.parentFile, "${job.baseName}$TMP_SUFFIX").apply { delete() }+ } else {+ job.destination+ }+ assemble(wavs, job.tempDir, m4aOut)?.let { return it }++ val (finalFile, conversionNote) = if (job.wantMp3) convertToMp3(m4aOut, job) else job.destination to ""+ GotchaStorage.publishToGallery(context, finalFile)+ return ToolResult.ok(+ "Created the podcast at '${finalFile.canonicalPath}' — ${MediaTimeSpec.format(totalMs)} of audio, " ++ "${resolver.formatSize(finalFile.length())}, synthesized as ${chunks.size} segment(s) with " ++ "voice '${job.voice}' and assembled on-device. It is visible in the phone's Files app under " ++ "Gotcha/Podcasts." + job.degradeNote + conversionNote+ )+ }++ /**+ * Joins the segment WAVs into [output] as AAC. Temp files skip+ * [FileResolver] on purpose: they live in the app's own cache, where a+ * permission check has nothing to say — the shared-storage checks already+ * ran on the final destination.+ */+ private suspend fun assemble(wavs: List<File>, tempDir: File, output: File): ToolResult? {+ output.parentFile?.mkdirs()+ if (wavs.size == 1) return mediaExport.run(input = wavs[0], output = output).failure()+ var inputs: List<File> = wavs+ var round = 0+ while (inputs.size > MediaEditTool.MAX_CONCAT_INPUTS) {+ inputs = inputs.chunked(MediaEditTool.MAX_CONCAT_INPUTS).mapIndexed { batchIndex, batch ->+ val partial = File(tempDir, "batch_${round}_$batchIndex.m4a")+ val outcome = if (batch.size == 1) {+ mediaExport.run(input = batch[0], output = partial)+ } else {+ mediaExport.concat(batch, partial)+ }+ outcome.failure()?.let { return it }+ partial+ }+ round+++ }+ return mediaExport.concat(inputs, output).failure()+ }++ /**+ * The Termux detour. A failure here does not fail the run: the synthesis+ * money is already spent and the audio is already good, so it is salvaged+ * as `.m4a` with a note saying what happened and how to finish the job.+ */+ private suspend fun convertToMp3(m4a: File, job: Job): Pair<File, String> {+ val result = mediaConvert.convert(m4a.absolutePath, job.destination.absolutePath, overwrite = job.overwrite)+ if (result.success) {+ m4a.delete()+ return job.destination to ""+ }+ val fallback = File(job.destination.parentFile, "${job.baseName}.$FORMAT_M4A")+ val kept = if ((job.overwrite || !fallback.exists()) && m4a.renameTo(fallback)) fallback else m4a+ return kept to " The MP3 conversion step failed " ++ "(${result.message.take(ERROR_DETAIL_CHARS)}) — the finished audio was kept as '${kept.name}'; " ++ "media_convert can turn it into an MP3 once that is fixed."+ }++ // ---- validation ----++ private fun credentialError(settings: Settings): ToolResult? {+ if (!settings.ttsProvider.isApiBased()) {+ return ToolResult.error(+ "The Text-to-Speech provider is '${settings.ttsProvider.label}', which can only speak aloud — " ++ "it cannot write audio to a file. Ask the user to set Settings → Speech → Text-to-Speech " ++ "to Samosa AI or External API, then try again."+ )+ }+ if (settings.effectiveTtsBaseUrl.isBlank()) {+ return ToolResult.error(+ if (settings.ttsProvider == AudioProvider.SAMOSA_AI) {+ "TTS is set to Samosa AI but there is no active session. Ask the user to sign in again " ++ "in Settings, then retry."+ } else {+ "TTS is set to External API but no base URL is configured. Ask the user to complete " ++ "Settings → Speech → Text-to-Speech, then retry."+ }+ )+ }+ return null+ }++ /** The format arg wins; a recognisable extension on output_name is honoured when the arg is absent. */+ private fun normaliseFormat(format: String?, outputName: String): String? {+ val requested = format?.trim()?.lowercase().takeUnless { it.isNullOrBlank() }+ ?: File(outputName).extension.trim().lowercase().ifBlank { FORMAT_M4A }+ return requested.takeIf { it == FORMAT_M4A || it == FORMAT_MP3 }+ }++ private fun unsupportedFormat(format: String?, outputName: String): ToolResult = ToolResult.error(+ "format '${format ?: File(outputName).extension}' is not supported — a podcast is written as 'm4a' " ++ "(the default, no setup needed) or 'mp3' (via Termux's ffmpeg). For other formats, create the " ++ ".m4a first and convert it with media_convert."+ )++ private fun noModelConfigured(): ToolResult = ToolResult.error(+ "No TTS model is configured. Pass model explicitly, or ask the user to pick one in " ++ "Settings → Speech → Text-to-Speech."+ )++ private fun resolveVoice(+ voiceArg: String?,+ settings: Settings,+ backend: TtsBackend,+ model: String+ ): String? {+ val explicit = (voiceArg ?: settings.ttsVoice).trim()+ if (explicit.isNotBlank()) return explicit+ val ttsModels = runCatching { backend.listModels() }.getOrDefault(emptyList())+ .filter { it.category == ModelCategory.TTS }+ return (ttsModels.firstOrNull { it.id == model } ?: ttsModels.firstOrNull())?.defaultVoice+ }++ @Suppress("ReturnCount")+ private fun resolveDestination(baseName: String, extension: String, overwrite: Boolean): Resolved {+ val target = File(GotchaStorage.podcastsRoot(), "$baseName.$extension")+ val file = when (val r = resolver.resolveForWrite(target.absolutePath)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Resolved.Failed(r.result)+ is FileResolver.ResolveResult.Error -> return Resolved.Failed(ToolResult.error(r.message))+ is FileResolver.ResolveResult.Ok -> r.file+ }+ resolver.checkWritePermission(file)?.let { return Resolved.Failed(it) }+ if (file.exists() && !overwrite) {+ return Resolved.Failed(+ ToolResult.error(+ "'${file.canonicalPath}' already exists. Pass overwrite=true to replace it, or choose a " ++ "different output_name."+ )+ )+ }+ file.parentFile?.let { parent ->+ if (!parent.exists() && !parent.mkdirs()) {+ return Resolved.Failed(ToolResult.error("Could not create '${parent.canonicalPath}'."))+ }+ }+ return Resolved.Ok(file)+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex d423783..43e7e11 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -19,6 +19,7 @@ object ToolCategories {private val backgroundTools = setOf("edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit", "media_convert",+ "synthesize_podcast","uninstall_app", "delete_calendar_event", "delete_alarm","delete_timer", "edit_alarm","toggle_wifi", "toggle_torch",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 895aeab..e73c3d7 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1441,6 +1441,74 @@ object ToolDefinitions {})+ val synthesizePodcast = tool(+ "synthesize_podcast",+ "Turn a written narration script into a spoken audio file — a single-voice podcast — saved under " ++ "Gotcha/Podcasts on shared storage, where the Files app can see it. Write the script yourself " ++ "first as plain prose (no markdown, no code; it will be read aloud verbatim), then pass it here. " ++ "Long scripts are synthesized in segments and joined on-device; ~25 minutes of speech is the " ++ "ceiling. Output is .m4a by default; format='mp3' converts through Termux's ffmpeg when Termux " ++ "is available and quietly falls back to .m4a when it is not. Needs an API-based TTS provider " ++ "(Samosa AI or External API) in Settings → Speech — Android's built-in TTS cannot write files, " ++ "and the error will say so.",+ schema {+ putJsonObject("properties") {+ putJsonObject("script") {+ put("type", "string")+ put(+ "description",+ "The full narration text, exactly as it should be spoken. Plain prose only — write " ++ "for the ear, not the eye."+ )+ }+ putJsonObject("output_name") {+ put("type", "string")+ put(+ "description",+ "Base name for the file, e.g. 'morning-news-digest'. It is slugified and written " ++ "under Gotcha/Podcasts; any directory part or extension is ignored except that " ++ "a '.mp3' extension selects the mp3 format."+ )+ }+ putJsonObject("model") {+ put("type", "string")+ put(+ "description",+ "TTS model id to use. Defaults to the model configured in Settings → Speech."+ )+ }+ putJsonObject("voice") {+ put("type", "string")+ put(+ "description",+ "Voice id from the TTS model's voice list. Defaults to the configured voice, then " ++ "to the model's own default."+ )+ }+ putJsonObject("format") {+ put("type", "string")+ put(+ "description",+ "'m4a' (default, works with no setup) or 'mp3' (needs Termux's ffmpeg; degrades to " ++ ".m4a with a note when unavailable)."+ )+ }+ putJsonObject("overwrite") {+ put("type", "boolean")+ put(+ "description",+ "Allow replacing an existing output file. Default false, which fails instead of " ++ "destroying a file the user may still need."+ )+ }+ }+ putJsonArray("required") {+ add("script")+ add("output_name")+ }+ }+ )+val edit = tool("edit","Replace exact text in a file, for surgical edits without rewriting it. oldString " +@@ -2674,6 +2742,8 @@ object ToolDefinitions {mediaEdit,// Audio format conversion via Termux ffmpeg (Operator only)mediaConvert,+ // Script-to-speech podcast synthesis (Operator only)+ synthesizePodcast,// Content search and file discoveryglob, grep,// Web search + fetchdiff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex d07b1ae..bb15df1 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -65,6 +65,7 @@ class ToolExecutor(private val pdfTool = PdfTool(appContext)private val mediaEditTool = MediaEditTool(appContext)private val mediaConvertTool = MediaConvertTool(appContext)+ private val podcastTool = PodcastTool(appContext)private val globTool = GlobTool(appContext)private val grepTool = GrepTool(appContext)private val accessibilityTool = AccessibilityTool(appContext)@@ -252,6 +253,14 @@ class ToolExecutor(bitrate = args.requireString("bitrate"),overwrite = args.requireBoolean("overwrite") ?: false)+ "synthesize_podcast" -> podcastTool.synthesize(+ script = args.requireString("script") ?: return missing("script"),+ outputName = args.requireString("output_name") ?: return missing("output_name"),+ model = args.requireString("model"),+ voice = args.requireString("voice"),+ format = args.requireString("format"),+ overwrite = args.requireBoolean("overwrite") ?: false+ )"open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))"set_brightness" -> systemTool.setBrightness(args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")diff --git a/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.ktnew file mode 100644index 0000000..9fdcd4b--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/PodcastAudioTest.kt@@ -0,0 +1,159 @@+package com.gotcha.tools++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.ByteArrayOutputStream++/**+ * The two pure halves of podcast synthesis: how a script is split for the TTS+ * API, and how the returned WAV bytes are measured. Both decide user-visible+ * outcomes — a bad split is audible at every join, and a misread header makes+ * the duration guard let a two-hour script through.+ */+class PodcastAudioTest {++ // ---- chunking ----++ @Test+ fun `a short script stays in one chunk`() {+ assertEquals(listOf("One sentence. And another."), PodcastAudio.chunk("One sentence. And another.", 100))+ }++ @Test+ fun `chunks break at sentence boundaries, never inside one`() {+ val text = "First sentence here. Second sentence here. Third sentence here."+ val chunks = PodcastAudio.chunk(text, 45)+ assertEquals(listOf("First sentence here. Second sentence here.", "Third sentence here."), chunks)+ }++ @Test+ fun `no chunk exceeds the limit`() {+ val text = (1..50).joinToString(" ") { "Sentence number $it is right here." }+ val chunks = PodcastAudio.chunk(text, 120)+ assertTrue(chunks.isNotEmpty())+ chunks.forEach { assertTrue("'${it.take(40)}…' is ${it.length} chars", it.length <= 120) }+ }++ @Test+ fun `nothing is lost or reordered by chunking`() {+ val text = (1..30).joinToString(" ") { "Sentence $it ends now." }+ val rejoined = PodcastAudio.chunk(text, 60).joinToString(" ")+ assertEquals(text, rejoined)+ }++ @Test+ fun `a single sentence longer than the limit is split at word boundaries`() {+ val words = (1..40).joinToString(" ") { "word$it" }+ val chunks = PodcastAudio.chunk(words, 50)+ assertTrue(chunks.size > 1)+ chunks.forEach { assertTrue(it.length <= 50) }+ assertEquals(words, chunks.joinToString(" "))+ }++ @Test+ fun `an unbroken run longer than the limit is hard-cut rather than looping forever`() {+ val chunk = PodcastAudio.chunk("a".repeat(120), 50)+ assertTrue(chunk.size >= 3)+ chunk.forEach { assertTrue(it.length <= 50) }+ }++ @Test+ fun `blank input produces no chunks`() {+ assertEquals(emptyList<String>(), PodcastAudio.chunk(" \n ", 100))+ }++ // ---- WAV parsing ----++ @Test+ fun `a canonical PCM WAV parses to its real duration`() {+ // 1 second of 24kHz mono 16-bit: 48000 data bytes.+ val wav = buildWav(sampleRate = 24_000, channels = 1, bitsPerSample = 16, dataBytes = 48_000)+ val info = PodcastAudio.wavInfo(wav)!!+ assertEquals(24_000, info.sampleRate)+ assertEquals(1, info.channels)+ assertEquals(16, info.bitsPerSample)+ assertEquals(1000L, info.durationMs)+ }++ @Test+ fun `sample rate is read, not assumed`() {+ // The same byte count at 44.1kHz stereo is a much shorter clip; a+ // hardcoded 24kHz-mono assumption would report ~4x the real duration.+ val wav = buildWav(sampleRate = 44_100, channels = 2, bitsPerSample = 16, dataBytes = 176_400)+ assertEquals(1000L, PodcastAudio.wavInfo(wav)!!.durationMs)+ }++ @Test+ fun `chunks before fmt and data are walked over, not tripped over`() {+ val wav = buildWav(+ sampleRate = 16_000,+ channels = 1,+ bitsPerSample = 16,+ dataBytes = 32_000,+ leadingJunkChunk = true+ )+ assertEquals(1000L, PodcastAudio.wavInfo(wav)!!.durationMs)+ }++ @Test+ fun `a data chunk with a lying size falls back to the bytes that actually arrived`() {+ val wav = buildWav(+ sampleRate = 24_000,+ channels = 1,+ bitsPerSample = 16,+ dataBytes = 48_000,+ declaredDataSize = 0+ )+ assertEquals(1000L, PodcastAudio.wavInfo(wav)!!.durationMs)+ }++ @Test+ fun `non-WAV responses are rejected, not misparsed`() {+ assertNull(PodcastAudio.wavInfo("{\"error\": \"invalid model\"}".toByteArray()))+ assertNull(PodcastAudio.wavInfo("<html>502 Bad Gateway</html>".toByteArray()))+ assertNull(PodcastAudio.wavInfo(ByteArray(10)))+ assertNull(PodcastAudio.wavInfo(ByteArray(0)))+ // MP3 sync frame — a provider that ignored response_format.+ assertNull(PodcastAudio.wavInfo(byteArrayOf(0xFF.toByte(), 0xFB.toByte()) + ByteArray(100)))+ }++ // ---- synthetic WAV builder ----++ private fun buildWav(+ sampleRate: Int,+ channels: Int,+ bitsPerSample: Int,+ dataBytes: Int,+ leadingJunkChunk: Boolean = false,+ declaredDataSize: Int = dataBytes+ ): ByteArray {+ val out = ByteArrayOutputStream()+ fun ascii(s: String) = out.write(s.toByteArray(Charsets.US_ASCII))+ fun le32(v: Int) = repeat(4) { out.write((v shr (8 * it)) and 0xFF) }+ fun le16(v: Int) = repeat(2) { out.write((v shr (8 * it)) and 0xFF) }++ val byteRate = sampleRate * channels * bitsPerSample / 8+ ascii("RIFF")+ le32(0)+ ascii("WAVE")+ if (leadingJunkChunk) {+ ascii("LIST")+ le32(4)+ ascii("INFO")+ }+ ascii("fmt ")+ le32(16)+ le16(1)+ le16(channels)+ le32(sampleRate)+ le32(byteRate)+ le16(channels * bitsPerSample / 8)+ le16(bitsPerSample)+ ascii("data")+ le32(declaredDataSize)+ out.write(ByteArray(dataBytes))+ return out.toByteArray()+ }+}diff --git a/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt b/app/src/test/java/com/gotcha/tools/PodcastToolTest.ktnew file mode 100644index 0000000..8204502--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/PodcastToolTest.kt@@ -0,0 +1,244 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.audio.AudioModel+import com.gotcha.audio.AudioProvider+import com.gotcha.audio.ModelCategory+import com.gotcha.audio.VoiceInfo+import com.gotcha.data.GotchaStorage+import com.gotcha.data.Settings+import com.gotcha.testsupport.ShadowExternalStorageManager+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import java.io.IOException++/**+ * `synthesize_podcast`'s guards — every refusal that happens before, or instead+ * of, spending TTS API money.+ *+ * The assembly itself (Media3 Transformer) cannot run below the INSTRUMENTED+ * tier, same as media_edit. What is testable here is the decision layer:+ * provider/credential checks, script validation, destination handling, voice+ * resolution, and how a misbehaving TTS endpoint is reported. The pure+ * chunking/WAV logic is covered separately by [PodcastAudioTest].+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class PodcastToolTest {++ private lateinit var context: Context++ /** A backend that records what it was asked and answers from a script. */+ private class FakeBackend(+ var models: List<AudioModel> = emptyList(),+ var answer: (String) -> Result<ByteArray> = { Result.failure(IOException("unreachable")) }+ ) : PodcastTool.TtsBackend {+ val synthesizedWith = mutableListOf<Triple<String, String, String>>()+ override fun listModels(): List<AudioModel> = models+ override fun synthesize(text: String, model: String, voice: String): Result<ByteArray> {+ synthesizedWith.add(Triple(text, model, voice))+ return answer(text)+ }+ }++ private val apiSettings = Settings(+ ttsProvider = AudioProvider.API,+ ttsApiBaseUrl = "http://localhost:8880/v1",+ ttsApiModel = "kokoro",+ ttsVoice = "af_heart"+ )++ @Before+ fun setUp() {+ ShadowExternalStorageManager.granted = true+ context = ApplicationProvider.getApplicationContext()+ GotchaStorage.podcastsRoot().deleteRecursively()+ }++ @After+ fun tearDown() {+ ShadowExternalStorageManager.resetGranted()+ }++ private fun tool(+ settings: Settings = apiSettings,+ backend: FakeBackend = FakeBackend(),+ termux: Boolean = false+ ): PodcastTool = PodcastTool(+ context,+ loadSettings = { settings },+ ttsBackendFactory = { _, _ -> backend },+ termuxUsable = { termux }+ )++ private fun synthesize(+ tool: PodcastTool,+ script: String = "A perfectly ordinary sentence.",+ name: String = "episode",+ model: String? = null,+ voice: String? = null,+ format: String? = null,+ overwrite: Boolean = false+ ): ToolResult = runBlocking { tool.synthesize(script, name, model, voice, format, overwrite) }++ // ---- provider and credential guards ----++ @Test+ fun `the Android provider is refused with directions to Settings`() {+ val result = synthesize(tool(settings = Settings(ttsProvider = AudioProvider.ANDROID)))+ assertFalse(result.success)+ assertTrue(result.message.contains("Settings"))+ assertTrue(result.message.contains("cannot write audio to a file"))+ }++ @Test+ fun `Samosa AI without a session asks for a sign-in, not a crash`() {+ val result = synthesize(tool(settings = Settings(ttsProvider = AudioProvider.SAMOSA_AI)))+ assertFalse(result.success)+ assertTrue(result.message.contains("sign in"))+ }++ @Test+ fun `an External API provider with no base URL is refused`() {+ val result = synthesize(tool(settings = Settings(ttsProvider = AudioProvider.API)))+ assertFalse(result.success)+ assertTrue(result.message.contains("base URL"))+ }++ @Test+ fun `a blank configured model is its own error, not a provider error`() {+ val settings = apiSettings.copy(ttsApiModel = "")+ val result = synthesize(tool(settings = settings))+ assertFalse(result.success)+ assertTrue(result.message.contains("model"))+ }++ // ---- script guards ----++ @Test+ fun `a script that sanitizes to nothing is refused before any API call`() {+ val backend = FakeBackend()+ val result = synthesize(tool(backend = backend), script = "```kotlin\nval x = 1\n``` 🎉")+ assertFalse(result.success)+ assertTrue(backend.synthesizedWith.isEmpty())+ }++ @Test+ fun `a script past the ceiling is refused before any API call`() {+ val backend = FakeBackend()+ val script = "This sentence repeats. ".repeat(2000)+ val result = synthesize(tool(backend = backend), script = script)+ assertFalse(result.success)+ assertTrue(result.message.contains(PodcastTool.MAX_SCRIPT_CHARS.toString()))+ assertTrue(backend.synthesizedWith.isEmpty())+ }++ // ---- format and destination guards ----++ @Test+ fun `an unsupported format is refused and names the two supported ones`() {+ val result = synthesize(tool(), format = "wav")+ assertFalse(result.success)+ assertTrue(result.message.contains("m4a"))+ assertTrue(result.message.contains("mp3"))+ }++ @Test+ fun `an unrecognised extension on output_name is refused when no format is given`() {+ val result = synthesize(tool(), name = "episode.ogg")+ assertFalse(result.success)+ }++ @Test+ fun `an existing output without overwrite is refused before any API call`() {+ val backend = FakeBackend()+ GotchaStorage.podcastsRoot().mkdirs()+ File(GotchaStorage.podcastsRoot(), "episode.m4a").writeBytes(ByteArray(4))+ val result = synthesize(tool(backend = backend))+ assertFalse(result.success)+ assertTrue(result.message.contains("overwrite"))+ assertTrue(backend.synthesizedWith.isEmpty())+ }++ @Test+ fun `output_name is slugified rather than trusted`() {+ GotchaStorage.podcastsRoot().mkdirs()+ File(GotchaStorage.podcastsRoot(), "my-morning-news.m4a").writeBytes(ByteArray(4))+ // The collision proves '../my morning*news!.wtf' resolved to the slug, not a path escape.+ val result = synthesize(tool(), name = "../my morning*news!", overwrite = false)+ assertFalse(result.success)+ assertTrue(result.message.contains("my-morning-news"))+ }++ // ---- voice resolution ----++ @Test+ fun `with no configured voice the model's own default voice is used`() {+ val backend = FakeBackend(+ models = listOf(+ AudioModel(+ id = "kokoro",+ category = ModelCategory.TTS,+ voices = listOf(VoiceInfo(id = "bf_emma"), VoiceInfo(id = "af_heart"))+ )+ )+ )+ synthesize(tool(settings = apiSettings.copy(ttsVoice = ""), backend = backend))+ assertEquals("bf_emma", backend.synthesizedWith.single().third)+ }++ @Test+ fun `an explicit voice argument beats the configured one`() {+ val backend = FakeBackend()+ synthesize(tool(backend = backend), voice = "bm_george")+ assertEquals("bm_george", backend.synthesizedWith.single().third)+ }++ @Test+ fun `no voice anywhere and an unreachable model list is an actionable error`() {+ val result = synthesize(tool(settings = apiSettings.copy(ttsVoice = "")))+ assertFalse(result.success)+ assertTrue(result.message.contains("voice"))+ }++ // ---- TTS endpoint misbehaviour ----++ @Test+ fun `a failed TTS request names the segment and writes nothing`() {+ val backend = FakeBackend(answer = { Result.failure(IOException("HTTP 401: bad key")) })+ val result = synthesize(tool(backend = backend))+ assertFalse(result.success)+ assertTrue(result.message.contains("segment 1"))+ assertTrue(result.message.contains("HTTP 401"))+ assertFalse(File(GotchaStorage.podcastsRoot(), "episode.m4a").exists())+ }++ @Test+ fun `a non-WAV response is diagnosed instead of assembled`() {+ val backend = FakeBackend(answer = { Result.success("{\"error\":\"no such voice\"}".toByteArray()) })+ val result = synthesize(tool(backend = backend))+ assertFalse(result.success)+ assertTrue(result.message.contains("not WAV"))+ }++ @Test+ fun `a long script reaches the API as multiple whole-sentence segments`() {+ val backend = FakeBackend(answer = { Result.failure(IOException("stop after capture")) })+ val script = (1..400).joinToString(" ") { "Sentence number $it carries some words along." }+ synthesize(tool(backend = backend), script = script)+ // Only the first segment is attempted (it fails), but its size proves chunking ran.+ val sent = backend.synthesizedWith.single().first+ assertTrue(sent.length <= PodcastTool.MAX_CHUNK_CHARS)+ assertTrue(sent.endsWith("."))+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex d7b85db..116cc96 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -434,6 +434,15 @@],"notes": "exhaustive coverage of the generated ffmpeg command on the JVM — POSIX shell quoting against spaces, embedded quotes and metacharacters, /storage/emulated/0 to /sdcard translation including secondary-user roots and near-miss prefixes, bitrate validation, and every audio target's codec arguments — plus the guards that run before Termux is invoked: unsupported and video output formats, nonsense bitrates, paths inside Gotcha's private storage that Termux cannot see, missing input, same-file conversion, existing-output refusal and directory outputs. The conversion itself is device-only and additionally needs Termux with the ffmpeg package installed, so a real MP3 round trip must be verified by hand"},+ {+ "tool": "synthesize_podcast",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.PodcastToolTest",+ "com.gotcha.tools.PodcastAudioTest"+ ],+ "notes": "the pure halves on the JVM — sentence-boundary script chunking (limit respected, nothing lost or reordered, oversize sentences split at word boundaries, hard cut only as a last resort) and WAV header parsing by chunk walk (real sample rate honoured rather than assumed, lying data-chunk sizes measured from what actually arrived, JSON/HTML/MP3 responses rejected) — plus every guard that runs before TTS money is spent: Android/unconfigured provider refusals with directions to Settings, blank model, scripts that sanitize to nothing or exceed the ceiling, unsupported formats, existing-output refusal, output_name slugification, and voice resolution (explicit argument beats configured voice beats the model's own default). The assembly itself is device-only — Media3 Transformer drives MediaCodec — and additionally needs a reachable TTS endpoint, so a full script-to-.m4a (and, with Termux, .mp3) run — audible joins, Files-app visibility, the .m4a fallback note — must be verified by hand"+ },{"tool": "glob","tier": "ROBOLECTRIC",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex bec678c..4c7c9d2 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 22 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 23 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **110** | |+| **Total** | **111** | |-**46 of 110** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**47 of 111** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -90,6 +90,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `snooze_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `start_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `stop_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |+| `synthesize_podcast` | `ROBOLECTRIC` | `PodcastToolTest`, `PodcastAudioTest` — the pure halves on the JVM — sentence-boundary script chunking (limit respected, nothing lost or reordered, oversize sentences split at word boundaries, hard cut only as a last resort) and WAV header parsing by chunk walk (real sample rate honoured rather than assumed, lying data-chunk sizes measured from what actually arrived, JSON/HTML/MP3 responses rejected) — plus every guard that runs before TTS money is spent: Android/unconfigured provider refusals with directions to Settings, blank model, scripts that sanitize to nothing or exceed the ceiling, unsupported formats, existing-output refusal, output_name slugification, and voice resolution (explicit argument beats configured voice beats the model's own default). The assembly itself is device-only — Media3 Transformer drives MediaCodec — and additionally needs a reachable TTS endpoint, so a full script-to-.m4a (and, with Termux, .mp3) run — audible joins, Files-app visibility, the .m4a fallback note — must be verified by hand || `take_photo` | `MANUAL_ONLY` | Needs a real camera; CameraX has no usable emulator fake for the capture callback. || `toggle_torch` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `toggle_wifi` | `MANUAL_ONLY` | `SystemToolTest` — The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier. |