Skip to content

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.

fix podcast review: wire session invalidation, cap duration, harden voice and mp3 salvage

Jalebi444c6728b17a
diff --git a/app/src/main/java/com/gotcha/tools/PodcastTool.kt b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
index 3a95746..2941958 100644
--- a/app/src/main/java/com/gotcha/tools/PodcastTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PodcastTool.kt
@@ -38,8 +38,9 @@ import kotlin.coroutines.coroutineContext
class PodcastTool(
private val context: Context,
private val loadSettings: () -> Settings = { SettingsRepository(context).load() },
+ private val onUnauthorized: (() -> Unit)? = null,
private val ttsBackendFactory: (baseUrl: String, apiKey: String) -> TtsBackend = { url, key ->
- ApiTtsBackend(AudioApi(url, key, timeoutSeconds = TTS_TIMEOUT_SECONDS))
+ ApiTtsBackend(AudioApi(url, key, timeoutSeconds = TTS_TIMEOUT_SECONDS, onUnauthorized = onUnauthorized))
},
private val mediaExport: MediaExport = MediaExport(context),
private val mediaConvert: MediaConvertTool = MediaConvertTool(context),
@@ -72,11 +73,12 @@ class PodcastTool(
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
+ * ~20 minutes of audio, 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.
+ * obviously hopeless script before any API spend. Kept conservative
+ * so the audio-duration guard remains the precise backstop.
*/
- const val MAX_SCRIPT_CHARS = 24_000
+ const val MAX_SCRIPT_CHARS = 20_000
/**
* Per-request text limit. OpenAI-compatible speech endpoints cap
@@ -85,8 +87,16 @@ class PodcastTool(
*/
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
+ /**
+ * Audio-duration ceiling. Re-uses media_edit's 30-min re-encode guard as
+ * an upper bound, but caps lower so a single [MediaExport] re-encode
+ * (bounded by a 10-minute timeout) can realistically finish on a slow
+ * device without discarding paid synthesis. Audio-only AAC encode is
+ * typically faster than realtime, but a 25-30 minute episode in one
+ * export is a plausible timeout after all TTS money is spent, so the
+ * ceiling is set to 20 minutes with margin.
+ */
+ const val MAX_TOTAL_DURATION_MS = 20L * 60 * 1000
/**
* Breathing room between dialogue turns when neither the call's
@@ -387,8 +397,29 @@ class PodcastTool(
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
+ // A failed ffmpeg run may have left a partial .mp3 at the destination;
+ // delete it so the next run with overwrite=false does not falsely hit
+ // "already exists" and to avoid stranding a corrupt file.
+ runCatching { if (job.destination.exists()) job.destination.delete() }
+ val parent = job.destination.parentFile ?: m4a.parentFile
+ val fallback = File(parent, "${job.baseName}.$FORMAT_M4A")
+ val kept: File = if (job.overwrite) {
+ if (m4a.renameTo(fallback)) fallback else m4a
+ } else {
+ if (!fallback.exists()) {
+ if (m4a.renameTo(fallback)) fallback else m4a
+ } else {
+ // Pick a stable .m4a name rather than leaving the temp-looking
+ // ".podcast-tmp.m4a" in the user's Podcasts folder.
+ var counter = 1
+ var candidate: File
+ do {
+ candidate = File(parent, "${job.baseName}-$counter.$FORMAT_M4A")
+ counter++
+ } while (candidate.exists() && counter < 100)
+ if (m4a.renameTo(candidate)) candidate 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."
@@ -476,7 +507,7 @@ class PodcastTool(
"Write the narration as plain prose and try again."
)
sanitizedLength > MAX_SCRIPT_CHARS -> ToolResult.error(
- "The script is $sanitizedLength characters; the limit is $MAX_SCRIPT_CHARS (~25 minutes of " +
+ "The script is $sanitizedLength characters; the limit is $MAX_SCRIPT_CHARS (~20 minutes of " +
"speech). Split it into parts and synthesize each as its own file."
)
else -> null
@@ -518,9 +549,13 @@ class PodcastTool(
): String? {
val explicit = (voiceArg ?: configuredVoice).trim()
if (explicit.isNotBlank()) return explicit
- return ttsModels(backend).let { models ->
- (models.firstOrNull { it.id == model } ?: models.firstOrNull())?.defaultVoice
- }
+ val models = ttsModels(backend)
+ val target = models.firstOrNull { it.id == model } ?: models.firstOrNull() ?: return null
+ // Do not fall back to a hard-coded Samosa voice id when the model's
+ // voice list is empty — on a third-party provider that id will not
+ // exist and the generic "not WAV" error hides the real problem.
+ if (target.voices.isEmpty()) return null
+ return target.voices.first().id
}
/**
diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
index 44f2af4..ecbf979 100644
--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
@@ -19,7 +19,7 @@ object ToolCategories {
private val backgroundTools = setOf(
"edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit", "media_convert",
- "synthesize_podcast", "synthesize_podcast_dialogue",
+ "synthesize_podcast", "synthesize_podcast_dialogue", "transcribe_file",
"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.kt
index 7f01509..de22190 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1446,7 +1446,7 @@ object ToolDefinitions {
"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 " +
+ "Long scripts are synthesized in segments and joined on-device; ~20 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, " +
@@ -1521,8 +1521,9 @@ object ToolDefinitions {
"revelation earns a beat first. gap_ms is only the fallback for turns you leave unpaced, so a " +
"script with no pause_ms at all comes out evenly spaced and lifeless. Length ceiling, output " +
"formats and the TTS provider requirement are the same as " +
- "synthesize_podcast: ~25 minutes, .m4a by default or format='mp3' via Termux's ffmpeg, and an " +
- "API-based TTS provider — Android's built-in TTS cannot write files.",
+ "synthesize_podcast: ~20 minutes, .m4a by default or format='mp3' via Termux's ffmpeg, and an " +
+ "API-based TTS provider — Android's built-in TTS cannot write files. Turns whose text is blank " +
+ "after sanitization (e.g. only markdown or emoji) are dropped rather than synthesized as silence.",
schema {
putJsonObject("properties") {
putJsonObject("lines") {
@@ -1531,7 +1532,8 @@ object ToolDefinitions {
"description",
"The dialogue in order. Each item is one turn: " +
"{\"speaker\": \"A\" or \"B\", \"text\": \"the words to speak\", " +
- "\"pause_ms\": the silence after it}."
+ "\"pause_ms\": the silence after it}. Turns whose text sanitizes to blank " +
+ "(e.g. only markdown or emoji) are dropped rather than synthesized as silence."
)
putJsonObject("items") {
put("type", "object")
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 6cbb9f7..9ef448a 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -68,8 +68,14 @@ class ToolExecutor(
private val pdfTool = PdfTool(appContext)
private val mediaEditTool = MediaEditTool(appContext)
private val mediaConvertTool = MediaConvertTool(appContext)
- private val podcastTool = PodcastTool(appContext)
- private val transcribeTool = TranscribeTool(appContext)
+ private val podcastTool = PodcastTool(
+ appContext,
+ onUnauthorized = { runCatching { com.gotcha.data.SettingsRepository(appContext).clearSamosaSession() } }
+ )
+ private val transcribeTool = TranscribeTool(
+ appContext,
+ onUnauthorized = { runCatching { com.gotcha.data.SettingsRepository(appContext).clearSamosaSession() } }
+ )
private val globTool = GlobTool(appContext)
private val grepTool = GrepTool(appContext)
private val accessibilityTool = AccessibilityTool(appContext)
diff --git a/app/src/main/java/com/gotcha/tools/TranscribeTool.kt b/app/src/main/java/com/gotcha/tools/TranscribeTool.kt
index ff264f4..a30e8e8 100644
--- a/app/src/main/java/com/gotcha/tools/TranscribeTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TranscribeTool.kt
@@ -27,8 +27,9 @@ import java.io.File
class TranscribeTool(
private val context: Context,
private val loadSettings: () -> Settings = { SettingsRepository(context).load() },
+ private val onUnauthorized: (() -> Unit)? = null,
private val sttBackendFactory: (baseUrl: String, apiKey: String) -> SttBackend = { url, key ->
- ApiSttBackend(AudioApi(url, key, timeoutSeconds = STT_TIMEOUT_SECONDS))
+ ApiSttBackend(AudioApi(url, key, timeoutSeconds = STT_TIMEOUT_SECONDS, onUnauthorized = onUnauthorized))
}
) {
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index 14eb859..fce1594 100644
--- a/docs/FEATURE_TEST_COVERAGE.md
+++ b/docs/FEATURE_TEST_COVERAGE.md
@@ -96,6 +96,7 @@ Every tool the assistant can call is listed below, together with how it is verif
| `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. |
+| `transcribe_file` | `ROBOLECTRIC` | `TranscribeToolTest` — every guard that runs before the upload — Android/unconfigured STT provider refusals with directions to Settings, missing/empty/oversized files, unsupported extensions refused before the backend is touched — plus the properties that make the tool safe to point at a user's only copy of a recording: the input file demonstrably survives transcription byte-for-byte (the deliberate contrast with SttEngine.transcribeApi, which deletes its input), model resolution (explicit argument beats configured setting beats the first STT model the API advertises), empty transcripts reported as errors rather than silence, and over-long transcripts truncated with an honest note. The upload itself needs a reachable STT endpoint, so a real memo round trip is device-only manual verification |
| `uninstall_app` | `MANUAL_ONLY` | `AgentLoopTest` — AgentLoopTest covers the CONFIRM_UNINSTALL marker and both sides of the confirmation gate, but the actual package removal is a system dialog that cannot be automated. |
| `vibrate` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |
| `write_file` | `ROBOLECTRIC` | `FileToolsTest`, `FileResolverTest`, `AgentLoopTest` — create, append, overwrite, parent-dir creation; also driven end-to-end through the agent loop |
@@ -145,7 +146,6 @@ Every tool the assistant can call is listed below, together with how it is verif
| `search_skills` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |
| `sleep` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |
| `todowrite` | `MANUAL_ONLY` | Pure UI round-trip: writes the visible todo list in the chat surface. |
-| `transcribe_file` | `ROBOLECTRIC` | `TranscribeToolTest` — every guard that runs before the upload — Android/unconfigured STT provider refusals with directions to Settings, missing/empty/oversized files, unsupported extensions refused before the backend is touched — plus the properties that make the tool safe to point at a user's only copy of a recording: the input file demonstrably survives transcription byte-for-byte (the deliberate contrast with SttEngine.transcribeApi, which deletes its input), model resolution (explicit argument beats configured setting beats the first STT model the API advertises), empty transcripts reported as errors rather than silence, and over-long transcripts truncated with an honest note. The upload itself needs a reachable STT endpoint, so a real memo round trip is device-only manual verification |
| `update_user_profile` | `UNIT` | `UpdateUserProfileTest` — merge semantics (modify-and-extend, never erase), the no-op guard, and the 250/50-word caps |
| `webfetch` | `UNIT` | `WebFetchToolTest` — HTML-to-text extraction, truncation, error handling |
| `websearch` | `MANUAL_ONLY` | Performs real network I/O against a search provider; exercising it in CI would make the suite non-hermetic. |