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(convert): media_convert, audio format conversion via Termux ffmpeg
Durganshudfef93799631
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b69442..951c68f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@ All notable changes to Gotcha are documented here.## [Unreleased]### Added+- **Audio format conversion.** A new `media_convert` tool converts audio between+ MP3, M4A, AAC, OGG, Opus, WAV and FLAC using Termux's ffmpeg — still entirely+ on the device, with nothing uploaded anywhere. This is the only way to get an+ MP3 out of Gotcha: Android ships no MP3 encoder at all, so `media_edit` cannot+ write one however it is asked. The tool appears only when Termux is installed,+ and if its ffmpeg package is missing the error says exactly what to run.- **Audio & video editing.** A new `media_edit` tool edits media entirelyon-device: trim a window out of a clip, pull a video's audio into its ownfile, mute a video, shrink one to a smaller resolution, speed it up or slow itdiff --git a/app/src/main/assets/skills/media_editing.json b/app/src/main/assets/skills/media_editing.jsonindex 0e09fa5..e849835 100644--- a/app/src/main/assets/skills/media_editing.json+++ b/app/src/main/assets/skills/media_editing.json@@ -4,32 +4,36 @@"title": "Audio & Video Editing Skills","description": "Trim, shrink, re-time and join audio and video on-device with media_edit instead of a web converter or an editor app.","requiresTools": [- "media_edit"+ "media_edit",+ "media_convert"],"keywords": [- "video",- "videos","audio","clip",- "trim",+ "compress",+ "conversion",+ "convert","cut",- "mute",- "recording",+ "faster","footage",- "mp4",+ "format",+ "join","m4a",- "soundtrack",- "voice","memo",+ "merge",+ "mp3",+ "mp4",+ "mute","podcast",- "compress",+ "recording","shrink",- "speed",- "faster","slower",- "join",- "merge",- "mp3"+ "soundtrack",+ "speed",+ "trim",+ "video",+ "videos",+ "voice"],- "instructions": "Never upload a video or audio file to a web converter, and never automate a video editor's UI to trim a clip. media_edit does it locally: the file never leaves the device, and there is no watermark, length limit or account.\n\nCall operation='info' FIRST whenever you need a timecode. It reports duration, tracks, resolution, rotation and codecs without decoding anything, so it is cheap. Never guess a duration from the file name or size, and never trim against a duration the user quoted from memory — check it.\n\nWhat it does:\n1. 'info' — what the file contains. Also the way to answer \"how long is this?\" or \"does this video have sound?\".\n2. 'trim' — keeps the window between 'start' and 'end' and drops the rest. Give at least one of them; 'start' alone runs to the end of the file, 'end' alone starts from the beginning.\n3. 'extract_audio' — writes the audio track as its own .m4a. This is \"rip the audio\", \"just the sound\", \"turn this video into a podcast episode\".\n4. 'remove_audio' — writes the video with the audio dropped. This is \"mute it\", \"remove the background noise\" (which it does by removing ALL sound — say so, because that is usually not what they hoped for).\n5. 'compress' — re-encodes smaller at 'height' (default 720). This is \"make it small enough to email/WhatsApp\". Compressing a file that is already that small or smaller is refused rather than silently degrading it.\n6. 'speed' — re-times by 'speed', between 0.25 and 4.0. Audio and video are re-timed together, so they stay in sync. 2.0 halves the duration.\n7. 'concat' — joins 'inputs' end to end, in exactly the order given. Confirm the order with the user when it is not obvious; a join in the wrong order looks like data loss to them. All inputs must be video, or all audio-only — mixing them is refused.\n\nTimecodes take several forms: '1:23' (m:ss), '1:02:03' (h:mm:ss), '90s', '1m30s', '500ms', or plain seconds like '12.5'. A colon field holding 60 or more seconds is refused as ambiguous — write '1:30' or '90s', not '1:90'. Use 'end' as the end timecode to mean the end of the file.\n\nAll four operations work identically on video and on audio-only files. Trimming an .m4a voice memo and trimming a 4K video are the same call. The two exceptions are refused with an explanation: extracting audio from a file that has no audio track, and removing the audio from a file that is audio-only.\n\nCost differs sharply between the two groups, and it is worth telling the user which they are getting. trim, extract_audio and remove_audio COPY the streams: they finish in seconds even on a long video and lose no quality whatsoever. compress, speed and concat RE-ENCODE: they run the whole file through the codec, which takes minutes and loses a little quality each time. The result message says which happened — pass that on, because repeated re-encoding visibly degrades a file and the user cannot see it coming.\n\nBecause re-encoding is slow, inputs longer than 30 minutes are refused for compress, speed and concat, and any export that overruns ten minutes is abandoned. When you hit either, do not retry the same call — trim the file to the part that is actually wanted first, and explain why you are doing that.\n\nOutput rules that matter. Every operation writes a NEW file and leaves the input untouched. The output path CANNOT be the same as the input — unlike pdf_edit there is no in-place mode, because the encoder writes the target while still reading the source, which would destroy both. Pick a clearly derived name (VID_0001-trimmed.mp4, interview-audio.m4a) and tell the user where you put it. An existing output fails unless you pass overwrite=true; do not reflexively retry with overwrite after that error, since the file in the way may be one the user still wants. The output must end in .mp4 (video) or .m4a (audio only) — the muxer always writes an MP4 container, so any other extension would be a mislabelled file.\n\nMP3 output is not possible, and this comes up constantly because \"extract the mp3\" is simply how people ask for an audio file. Android ships no MP3 encoder and its muxer only writes AAC audio, so no on-device tool can produce one — this is a property of the platform, not a gap in Gotcha. Write '.m4a' instead and say what you did: \"I saved it as an .m4a rather than an MP3, because MP3 can't be created on-device — it plays everywhere MP3 does and is a bit smaller for the same quality.\" Do NOT detour to ffmpeg over a file extension; that costs a Termux dependency the user may not have installed, to produce a file no more useful than the .m4a. Reach for ffmpeg via run_termux_command only when the user says they specifically need MP3 for something that accepts nothing else.\n\nThe hard limits, which you must state plainly rather than work around:\n• It CANNOT add background music or any second audio track, overlay text, a watermark or an image, fade audio in or out, adjust volume, or change the bitrate directly. These are not implemented. Do not fake any of them by chaining other tools.\n• It CANNOT open DRM-protected media — anything bought or downloaded from a store. That is a property of the file, not a missing feature, and no retry will work.\n• It CANNOT edit what is inside a frame: no removing an object, no blurring a face, no colour grading, no stabilisation.\n• Cutting a middle section OUT of one file is possible, but only as two steps: trim the part before and the part after into separate files, then concat them. Say that is what you are doing, and clean up the intermediate files afterwards with delete_file.\nWhen asked for one of these, say so directly and offer what does work.\n\nIf a file will not open at all, it may be in a container Android's codecs cannot read (MKV, OGG, FLV are the usual ones). ffmpeg through run_termux_command is the fallback, but it requires Termux installed with the ffmpeg package, so offer it as an option rather than assuming it is there.\n\nFinding the file: phone video lives in /sdcard/DCIM/Camera, screen recordings in /sdcard/Movies, voice memos and music in /sdcard/Music or /sdcard/Recordings, downloads in /sdcard/Download, and WhatsApp media under /sdcard/Android/media/com.whatsapp. Use glob (e.g. '/sdcard/DCIM/Camera/*.mp4') rather than asking the user for a full path they will not know. When several match, use info on the likely ones and confirm which they meant before writing anything — trimming the wrong video looks like data loss."+ "instructions": "Never upload a video or audio file to a web converter, and never automate a video editor's UI to trim a clip. media_edit does it locally: the file never leaves the device, and there is no watermark, length limit or account.\n\nCall operation='info' FIRST whenever you need a timecode. It reports duration, tracks, resolution, rotation and codecs without decoding anything, so it is cheap. Never guess a duration from the file name or size, and never trim against a duration the user quoted from memory — check it.\n\nWhat it does:\n1. 'info' — what the file contains. Also the way to answer \"how long is this?\" or \"does this video have sound?\".\n2. 'trim' — keeps the window between 'start' and 'end' and drops the rest. Give at least one of them; 'start' alone runs to the end of the file, 'end' alone starts from the beginning.\n3. 'extract_audio' — writes the audio track as its own .m4a. This is \"rip the audio\", \"just the sound\", \"turn this video into a podcast episode\".\n4. 'remove_audio' — writes the video with the audio dropped. This is \"mute it\", \"remove the background noise\" (which it does by removing ALL sound — say so, because that is usually not what they hoped for).\n5. 'compress' — re-encodes smaller at 'height' (default 720). This is \"make it small enough to email/WhatsApp\". Compressing a file that is already that small or smaller is refused rather than silently degrading it.\n6. 'speed' — re-times by 'speed', between 0.25 and 4.0. Audio and video are re-timed together, so they stay in sync. 2.0 halves the duration.\n7. 'concat' — joins 'inputs' end to end, in exactly the order given. Confirm the order with the user when it is not obvious; a join in the wrong order looks like data loss to them. All inputs must be video, or all audio-only — mixing them is refused.\n\nTimecodes take several forms: '1:23' (m:ss), '1:02:03' (h:mm:ss), '90s', '1m30s', '500ms', or plain seconds like '12.5'. A colon field holding 60 or more seconds is refused as ambiguous — write '1:30' or '90s', not '1:90'. Use 'end' as the end timecode to mean the end of the file.\n\nAll four operations work identically on video and on audio-only files. Trimming an .m4a voice memo and trimming a 4K video are the same call. The two exceptions are refused with an explanation: extracting audio from a file that has no audio track, and removing the audio from a file that is audio-only.\n\nCost differs sharply between the two groups, and it is worth telling the user which they are getting. trim, extract_audio and remove_audio COPY the streams: they finish in seconds even on a long video and lose no quality whatsoever. compress, speed and concat RE-ENCODE: they run the whole file through the codec, which takes minutes and loses a little quality each time. The result message says which happened — pass that on, because repeated re-encoding visibly degrades a file and the user cannot see it coming.\n\nBecause re-encoding is slow, inputs longer than 30 minutes are refused for compress, speed and concat, and any export that overruns ten minutes is abandoned. When you hit either, do not retry the same call — trim the file to the part that is actually wanted first, and explain why you are doing that.\n\nOutput rules that matter. Every operation writes a NEW file and leaves the input untouched. The output path CANNOT be the same as the input — unlike pdf_edit there is no in-place mode, because the encoder writes the target while still reading the source, which would destroy both. Pick a clearly derived name (VID_0001-trimmed.mp4, interview-audio.m4a) and tell the user where you put it. An existing output fails unless you pass overwrite=true; do not reflexively retry with overwrite after that error, since the file in the way may be one the user still wants. The output must end in .mp4 (video) or .m4a (audio only) — the muxer always writes an MP4 container, so any other extension would be a mislabelled file.\n\nMP3 and other formats: media_edit itself always writes an MP4 container (.mp4 or .m4a), because Android ships no MP3 encoder and its muxer only writes AAC. When someone asks for an MP3 there are two good answers, in this order.\n1. If they just want \"the audio\" — which is what \"extract the mp3\" almost always means — use media_edit extract_audio to write an .m4a and say so: \"I saved it as an .m4a rather than an MP3; it plays everywhere MP3 does and is a bit smaller for the same quality.\" This needs no setup and takes seconds.\n2. If they specifically want an MP3, use the media_convert tool, which runs Termux's ffmpeg on the device. It converts to .mp3, .m4a, .aac, .ogg, .opus, .wav or .flac and the file never leaves the phone. It only appears when Termux is installed; if it is not in your tool list, offer option 1 and mention that installing Termux plus 'pkg install ffmpeg' would enable real MP3 conversion.\nTo go from a video to an MP3: media_edit extract_audio to .m4a first, then media_convert that to .mp3. Do not try to point media_convert at a video and a .mp3 output in one step — extract first, then convert. Never hand-write an ffmpeg command line with run_termux_command for a conversion media_convert already does; the tool quotes paths safely and diagnoses the common failures, and a hand-written command does neither.\n\nThe hard limits, which you must state plainly rather than work around:\n• It CANNOT add background music or any second audio track, overlay text, a watermark or an image, fade audio in or out, adjust volume, or change the bitrate directly. These are not implemented. Do not fake any of them by chaining other tools.\n• It CANNOT open DRM-protected media — anything bought or downloaded from a store. That is a property of the file, not a missing feature, and no retry will work.\n• It CANNOT edit what is inside a frame: no removing an object, no blurring a face, no colour grading, no stabilisation.\n• Cutting a middle section OUT of one file is possible, but only as two steps: trim the part before and the part after into separate files, then concat them. Say that is what you are doing, and clean up the intermediate files afterwards with delete_file.\nWhen asked for one of these, say so directly and offer what does work.\n\nIf a file will not open at all, it may be in a container Android's codecs cannot read (MKV, OGG, FLV are the usual ones). ffmpeg through run_termux_command is the fallback, but it requires Termux installed with the ffmpeg package, so offer it as an option rather than assuming it is there.\n\nFinding the file: phone video lives in /sdcard/DCIM/Camera, screen recordings in /sdcard/Movies, voice memos and music in /sdcard/Music or /sdcard/Recordings, downloads in /sdcard/Download, and WhatsApp media under /sdcard/Android/media/com.whatsapp. Use glob (e.g. '/sdcard/DCIM/Camera/*.mp4') rather than asking the user for a full path they will not know. When several match, use info on the likely ones and confirm which they meant before writing anything — trimming the wrong video looks like data loss."}diff --git a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.ktindex ed0e482..226d3df 100644--- a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt+++ b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt@@ -52,7 +52,12 @@ enum class Capability("Termux (the Linux terminal app, installed from F-Droid)",// Gated on Termux being installed, not on the RUN_COMMAND grant: gating on the grant// would hide the only tool that can raise the prompt for it. See DeviceCapabilities.- setOf("run_termux_command")+ //+ // media_convert rides on the same capability because it is ffmpeg run through+ // run_termux_command. Hiding it without Termux is the point: it is the only route to+ // MP3, and a model that could see it on a device that cannot run it would promise a+ // conversion it has no way to perform.+ setOf("run_termux_command", "media_convert")),HEALTH_CONNECT(diff --git a/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt b/app/src/main/java/com/gotcha/tools/FfmpegCommand.ktindex ff49762..3c5ee64 100644--- a/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt+++ b/app/src/main/java/com/gotcha/tools/FfmpegCommand.kt@@ -24,8 +24,14 @@ import java.util.Locale*/object FfmpegCommand {- /** Android's canonical shared-storage root, as Gotcha's [FileResolver] reports it. */- const val SHARED_STORAGE_ROOT = "/storage/emulated/0"+ /**+ * Shared storage as Android usually reports it for the primary user. Only a+ * fallback and a documentation aid: callers pass the real root from+ * `Environment.getExternalStorageDirectory()`, because a secondary Android+ * user gets `/storage/emulated/<id>` and hardcoding the primary would send+ * ffmpeg at another user's files — or, under a test harness, at nothing.+ */+ const val DEFAULT_SHARED_STORAGE_ROOT = "/storage/emulated/0"/** The same tree as Termux must address it. */const val TERMUX_STORAGE_ROOT = "/sdcard"@@ -85,16 +91,16 @@ object FfmpegCommand {* Anything outside shared storage is returned unchanged — [MediaConvertTool]* refuses those separately, with an explanation Termux itself cannot give.*/- fun termuxPath(canonicalPath: String): String = when {- canonicalPath == SHARED_STORAGE_ROOT -> TERMUX_STORAGE_ROOT- canonicalPath.startsWith("$SHARED_STORAGE_ROOT/") ->- TERMUX_STORAGE_ROOT + canonicalPath.removePrefix(SHARED_STORAGE_ROOT)+ fun termuxPath(canonicalPath: String, sharedRoot: String = DEFAULT_SHARED_STORAGE_ROOT): String = when {+ canonicalPath == sharedRoot -> TERMUX_STORAGE_ROOT+ canonicalPath.startsWith("$sharedRoot/") ->+ TERMUX_STORAGE_ROOT + canonicalPath.removePrefix(sharedRoot)else -> canonicalPath}/** True when [canonicalPath] is somewhere Termux can reach at all. */- fun isReachableFromTermux(canonicalPath: String): Boolean =- canonicalPath == SHARED_STORAGE_ROOT || canonicalPath.startsWith("$SHARED_STORAGE_ROOT/")+ fun isReachableFromTermux(canonicalPath: String, sharedRoot: String = DEFAULT_SHARED_STORAGE_ROOT): Boolean =+ canonicalPath == sharedRoot || canonicalPath.startsWith("$sharedRoot/")/*** Normalises a requested bitrate to ffmpeg's spelling, or null when it is not@@ -129,15 +135,16 @@ object FfmpegCommand {inputCanonical: String,outputCanonical: String,target: Target,- bitrate: String?+ bitrate: String?,+ sharedRoot: String = DEFAULT_SHARED_STORAGE_ROOT): String {val args = mutableListOf("ffmpeg", "-nostdin", "-loglevel", "error", "-y")- args += listOf("-i", shellQuote(termuxPath(inputCanonical)))+ args += listOf("-i", shellQuote(termuxPath(inputCanonical, sharedRoot)))args += "-vn"args += target.codecArgsval effective = if (target.isLossless) null else bitrate ?: target.bitrateeffective?.let { args += listOf("-b:a", it) }- args += shellQuote(termuxPath(outputCanonical))+ args += shellQuote(termuxPath(outputCanonical, sharedRoot))return args.joinToString(" ")}diff --git a/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt b/app/src/main/java/com/gotcha/tools/MediaConvertTool.ktnew file mode 100644index 0000000..b8d6f83--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/MediaConvertTool.kt@@ -0,0 +1,281 @@+package com.gotcha.tools++import android.content.Context+import android.os.Environment+import java.io.File++/**+ * Audio format conversion, run through Termux's ffmpeg.+ *+ * This exists because of a hard platform limit rather than a missing feature.+ * Android ships an MP3 decoder but no encoder, and [MediaEditTool]'s muxer+ * writes only AAC, so MP3 — the format people ask for by name more than any+ * other — is unreachable on-device through the media3 pipeline at any effort.+ * Termux's ffmpeg carries libmp3lame and the rest, and [TermuxTool] is already+ * wired up, so the conversion still happens entirely on the phone.+ *+ * Kept a separate tool from [MediaEditTool] rather than an eighth operation on+ * it, because their availability differs: media_edit works with no setup, this+ * needs Termux installed and its ffmpeg package present. Being separate lets+ * [Capability.TERMUX] hide it when Termux is absent, so the model is never shown+ * a tool it cannot run.+ *+ * Only available to Operator (writes files).+ */+class MediaConvertTool(+ private val context: Context,+ private val termux: TermuxTool = TermuxTool(context)+) {++ private val resolver = FileResolver(context)++ /**+ * Shared storage as this device reports it. Read from [Environment] rather+ * than assumed, because a secondary Android user's storage is+ * `/storage/emulated/<id>`, and the boundary decides both which paths Termux+ * can reach and how they are rewritten for it.+ */+ private val sharedRoot: String+ get() = runCatching { Environment.getExternalStorageDirectory().absolutePath }+ .getOrDefault(FfmpegCommand.DEFAULT_SHARED_STORAGE_ROOT)++ companion object {+ /**+ * Per-file input cap. Lower than [MediaEditTool.MAX_MEDIA_BYTES] because+ * every byte crosses the Gotcha/Termux uid boundary through FUSE, which+ * the `termux_filesystem` skill notes is slow above ~100MB — and unlike a+ * transmux, this decodes and re-encodes the whole stream.+ */+ const val MAX_INPUT_BYTES = 512L * 1024 * 1024++ /**+ * Ceiling for one conversion. Audio re-encoding is roughly realtime-over-N+ * on a phone, so this covers a long album side while staying under+ * [TermuxTool]'s own 600s hard limit.+ */+ const val TIMEOUT_SECONDS = 480++ /**+ * [TermuxTool.formatResult] always opens with this. Its presence is how a+ * command that *ran and failed* is told apart from Termux itself being+ * unavailable — the latter carries its own well-written message from+ * [TermuxMessages], which should reach the model unaltered rather than be+ * rewritten in ffmpeg's terms.+ */+ private const val SHELL_RESULT_PREFIX = "exit code:"+ }++ /**+ * Converts [input] to [output], choosing the codec from [output]'s extension.+ *+ * @param bitrate optional `-b:a` value ("192k", or a bare kbps number).+ * Ignored for the lossless targets, where it has no meaning.+ */+ suspend fun convert(+ input: String,+ output: String,+ bitrate: String? = null,+ overwrite: Boolean = false+ ): ToolResult {+ val target = targetFor(output) ?: return unsupportedTarget(output)+ val normalisedBitrate = resolveBitrate(bitrate).unwrapString { return it }++ val source = resolveInput(input).unwrap { return it }+ val destination = resolveOutput(output, source, overwrite).unwrap { return it }++ val command = FfmpegCommand.buildAudioConversion(+ inputCanonical = source.canonicalPath,+ outputCanonical = destination.canonicalPath,+ target = target,+ bitrate = normalisedBitrate,+ sharedRoot = sharedRoot+ )++ val result = termux.runCommand(command = command, timeoutSeconds = TIMEOUT_SECONDS)+ if (!result.success) return interpretFailure(result, source, destination)++ // ffmpeg reports success on some malformed inputs after writing nothing.+ if (!destination.exists() || destination.length() == 0L) {+ return ToolResult.error(+ "ffmpeg reported success but '${destination.canonicalPath}' is missing or empty. " ++ "The input may not contain a decodable audio track — check it with media_edit " ++ "operation='info'."+ )+ }+ val quality = if (target.isLossless) {+ "lossless ${target.extension.uppercase()}"+ } else {+ "${normalisedBitrate ?: target.bitrate} ${target.extension.uppercase()}"+ }+ return ToolResult.ok(+ "Converted '${source.name}' to $quality at '${destination.canonicalPath}' — " ++ "${resolver.formatSize(source.length())} became ${resolver.formatSize(destination.length())}. " ++ "This ran through Termux's ffmpeg on the device; the file was never uploaded anywhere."+ )+ }++ // ---- validation ----++ private fun targetFor(output: String): FfmpegCommand.Target? =+ FfmpegCommand.audioTargetFor(File(output).extension)++ private fun unsupportedTarget(output: String): ToolResult {+ val extension = File(output).extension.ifEmpty { "no extension" }+ return ToolResult.error(+ "Output '$output' has $extension, which this tool does not convert to. Supported audio targets: " ++ "${FfmpegCommand.describeAudioTargets()}. For video — trimming, muting, compressing, joining — " ++ "use media_edit instead; converting a video container is not something this tool does yet."+ )+ }++ private fun resolveBitrate(bitrate: String?): Result<String?> {+ if (bitrate.isNullOrBlank()) return Result.success(null)+ val normalised = FfmpegCommand.normaliseBitrate(bitrate)+ ?: return Result.failure(+ ResultCarrier(+ ToolResult.error(+ "bitrate '$bitrate' is not a bitrate. Write it as kbps, e.g. '192k' or '320k', between " ++ "${FfmpegCommand.MIN_BITRATE_KBPS} and ${FfmpegCommand.MAX_BITRATE_KBPS}."+ )+ )+ )+ return Result.success(normalised)+ }++ private fun resolveInput(path: String): Result<File> {+ val file = when (val resolved = resolver.resolveForRead(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkReadPermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (!file.exists()) {+ return fail(+ "'$path' does not exist (resolved: ${file.canonicalPath}). You may use list_files or glob to find it."+ )+ }+ if (!file.isFile) return fail("'$path' is not a regular file.")+ if (file.length() > MAX_INPUT_BYTES) {+ return fail(+ "'${file.name}' is ${resolver.formatSize(file.length())}; the limit for conversion is " ++ "${resolver.formatSize(MAX_INPUT_BYTES)}, because every byte crosses between Gotcha and " ++ "Termux. Trim it with media_edit first if only part of it is wanted."+ )+ }+ unreachableFromTermux(file, "Input")?.let { return Result.failure(ResultCarrier(it)) }+ return Result.success(file)+ }++ private fun resolveOutput(path: String, input: File, overwrite: Boolean): Result<File> {+ val file = when (val resolved = resolver.resolveForWrite(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkWritePermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (file.isDirectory) {+ return fail("Output '$path' is a directory. Give the full path of the file to write.")+ }+ if (file.canonicalPath == input.canonicalPath) {+ return fail(+ "Output cannot be the same file as the input — ffmpeg would truncate it before reading it. " ++ "Write to a new path such as '${input.nameWithoutExtension}.${File(path).extension}'."+ )+ }+ if (file.exists() && !overwrite) {+ return fail(+ "'${file.canonicalPath}' already exists. Pass overwrite=true to replace it, " ++ "or choose a different output path."+ )+ }+ file.parentFile?.let { parent ->+ if (!parent.exists() && !parent.mkdirs()) {+ return fail("Could not create the output directory '${parent.canonicalPath}'.")+ }+ }+ unreachableFromTermux(file, "Output")?.let { return Result.failure(ResultCarrier(it)) }+ return Result.success(file)+ }++ /**+ * Gotcha's own sandbox is invisible to Termux — different uid, private+ * directory — so a path there cannot be converted however valid it looks to+ * Gotcha. Caught here rather than left to ffmpeg, which would report a+ * missing file and send the model hunting for a typo.+ */+ private fun unreachableFromTermux(file: File, role: String): ToolResult? {+ if (FfmpegCommand.isReachableFromTermux(file.canonicalPath, sharedRoot)) return null+ return ToolResult.error(+ "$role path '${file.canonicalPath}' is inside Gotcha's private storage, which Termux cannot see — " ++ "they run as different Android users. Use a shared-storage path instead, under " ++ "$sharedRoot/Music, /Download or /Documents, which both can reach."+ )+ }++ // ---- failure interpretation ----++ /**+ * Turns a failed run into something the model can act on.+ *+ * A result that never reached the shell — Termux missing, the plugin API+ * absent, the RUN_COMMAND permission ungranted — already carries a message+ * written for exactly that situation, and a permission result carries the+ * grant flow with it. Those pass through untouched; only ffmpeg's own+ * failures are rewritten.+ */+ private fun interpretFailure(result: ToolResult, input: File, output: File): ToolResult {+ if (result.needsPermission != null) return result+ if (!result.message.trimStart().startsWith(SHELL_RESULT_PREFIX)) return result++ val text = result.message+ val detail = text.substringAfter("stderr:", "").trim().ifEmpty { text }+ return when {+ text.contains("not found", ignoreCase = true) -> ToolResult.error(+ "Termux has no ffmpeg installed, which is what does the conversion. Ask the user to open Termux " ++ "and run 'pkg install ffmpeg' (it is a large download, so say that), then try again. " ++ "You may also run it yourself with run_termux_command if the user agrees."+ )+ text.contains("No such file or directory", ignoreCase = true) -> ToolResult.error(+ "ffmpeg could not see '${input.canonicalPath}', although Gotcha can. This almost always means the " ++ "user has never run 'termux-setup-storage' in Termux, without which Termux sees " ++ "$sharedRoot as empty. Ask them to open Termux once, run " ++ "'termux-setup-storage' and grant the storage prompt, then try again."+ )+ text.contains("Unknown encoder", ignoreCase = true) ||+ text.contains("Unknown decoder", ignoreCase = true) -> ToolResult.error(+ "This build of Termux's ffmpeg does not carry the codec needed for " ++ "'${output.extension}'. Ask the user to run 'pkg upgrade ffmpeg', or pick another format — " ++ "${FfmpegCommand.describeAudioTargets()}. Detail: $detail"+ )+ text.contains("Invalid data found", ignoreCase = true) -> ToolResult.error(+ "ffmpeg could not decode '${input.name}' — it is corrupt, incomplete, or not actually audio. " ++ "Check it with media_edit operation='info'."+ )+ text.contains("Permission denied", ignoreCase = true) -> ToolResult.error(+ "Termux was refused access to '${output.canonicalPath}'. If the user has run " ++ "'termux-setup-storage', the folder may still be one Android does not let other apps write. " ++ "Try $sharedRoot/Download instead."+ )+ else -> ToolResult.error("The conversion failed. ffmpeg said: $detail")+ }+ }++ // ---- shared plumbing ----++ /** Carries an already-formed [ToolResult] (permission or validation) out of a helper. */+ private class ResultCarrier(val result: ToolResult) : Exception(result.message)++ private fun fail(message: String): Result<File> = Result.failure(ResultCarrier(ToolResult.error(message)))++ private inline fun Result<File>.unwrap(onFailure: (ToolResult) -> Nothing): File =+ fold(+ onSuccess = { it },+ onFailure = { e -> onFailure((e as? ResultCarrier)?.result ?: ToolResult.error(e.message.orEmpty())) }+ )++ private inline fun Result<String?>.unwrapString(onFailure: (ToolResult) -> Nothing): String? =+ fold(+ onSuccess = { it },+ onFailure = { e -> onFailure((e as? ResultCarrier)?.result ?: ToolResult.error(e.message.orEmpty())) }+ )+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex f0fba1a..d423783 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -18,7 +18,7 @@ object ToolCategories {)private val backgroundTools = setOf(- "edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit",+ "edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit", "media_convert","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 ed417d3..895aeab 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1389,6 +1389,58 @@ object ToolDefinitions {})+ val mediaConvert = tool(+ "media_convert",+ "Convert an audio file from one format to another on-device, using Termux's ffmpeg. This is the ONLY " ++ "way to produce an MP3: Android ships no MP3 encoder, so media_edit physically cannot write one. " ++ "Targets: .mp3, .m4a, .aac, .ogg, .opus, .wav, .flac — the format is taken from the output " ++ "extension. The file never leaves the device. Needs Termux installed with the ffmpeg package; if " ++ "it is missing the error says exactly what to install. For everything other than format — " ++ "trimming, muting, compressing, changing speed, joining — use media_edit, which needs no setup. " ++ "This does not convert video containers.",+ schema {+ putJsonObject("properties") {+ putJsonObject("input") {+ put("type", "string")+ put(+ "description",+ "Path of the source audio or video file to take the audio from, e.g. " ++ "'/sdcard/Music/recording.m4a'. Must be on shared storage — Termux cannot see " ++ "Gotcha's private folders."+ )+ }+ putJsonObject("output") {+ put("type", "string")+ put(+ "description",+ "Path to write, its extension choosing the format: '.mp3', '.m4a', '.aac', '.ogg', " ++ "'.opus', '.wav' or '.flac'. Must be on shared storage and cannot be the input."+ )+ }+ putJsonObject("bitrate") {+ put("type", "string")+ put(+ "description",+ "Audio bitrate as kbps, e.g. '192k' or '320k'. Defaults to 192k (128k for Opus). " ++ "Ignored for .wav and .flac, which are lossless."+ )+ }+ 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("input")+ add("output")+ }+ }+ )+val edit = tool("edit","Replace exact text in a file, for surgical edits without rewriting it. oldString " +@@ -2620,6 +2672,8 @@ object ToolDefinitions {pdfEdit,// Audio/video editing (Operator only)mediaEdit,+ // Audio format conversion via Termux ffmpeg (Operator only)+ mediaConvert,// 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 6bb1659..d07b1ae 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -64,6 +64,7 @@ class ToolExecutor(private val editTool = EditTool(appContext)private val pdfTool = PdfTool(appContext)private val mediaEditTool = MediaEditTool(appContext)+ private val mediaConvertTool = MediaConvertTool(appContext)private val globTool = GlobTool(appContext)private val grepTool = GrepTool(appContext)private val accessibilityTool = AccessibilityTool(appContext)@@ -245,6 +246,12 @@ class ToolExecutor(speed = args["speed"]?.jsonPrimitive?.doubleOrNull,overwrite = args.requireBoolean("overwrite") ?: false)+ "media_convert" -> mediaConvertTool.convert(+ input = args.requireString("input") ?: return missing("input"),+ output = args.requireString("output") ?: return missing("output"),+ bitrate = args.requireString("bitrate"),+ 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/FfmpegCommandTest.kt b/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.ktindex 4c009c8..a2b7da7 100644--- a/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.kt+++ b/app/src/test/java/com/gotcha/tools/FfmpegCommandTest.kt@@ -79,6 +79,16 @@ class FfmpegCommandTest {assertEquals("/data/data/com.gotcha/files/a.m4a", FfmpegCommand.termuxPath("/data/data/com.gotcha/files/a.m4a"))}+ @Test+ fun `a secondary android user's storage root is honoured`() {+ // /storage/emulated/10 is a second profile; hardcoding the primary root+ // would point ffmpeg at another user's files or at nothing at all.+ val secondary = "/storage/emulated/10"+ assertEquals("/sdcard/Music/a.mp3", FfmpegCommand.termuxPath("$secondary/Music/a.mp3", secondary))+ assertTrue(FfmpegCommand.isReachableFromTermux("$secondary/Music/a.mp3", secondary))+ assertFalse(FfmpegCommand.isReachableFromTermux("/storage/emulated/0/Music/a.mp3", secondary))+ }+@Testfun `reachability follows the same boundary as translation`() {assertTrue(FfmpegCommand.isReachableFromTermux("/storage/emulated/0/Download/a.m4a"))diff --git a/app/src/test/java/com/gotcha/tools/MediaConvertToolTest.kt b/app/src/test/java/com/gotcha/tools/MediaConvertToolTest.ktnew file mode 100644index 0000000..aa783e8--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/MediaConvertToolTest.kt@@ -0,0 +1,178 @@+package com.gotcha.tools++import android.os.Environment+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.ShadowExternalStorageManager+import kotlinx.coroutines.runBlocking+import org.junit.After+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++/**+ * `media_convert`'s guards — every refusal that happens before Termux is asked+ * to do anything.+ *+ * The conversion itself cannot be tested at any tier below INSTRUMENTED, and not+ * even there without Termux and its ffmpeg package installed on the device. What+ * *is* testable is everything that decides whether a call ever reaches ffmpeg,+ * which is also where a mistake costs a user their file. The command string that+ * would be sent is covered separately and exhaustively by [FfmpegCommandTest].+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class MediaConvertToolTest {++ private lateinit var tool: MediaConvertTool+ private lateinit var shared: File+ private lateinit var sandbox: File++ @Before+ fun setUp() {+ // Shared storage is where this tool insists its files live, so the tests+ // need "All files access" granted to reach any of the interesting guards.+ ShadowExternalStorageManager.granted = true+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ tool = MediaConvertTool(context)+ shared = File(Environment.getExternalStorageDirectory(), "convert").apply {+ deleteRecursively()+ mkdirs()+ }+ sandbox = File(context.filesDir, "convert").apply {+ deleteRecursively()+ mkdirs()+ }+ }++ @After+ fun tearDown() {+ ShadowExternalStorageManager.resetGranted()+ }++ /** A file that exists but is not decodable — every case here refuses before ffmpeg runs. */+ private fun placeholder(dir: File, name: String): File =+ File(dir, name).apply { writeBytes(ByteArray(1024)) }++ private fun convert(+ input: String,+ output: String,+ bitrate: String? = null,+ overwrite: Boolean = false+ ): ToolResult = runBlocking { tool.convert(input, output, bitrate, overwrite) }++ // ---- target format ----++ @Test+ fun `an unsupported output format lists what is supported`() {+ val result = convert(placeholder(shared, "a.m4a").path, File(shared, "out.xyz").path)+ assertFalse(result.success)+ assertTrue(result.message.contains(".mp3"))+ assertTrue(result.message.contains(".flac"))+ }++ @Test+ fun `a video output is redirected to media_edit rather than attempted`() {+ val result = convert(placeholder(shared, "a.m4a").path, File(shared, "out.mp4").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("media_edit"))+ }++ @Test+ fun `every advertised target is actually accepted`() {+ // Guards against the tool description promising a format the table lacks.+ FfmpegCommand.AUDIO_TARGETS.keys.forEach { ext ->+ val result = convert(placeholder(shared, "a.m4a").path, File(shared, "out.$ext").path)+ assertFalse(ext, result.message.contains("does not convert to"))+ }+ }++ // ---- bitrate ----++ @Test+ fun `a nonsense bitrate is refused before anything runs`() {+ listOf("loud", "192kbps", "192k; reboot").forEach { bad ->+ val result = convert(+ placeholder(shared, "a.m4a").path,+ File(shared, "out.mp3").path,+ bitrate = bad+ )+ assertFalse(bad, result.success)+ assertTrue(bad, result.message.contains("not a bitrate"))+ }+ }++ // ---- the uid boundary, which is this tool's peculiar failure mode ----++ @Test+ fun `an input in Gotcha's private storage is refused with the reason`() {+ val result = convert(placeholder(sandbox, "a.m4a").path, File(shared, "out.mp3").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("Termux cannot see"))+ assertTrue("should suggest where to put it", result.message.contains("Music"))+ }++ @Test+ fun `an output in Gotcha's private storage is refused too`() {+ val result = convert(placeholder(shared, "a.m4a").path, File(sandbox, "out.mp3").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("Termux cannot see"))+ }++ // ---- input resolution ----++ @Test+ fun `a missing input suggests how to find it`() {+ val result = convert(File(shared, "nope.m4a").path, File(shared, "out.mp3").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("glob"))+ }++ @Test+ fun `a directory is not accepted as input`() {+ val result = convert(shared.path, File(shared, "out.mp3").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("not a regular file"))+ }++ // ---- output resolution ----++ @Test+ fun `converting a file onto itself is refused`() {+ val same = placeholder(shared, "a.mp3")+ val result = convert(same.path, same.path, overwrite = true)+ assertFalse(result.success)+ assertTrue(result.message.contains("same file"))+ }++ @Test+ fun `an existing output is refused unless overwrite is passed`() {+ val existing = File(shared, "out.mp3").apply { writeBytes(ByteArray(8)) }+ val result = convert(placeholder(shared, "a.m4a").path, existing.path)+ assertFalse(result.success)+ assertTrue(result.message.contains("overwrite=true"))+ assertTrue("the file in the way must be untouched", existing.length() == 8L)+ }++ @Test+ fun `a directory named like a target file is still refused as a directory`() {+ // A bare directory path has no extension and is caught by the format check.+ // The one that reaches the directory guard is a folder called "out.mp3",+ // which ffmpeg would otherwise fail on with something unreadable.+ val trap = File(shared, "out.mp3").apply { mkdirs() }+ val result = convert(placeholder(shared, "a.m4a").path, trap.path)+ assertFalse(result.success)+ assertTrue(result.message.contains("is a directory"))+ }++ @Test+ fun `a bare directory path is refused for having no format`() {+ val result = convert(placeholder(shared, "a.m4a").path, shared.path)+ assertFalse(result.success)+ assertTrue(result.message.contains("does not convert to"))+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 2cee43c..d7b85db 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -425,6 +425,15 @@],"notes": "timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input or over any concat input, existing-output refusal, directory output, the MP4/M4A container check and the .mp3 redirect to .m4a, speed bounds and the pointless speed=1.0 re-encode, non-positive compress height, and concat's input-count limits. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so the output of trim, extract_audio, remove_audio, compress, speed and concat must be verified by hand on hardware"},+ {+ "tool": "media_convert",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.MediaConvertToolTest",+ "com.gotcha.tools.FfmpegCommandTest"+ ],+ "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": "glob","tier": "ROBOLECTRIC",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex c8b2371..bec678c 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` | 21 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 22 | 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** | **109** | |+| **Total** | **110** | |-**45 of 109** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**46 of 110** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -65,6 +65,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `lock_screen` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `mark_email_read` | `UNIT` | `EmailToolsTest` — read/unread toggle routed to the right backend || `media_control` | `UNIT` | `MediaSelectionTest` — action parsing and active-session selection |+| `media_convert` | `ROBOLECTRIC` | `MediaConvertToolTest`, `FfmpegCommandTest` — 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 || `media_edit` | `ROBOLECTRIC` | `MediaEditToolTest`, `MediaTimeSpecTest` — timecode parsing and trim-window arithmetic on the JVM (m:ss, h:mm:ss, unit and plain-seconds forms, ambiguous-field and backwards-window refusals, clamping an over-long end), plus every guard that runs before a codec is touched: unknown operation, missing arguments, trim with no bounds, refusal to write back over the input or over any concat input, existing-output refusal, directory output, the MP4/M4A container check and the .mp3 redirect to .m4a, speed bounds and the pointless speed=1.0 re-encode, non-positive compress height, and concat's input-count limits. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so the output of trim, extract_audio, remove_audio, compress, speed and concat must be verified by hand on hardware || `notion_append_to_page` | `UNIT` | `NotionToolsTest` — block append request shape || `notion_create_page` | `UNIT` | `NotionToolsTest` — parent/title handling and request shape |