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.

feat(media): wire media_edit into the catalog with info, trim and track splitting

Durganshu7b42b1988084
diff --git a/app/src/main/assets/skills/media_editing.json b/app/src/main/assets/skills/media_editing.json
new file mode 100644
index 0000000..0f0019d
--- /dev/null
+++ b/app/src/main/assets/skills/media_editing.json
@@ -0,0 +1,27 @@
+{
+ "id": "media_editing",
+ "targetPackageNames": [],
+ "title": "Audio & Video Editing Skills",
+ "description": "Trim clips and split audio from video on-device with media_edit instead of a web converter or an editor app.",
+ "requiresTools": [
+ "media_edit"
+ ],
+ "keywords": [
+ "video",
+ "videos",
+ "audio",
+ "clip",
+ "trim",
+ "cut",
+ "mute",
+ "recording",
+ "footage",
+ "mp4",
+ "m4a",
+ "soundtrack",
+ "voice",
+ "memo",
+ "podcast"
+ ],
+ "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).\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\nThese operations copy the streams instead of re-encoding them, so they are fast even on a long video and lose no quality at all. The result message tells you which happened; if it ever says the file was re-encoded, pass that on, because repeated re-encoding visibly degrades a file.\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\nThe hard limits, which you must state plainly rather than work around:\n• It CANNOT compress, resize, change resolution or bitrate, change playback speed, join or concatenate files, add background music, overlay text or a watermark, fade audio, or adjust volume. These are not yet 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 cutting a middle section out and rejoining the ends (that needs concatenation).\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/MediaEditTool.kt b/app/src/main/java/com/gotcha/tools/MediaEditTool.kt
index 7a7391e..e74f970 100644
--- a/app/src/main/java/com/gotcha/tools/MediaEditTool.kt
+++ b/app/src/main/java/com/gotcha/tools/MediaEditTool.kt
@@ -104,8 +104,10 @@ class MediaEditTool(private val context: Context) {
)
}
val file = resolveInput(input).unwrap { return it }
- val probe = MediaProbe.of(file)
+ // Path validation before probing: it is cheaper, and it fails without
+ // having opened a file the model was never going to be allowed to write.
val target = resolveOutput(output, file, overwrite).unwrap { return it }
+ val probe = MediaProbe.of(file)
val window = MediaTimeSpec.parseRange(start, end, probe.durationMs)
.getOrElse { return ToolResult.error(it.message.orEmpty()) }
@@ -126,6 +128,7 @@ class MediaEditTool(private val context: Context) {
private suspend fun extractAudio(input: String, output: String, overwrite: Boolean): ToolResult {
val file = resolveInput(input).unwrap { return it }
+ val target = resolveOutput(output, file, overwrite).unwrap { return it }
val probe = MediaProbe.of(file)
if (!probe.hasAudio) {
return ToolResult.error(
@@ -133,7 +136,6 @@ class MediaEditTool(private val context: Context) {
"what a file contains before choosing an operation."
)
}
- val target = resolveOutput(output, file, overwrite).unwrap { return it }
val export = MediaExport(context).run(input = file, output = target, removeVideo = true)
export.failure()?.let { return it }
return ToolResult.ok(
@@ -145,6 +147,7 @@ class MediaEditTool(private val context: Context) {
private suspend fun removeAudio(input: String, output: String, overwrite: Boolean): ToolResult {
val file = resolveInput(input).unwrap { return it }
+ val target = resolveOutput(output, file, overwrite).unwrap { return it }
val probe = MediaProbe.of(file)
if (probe.isAudioOnly) {
return ToolResult.error(
@@ -155,7 +158,6 @@ class MediaEditTool(private val context: Context) {
if (!probe.hasAudio) {
return ToolResult.error("'${file.name}' already has no audio track — there is nothing to remove.")
}
- val target = resolveOutput(output, file, overwrite).unwrap { return it }
val export = MediaExport(context).run(input = file, output = target, removeAudio = true)
export.failure()?.let { return it }
return ToolResult.ok(
diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
index 696eec1..f0fba1a 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",
+ "edit", "write_file", "make_directory", "delete_file", "pdf_edit", "media_edit",
"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 7ab46cb..2a28136 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1288,6 +1288,80 @@ object ToolDefinitions {
}
)
+ val mediaEdit = tool(
+ "media_edit",
+ "Edit an audio or video file on-device: trim a window out of it, pull its audio track into a " +
+ "separate file, or strip the audio from a video. Also reports duration, resolution, tracks and " +
+ "codecs with operation='info' — call that FIRST whenever you need a timecode, so you are trimming " +
+ "against the real duration rather than a guess. Works the same on video and on audio-only files. " +
+ "Every operation writes a NEW file and never modifies the input; the output cannot be the input, " +
+ "because the encoder writes it while still reading from it. These operations copy the streams " +
+ "rather than re-encoding, so they are fast and lossless. It CANNOT re-encode, compress, resize, " +
+ "change speed, join files, or add music yet, and it cannot open DRM-protected media at all — say " +
+ "so plainly instead of attempting a workaround.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("operation") {
+ put("type", "string")
+ putJsonArray("enum") { MediaEditTool.OPERATIONS.forEach { add(it) } }
+ put(
+ "description",
+ "info = duration, tracks, resolution and codecs; trim = keep the window between " +
+ "'start' and 'end'; extract_audio = write the audio track as its own file; " +
+ "remove_audio = write the video with its audio dropped."
+ )
+ }
+ putJsonObject("input") {
+ put("type", "string")
+ put(
+ "description",
+ "Path of the source audio or video file, e.g. '/sdcard/DCIM/Camera/VID_0001.mp4'. " +
+ "Required by every operation."
+ )
+ }
+ putJsonObject("output") {
+ put("type", "string")
+ put(
+ "description",
+ "Path of the file to write. Required by every operation except info. Must end in .mp4 " +
+ "(video) or .m4a (audio only) — the muxer always writes an MP4 container. Cannot be " +
+ "the same path as 'input'."
+ )
+ }
+ putJsonObject("start") {
+ put("type", "string")
+ put(
+ "description",
+ "trim only: where the kept window begins. Timecodes are '1:23' (m:ss), '1:02:03' " +
+ "(h:mm:ss), '90s', '1m30s' or plain seconds like '12.5'. Defaults to the start of " +
+ "the file."
+ )
+ }
+ putJsonObject("end") {
+ put("type", "string")
+ put(
+ "description",
+ "trim only: where the kept window ends, in the same timecode formats, or 'end' for the " +
+ "end of the file. Defaults to the end of the file. Give at least one of 'start' " +
+ "and 'end'."
+ )
+ }
+ 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("operation")
+ add("input")
+ }
+ }
+ )
+
val edit = tool(
"edit",
"Replace exact text in a file, for surgical edits without rewriting it. oldString " +
@@ -2517,6 +2591,8 @@ object ToolDefinitions {
edit,
// PDF page-structure editing (Operator only)
pdfEdit,
+ // Audio/video editing (Operator only)
+ mediaEdit,
// Content search and file discovery
glob, grep,
// Web search + fetch
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 8f173e6..61fb3ac 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -62,6 +62,7 @@ class ToolExecutor(
private val todoTool = TodoTool()
private val editTool = EditTool(appContext)
private val pdfTool = PdfTool(appContext)
+ private val mediaEditTool = MediaEditTool(appContext)
private val globTool = GlobTool(appContext)
private val grepTool = GrepTool(appContext)
private val accessibilityTool = AccessibilityTool(appContext)
@@ -232,6 +233,14 @@ class ToolExecutor(
overwrite = args.requireBoolean("overwrite") ?: false,
confirmed = args.requireBoolean("confirmed") ?: false
)
+ "media_edit" -> mediaEditTool.edit(
+ operation = args.requireString("operation") ?: return missing("operation"),
+ input = args.requireString("input"),
+ output = args.requireString("output"),
+ start = args.requireString("start"),
+ end = args.requireString("end"),
+ 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/MediaEditToolTest.kt b/app/src/test/java/com/gotcha/tools/MediaEditToolTest.kt
new file mode 100644
index 0000000..b43ba6b
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/MediaEditToolTest.kt
@@ -0,0 +1,168 @@
+package com.gotcha.tools
+
+import androidx.test.core.app.ApplicationProvider
+import kotlinx.coroutines.runBlocking
+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_edit`'s guards — every refusal that happens *before* a codec is touched.
+ *
+ * The export path itself cannot be tested here at any tier below INSTRUMENTED:
+ * Media3 Transformer drives MediaCodec, which is native and has no Robolectric
+ * shadow, so a real device is the only place a trim can actually be exercised.
+ * That makes these guards worth pinning down all the more — they are the part
+ * that decides whether a wrong call destroys a file or returns an explanation,
+ * and they are reachable without hardware precisely because [MediaEditTool]
+ * validates paths before it opens anything.
+ *
+ * Everything stays inside the app sandbox so [FileResolver] grants access
+ * without a permission stub.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class MediaEditToolTest {
+
+ private lateinit var tool: MediaEditTool
+ private lateinit var dir: File
+
+ @Before
+ fun setUp() {
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ tool = MediaEditTool(context)
+ dir = File(context.filesDir, "mediatest").apply {
+ deleteRecursively()
+ mkdirs()
+ }
+ }
+
+ /**
+ * A file that exists and is plausibly sized, but is not decodable. Every
+ * assertion below is about a refusal that must land before anything tries to
+ * parse it, so the bytes never matter.
+ */
+ private fun placeholder(name: String): File =
+ File(dir, name).apply { writeBytes(ByteArray(1024)) }
+
+ private fun edit(
+ operation: String,
+ input: String? = null,
+ output: String? = null,
+ start: String? = null,
+ end: String? = null,
+ overwrite: Boolean = false
+ ): ToolResult = runBlocking {
+ tool.edit(operation, input, output, start, end, overwrite)
+ }
+
+ // ---- operation and argument validation ----
+
+ @Test
+ fun `an unknown operation lists the valid ones`() {
+ val result = edit("sharpen", input = placeholder("a.mp4").path)
+ assertFalse(result.success)
+ MediaEditTool.OPERATIONS.forEach { assertTrue(it, result.message.contains(it)) }
+ }
+
+ @Test
+ fun `a missing input names the parameter and the operation`() {
+ val result = edit("info")
+ assertFalse(result.success)
+ assertTrue(result.message.contains("input"))
+ assertTrue(result.message.contains("info"))
+ }
+
+ @Test
+ fun `a missing output is refused for every writing operation`() {
+ listOf("trim", "extract_audio", "remove_audio").forEach { op ->
+ val result = edit(op, input = placeholder("a.mp4").path, start = "1")
+ assertFalse(op, result.success)
+ assertTrue(op, result.message.contains("output"))
+ }
+ }
+
+ @Test
+ fun `trim with neither bound is refused rather than copying the file`() {
+ val result = edit("trim", input = placeholder("a.mp4").path, output = File(dir, "out.mp4").path)
+ assertFalse(result.success)
+ assertTrue(result.message.contains("at least one"))
+ }
+
+ @Test
+ fun `a malformed timecode is reported without writing anything`() {
+ val out = File(dir, "out.mp4")
+ val result = edit("trim", input = placeholder("a.mp4").path, output = out.path, start = "banana")
+ assertFalse(result.success)
+ assertFalse(out.exists())
+ }
+
+ // ---- input resolution ----
+
+ @Test
+ fun `a missing input file suggests how to find it`() {
+ val result = edit("info", input = File(dir, "nope.mp4").path)
+ assertFalse(result.success)
+ assertTrue(result.message.contains("glob"))
+ }
+
+ @Test
+ fun `a directory is not accepted as input`() {
+ val result = edit("info", input = dir.path)
+ assertFalse(result.success)
+ assertTrue(result.message.contains("not a regular file"))
+ }
+
+ // ---- output resolution: the guards that protect a user's files ----
+
+ @Test
+ fun `writing back over the input is refused with the reason`() {
+ val input = placeholder("clip.mp4")
+ val result = edit("trim", input = input.path, output = input.path, start = "1", overwrite = true)
+ assertFalse(result.success)
+ assertTrue(result.message.contains("same file"))
+ // The suggested alternative has to be a usable path, not a shrug.
+ assertTrue(result.message.contains("clip-edited.mp4"))
+ }
+
+ @Test
+ fun `an existing output is refused unless overwrite is passed`() {
+ val existing = File(dir, "out.mp4").apply { writeBytes(ByteArray(8)) }
+ val result = edit("trim", input = placeholder("a.mp4").path, output = existing.path, start = "1")
+ assertFalse(result.success)
+ assertTrue(result.message.contains("overwrite=true"))
+ // Refusal must not have touched the file that was in the way.
+ assertTrue(existing.length() == 8L)
+ }
+
+ @Test
+ fun `a directory as output is refused`() {
+ val result = edit("trim", input = placeholder("a.mp4").path, output = dir.path, start = "1")
+ assertFalse(result.success)
+ assertTrue(result.message.contains("is a directory"))
+ }
+
+ @Test
+ fun `an output container the muxer cannot write is refused`() {
+ listOf("out.mp3", "out.wav", "out.mkv", "out").forEach { name ->
+ val result = edit("trim", input = placeholder("a.mp4").path, output = File(dir, name).path, start = "1")
+ assertFalse(name, result.success)
+ assertTrue(name, result.message.contains(".mp4") && result.message.contains(".m4a"))
+ }
+ }
+
+ @Test
+ fun `the supported output containers pass the extension guard`() {
+ // These get past validation and fail later at the codec, which Robolectric
+ // has no shadow for — the point is only that the guard let them through.
+ listOf("out.mp4", "out.M4A").forEach { name ->
+ val result = edit("trim", input = placeholder("a.mp4").path, output = File(dir, name).path, start = "1")
+ assertFalse(name, result.message.contains("name it .mp4"))
+ }
+ }
+}
diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.json
index 61be20f..9154921 100644
--- a/app/src/test/resources/feature-test-coverage.json
+++ b/app/src/test/resources/feature-test-coverage.json
@@ -416,6 +416,15 @@
],
"notes": "every operation round-tripped through pdfbox (merge order, split naming, extract/delete page identity, cumulative rotation), password-protected files at 40/128/256-bit, and the guards: overwrite refusal, safe write-back over the input, delete-all refusal, non-PDF signature rejection and page-range arithmetic"
},
+ {
+ "tool": "media_edit",
+ "tier": "ROBOLECTRIC",
+ "tests": [
+ "com.gotcha.tools.MediaEditToolTest",
+ "com.gotcha.tools.MediaTimeSpecTest"
+ ],
+ "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, existing-output refusal, directory output and the MP4/M4A container check. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so trim/extract_audio/remove_audio output must be verified by hand on hardware"
+ },
{
"tool": "glob",
"tier": "ROBOLECTRIC",
diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.md
index 4eef1b7..d4585f3 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` | 20 | JVM test against Robolectric's Android framework, often across several API levels. |
+| `ROBOLECTRIC` | 21 | 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** | **108** | |
+| **Total** | **109** | |
-**44 of 108** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.
+**45 of 109** 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_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, existing-output refusal, directory output and the MP4/M4A container check. The export itself is device-only — Media3 Transformer drives MediaCodec, which is native and has no Robolectric shadow, so trim/extract_audio/remove_audio output 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 |
| `pause_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |