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: Implement standardized file storage and readable chat folder names
Durganshu Mishraf8d5ebf282e7
diff --git a/RUNNING.md b/RUNNING.mdindex c64626c..f7c89e8 100644--- a/RUNNING.md+++ b/RUNNING.md@@ -71,6 +71,27 @@ checks on every run, so any new finding fails CI immediately.The unit tests shell out to a POSIX `sh` (TerminalTool), so they need Linux,macOS, or Git Bash — on plain Windows they fail; use CI instead.+## On-disk layout++All Gotcha-managed files on shared storage live under one root, `data/GotchaStorage.kt`:++```+/storage/emulated/0/Gotcha/+ chats/<Slug_shortId>/ <- agent working dir (cwd for file tools)+ Pictures/ <- camera captures+ Recordings/ <- audio captures+ Screenshots/ <- agent read_screen_raw captures+ .debug/ <- perception overlay dumps+ calls/<sessionId>/ <- voice-call working dirs+ old_chats/<Slug_shortId>/ <- archived on chat delete+ Screenshots/ <- assistive-ball + Lens captures+ Downloads/+```++Chat folders are named `slug(title)_<first 8 chars of the session UUID>` and renamed in place+when the title becomes known. Deleting a chat moves its working directory to `old_chats/` instead+of deleting it. See `STORAGE_PLAN.md` for the full rationale.+## 5. Configure the LLM (required before chatting)The app talks to **any OpenAI-compatible `/chat/completions` endpoint**. On thediff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex c5d8680..71d3b05 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -438,11 +438,8 @@ class MainActivity : ComponentActivity() {).clearCache()},onClearDebugScreenshots = {- val baseDir = java.io.File("/storage/emulated/0/Gotcha")- if (baseDir.exists()) {- baseDir.walkTopDown()- .filter { it.isFile && it.name.startsWith("screenshot_overlay_") }- .forEach { it.delete() }+ com.gotcha.data.GotchaStorage.chatsRoot().listFiles()?.forEach { chatDir ->+ java.io.File(chatDir, ".debug").deleteRecursively()}},onBack = { currentRoute = Route.HOME },diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 90a7114..c0531a2 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -4,6 +4,7 @@ import android.content.Contextimport android.util.Logimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.ChatSession+import com.gotcha.data.GotchaStorageimport com.gotcha.data.Settingsimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient@@ -54,7 +55,7 @@ class AgentEngine(private val historyRepository: ChatHistoryRepository,private val settingsProvider: () -> Settings,private val clientProvider: () -> LLMClient?,- private val workingDirRoot: String = "/storage/emulated/0/Gotcha/chats",+ private val workingDirRoot: String = GotchaStorage.chatsRoot().absolutePath,/** Supplies the current on-screen transcript to persist alongside history. */private val displayMessagesProvider: () -> List<UiMessage> = { emptyList() },/** Supplies the active agent mode to persist so it survives restarts. */@@ -164,24 +165,39 @@ class AgentEngine()}- fun workingDir(): java.io.File = java.io.File(workingDirRoot, sessionId ?: "unknown")+ private fun resolveWorkingDir(create: Boolean): java.io.File {+ val id = sessionId ?: "unknown"+ return if (workingDirRoot == GotchaStorage.chatsRoot().absolutePath) {+ // Chat dirs are named "Slug_shortId" and renamed in place as the+ // title becomes known; call working dirs (below) have no title.+ GotchaStorage.ensureChatDir(id, currentTitle(), create)+ } else {+ java.io.File(workingDirRoot, id).also { if (create) it.mkdirs() }+ }+ }++ fun workingDir(): java.io.File = resolveWorkingDir(create = false)/**- * Sets up the per-chat working directory at {workingDirRoot}/{sessionId}/.+ * Sets up the per-chat working directory, renaming it in place if the+ * title has changed since it was created (contents preserved).** Updates [FileResolver.WORKING_DIR_BASE] so file tools resolve relative* paths against this directory.*/- fun setupWorkingDir() {- val dir = workingDir()- if (!dir.exists()) dir.mkdirs()+ fun setupWorkingDir(create: Boolean = true) {+ val dir = resolveWorkingDir(create)FileResolver.WORKING_DIR_BASE = dir.absolutePathLog.d(TAG, "setupWorkingDir: ${dir.absolutePath}")}+ /** Derived from the first user message; stable for the rest of the session. */+ fun currentTitle(): String =+ history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"+suspend fun saveCurrentSession() {val id = sessionId ?: return- val title = history.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"+ val title = currentTitle()historyRepository.saveSession(ChatSession(id = id,@@ -275,7 +291,7 @@ class AgentEngine(// two agents running tool rounds concurrently race last-writer-wins.// The full fix is threading a cwd through ToolExecutor into the file// tools (FileResolver already accepts one); deferred for now.- FileResolver.WORKING_DIR_BASE = workingDir().absolutePath+ setupWorkingDir()checkAndCompactHistory(llm)// Anti-loop guard: if consecutive tool rounds produce the byte-identical// set of tool-call names + results (e.g. a tool that keeps returning the@@ -424,7 +440,7 @@ class AgentEngine(executeToolCalls()saveCurrentSession()// Re-assert after each round; a concurrent engine may have moved it.- FileResolver.WORKING_DIR_BASE = workingDir().absolutePath+ setupWorkingDir()// Anti-loop guard: signature = tool-call names + the tool result text// appended this round. Identical signatures across consecutive rounds@@ -947,7 +963,7 @@ class AgentEngine(private suspend fun captureCompressedScreenshot(drawGrid: Boolean = true): ScreenPerception.CompressedScreenshot? {- val saveDir = java.io.File(FileResolver.WORKING_DIR_BASE, "debug_screenshots")+ val saveDir = GotchaStorage.subdir(workingDir(), GotchaStorage.Kind.DEBUG)return ScreenPerception.compressScreenshot(drawGrid = drawGrid, saveDir = saveDir)}@@ -956,7 +972,7 @@ class AgentEngine(* Used by read_screen_raw for maximum visual detail.*/private suspend fun captureFullResScreenshot(): ScreenPerception.CompressedScreenshot? {- val saveDir = java.io.File(FileResolver.WORKING_DIR_BASE, "debug_screenshots")+ val saveDir = GotchaStorage.subdir(workingDir(), GotchaStorage.Kind.DEBUG)return ScreenPerception.compressScreenshot(maxDimension = 0,drawGrid = false,@@ -1016,8 +1032,7 @@ class AgentEngine("yyyyMMdd_HHmmss",java.util.Locale.US).format(java.util.Date())- val dir = java.io.File(FileResolver.WORKING_DIR_BASE)- if (!dir.exists()) dir.mkdirs()+ val dir = GotchaStorage.subdir(workingDir(), GotchaStorage.Kind.SCREENSHOTS)val file = java.io.File(dir, "screenshot_$ts.png")val rawBytes = android.util.Base64.decode(screenshot.base64,diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 111c8e7..90f32c0 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -22,6 +22,7 @@ import com.gotcha.tools.ScreenPerceptionimport com.gotcha.ui.ConfirmationOverlayimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.flow.MutableSharedFlow@@ -167,9 +168,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A// empty chat; past sessions remain one tap away in the drawer.agentEngine.sessionId = java.util.UUID.randomUUID().toString()agentEngine.tokenCount = 0- agentEngine.setupWorkingDir()+ agentEngine.setupWorkingDir(create = false)_uiState.update { it.copy(activeSessionId = agentEngine.sessionId) }updateContextUsage()+ migrateChatDirsIfNeeded()refreshSessions()}}@@ -629,7 +631,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AagentEngine.history.clear()agentEngine.sessionId = newIdagentEngine.tokenCount = 0- agentEngine.setupWorkingDir()+ agentEngine.setupWorkingDir(create = false)engineTranscript = emptyList()engineAgent = defaultAgent}@@ -643,6 +645,32 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AapplyContextUsage(0)}+ /**+ * One-time migration: rename any pre-existing UUID-named chat working dirs+ * to the readable "Slug_shortId" scheme. Guarded so it only ever runs once.+ */+ private suspend fun migrateChatDirsIfNeeded() {+ val prefs = settingsRepository.prefs+ if (prefs.getBoolean(MIGRATED_CHAT_DIRS_KEY, false)) return+ val sessions = historyRepository.listSessions()+ val chatsRoot = com.gotcha.data.GotchaStorage.chatsRoot()+ for (session in sessions) {+ try {+ val rawDir = java.io.File(chatsRoot, session.id)+ if (rawDir.exists() && rawDir.isDirectory) {+ val target = java.io.File(+ chatsRoot,+ com.gotcha.data.GotchaStorage.chatDirName(session.title, session.id)+ )+ rawDir.renameTo(target)+ }+ } catch (e: Exception) {+ android.util.Log.w("Gotcha", "migrateChatDirsIfNeeded: failed for ${session.id}", e)+ }+ }+ prefs.edit().putBoolean(MIGRATED_CHAT_DIRS_KEY, true).apply()+ }+fun refreshSessions() {viewModelScope.launch {_sessions.value = historyRepository.listSessions()@@ -720,6 +748,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Afun deleteSession(id: String) {viewModelScope.launch {+ withContext(Dispatchers.IO) {+ com.gotcha.data.GotchaStorage.archiveChatDir(id)+ }historyRepository.deleteSession(id)if (agentEngine.sessionId == id) {clearChat()@@ -921,5 +952,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate companion object {const val GATE_TIMEOUT_MS = 120_000L+ const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"}}diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 8bd9abb..1d42337 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -121,11 +121,15 @@ class SttEngine(language: String = ""): Result<String> = withContext(Dispatchers.IO) {val api = audioApi ?: return@withContext Result.failure(Exception("API not configured"))- api.transcribe(- audioFile = audioFile,- model = model,- language = language- )+ try {+ api.transcribe(+ audioFile = audioFile,+ model = model,+ language = language+ )+ } finally {+ audioFile.delete()+ }}// ---- Android STT (SpeechRecognizer) ----diff --git a/app/src/main/java/com/gotcha/data/GotchaStorage.kt b/app/src/main/java/com/gotcha/data/GotchaStorage.ktnew file mode 100644index 0000000..cea502f--- /dev/null+++ b/app/src/main/java/com/gotcha/data/GotchaStorage.kt@@ -0,0 +1,110 @@+package com.gotcha.data++import android.content.Context+import android.media.MediaScannerConnection+import android.os.Environment+import java.io.File++/**+ * Single source of truth for every path Gotcha reads or writes under shared+ * storage. See STORAGE_PLAN.md for the full layout and rationale.+ */+object GotchaStorage {++ private var overrideRootPath: String? = null++ /**+ * Overridable so JVM unit tests can point at a TemporaryFolder. The Android+ * default is computed lazily on first access so plain JUnit tests (no+ * Android framework available) can set this before it's ever touched.+ */+ var rootPath: String+ get() = overrideRootPath ?: File(Environment.getExternalStorageDirectory(), "Gotcha").absolutePath+ set(value) { overrideRootPath = value }++ enum class Kind(val dirName: String) {+ PICTURES("Pictures"),+ RECORDINGS("Recordings"),+ SCREENSHOTS("Screenshots"),+ DEBUG(".debug")+ }++ fun root(): File = File(rootPath)+ fun chatsRoot(): File = File(root(), "chats")+ fun callsRoot(): File = File(root(), "calls")+ fun archiveRoot(): File = File(root(), "old_chats")+ fun screenshotsRoot(): File = File(root(), "Screenshots")+ fun downloadsRoot(): File = File(root(), "Downloads")++ /**+ * Non-alphanumeric runs collapse to a single '-'; leading/trailing '-' trimmed;+ * truncated to 40 chars; blank input falls back to "New-Chat".+ */+ fun slugify(title: String): String {+ val collapsed = title+ .replace(Regex("[^\\p{L}\\p{N}]+"), "-")+ .trim('-')+ .take(40)+ .trim('-')+ return collapsed.ifEmpty { "New-Chat" }+ }++ fun shortId(sessionId: String): String = sessionId.replace("-", "").take(8)++ fun chatDirName(title: String, sessionId: String): String = "${slugify(title)}_${shortId(sessionId)}"++ /** Existing dir for this session under [chatsRoot], matched by "_<shortId>" suffix. */+ fun findChatDir(sessionId: String): File? {+ val suffix = "_${shortId(sessionId)}"+ return chatsRoot().listFiles()?.firstOrNull { it.isDirectory && it.name.endsWith(suffix) }+ }++ /**+ * Resolves the chat directory for [sessionId] / [title], renaming an existing+ * dir in place if the title changed (contents preserved), and creating it+ * (and any renamed target) when [create] is true. Idempotent: calling again+ * with the same title is a no-op beyond returning the same dir.+ */+ fun ensureChatDir(sessionId: String, title: String, create: Boolean = true): File {+ val desiredName = chatDirName(title, sessionId)+ val existing = findChatDir(sessionId)+ val dir = if (existing != null) {+ if (existing.name != desiredName) {+ val target = File(chatsRoot(), desiredName)+ if (existing.renameTo(target)) target else existing+ } else {+ existing+ }+ } else {+ File(chatsRoot(), desiredName)+ }+ if (create) dir.mkdirs()+ return dir+ }++ fun subdir(chatDir: File, kind: Kind): File {+ val dir = File(chatDir, kind.dirName)+ dir.mkdirs()+ return dir+ }++ /** Move chats/<dir> -> old_chats/<dir>, suffixing _<millis> on collision. */+ fun archiveChatDir(sessionId: String) {+ val dir = findChatDir(sessionId) ?: return+ val archive = archiveRoot()+ archive.mkdirs()+ var target = File(archive, dir.name)+ if (target.exists()) {+ target = File(archive, "${dir.name}_${System.currentTimeMillis()}")+ }+ if (!dir.renameTo(target)) {+ dir.copyRecursively(target, overwrite = true)+ dir.deleteRecursively()+ }+ }++ /** Scans [file] into the MediaStore so it shows up in the Gallery. */+ fun publishToGallery(context: Context, file: File) {+ MediaScannerConnection.scanFile(context, arrayOf(file.absolutePath), null, null)+ }+}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 77f67f0..46532b9 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -762,28 +762,14 @@ class AssistiveBallService : Service() {java.util.Locale.US).format(java.util.Date())val fileName = "Screenshot_$timestamp.png"- val contentValues = android.content.ContentValues().apply {- put(android.provider.MediaStore.Images.Media.DISPLAY_NAME, fileName)- put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/png")- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- put(- android.provider.MediaStore.Images.Media.RELATIVE_PATH,- android.os.Environment.DIRECTORY_PICTURES + "/Gotcha"- )- }- }- val uri = contentResolver.insert(- android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,- contentValues- )- if (uri != null) {- contentResolver.openOutputStream(uri)?.use { out ->- bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)- }- withContext(Dispatchers.Main) { overlay.showError("Screenshot saved: $fileName") }- } else {- withContext(Dispatchers.Main) { overlay.showError("Screenshot save failed") }+ val dir = com.gotcha.data.GotchaStorage.screenshotsRoot()+ dir.mkdirs()+ val file = java.io.File(dir, fileName)+ file.outputStream().use { out ->+ bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)}+ com.gotcha.data.GotchaStorage.publishToGallery(applicationContext, file)+ withContext(Dispatchers.Main) { overlay.showError("Screenshot saved: $fileName") }bitmap.recycle()} catch (e: Throwable) {withContext(Dispatchers.Main) {diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 47743d3..c56665d 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -517,7 +517,7 @@ class CallSessionController(companion object {private const val NARRATION_THROTTLE_MS = 3_000Lprivate const val CONFIRM_TIMEOUT_MS = 90_000L- const val CALLS_WORKING_ROOT = "/storage/emulated/0/Gotcha/calls"+ val CALLS_WORKING_ROOT: String get() = com.gotcha.data.GotchaStorage.callsRoot().absolutePathprivate const val CAPTURE_SETTLE_MS = 350Lprivate const val QUESTION_TIMEOUT_MS = 30_000Lprivate const val TOOL_TEXT_LIMIT = 300diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex 8059d02..0ea43f6 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -489,29 +489,19 @@ class ScreenLensController(scope.launch(Dispatchers.IO) {try {val filename = "Gotcha_Lens_${System.currentTimeMillis()}.png"- val resolver = appContext.contentResolver- val contentValues = android.content.ContentValues().apply {- put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, filename)- put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "image/png")- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {- put(- android.provider.MediaStore.MediaColumns.RELATIVE_PATH,- android.os.Environment.DIRECTORY_PICTURES + "/Gotcha"- )- }+ val dir = com.gotcha.data.GotchaStorage.screenshotsRoot()+ dir.mkdirs()+ val file = java.io.File(dir, filename)+ file.outputStream().use { out ->+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)}- val uri = resolver.insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)- if (uri != null) {- resolver.openOutputStream(uri)?.use { out ->- bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)- }- withContext(Dispatchers.Main) {- android.widget.Toast.makeText(- appContext,- "Saved image to Pictures/Gotcha",- android.widget.Toast.LENGTH_SHORT- ).show()- }+ com.gotcha.data.GotchaStorage.publishToGallery(appContext, file)+ withContext(Dispatchers.Main) {+ android.widget.Toast.makeText(+ appContext,+ "Saved image to Gotcha/Screenshots",+ android.widget.Toast.LENGTH_SHORT+ ).show()}} catch (e: Exception) {withContext(Dispatchers.Main) {diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.ktindex 2531aac..17f890b 100644--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt@@ -56,7 +56,10 @@ class AppNavigatorSession(// 1. Capture fresh perception with grid overlayval uiTree = ScreenPerception.buildUiHierarchyText()- val saveDir = java.io.File(FileResolver.WORKING_DIR_BASE, "debug_screenshots")+ val saveDir = com.gotcha.data.GotchaStorage.subdir(+ java.io.File(FileResolver.WORKING_DIR_BASE),+ com.gotcha.data.GotchaStorage.Kind.DEBUG+ )val screenshot = ScreenPerception.compressScreenshot(drawGrid = true, saveDir = saveDir)// 2. Build single-turn promptdiff --git a/app/src/main/java/com/gotcha/tools/FileResolver.kt b/app/src/main/java/com/gotcha/tools/FileResolver.ktindex 7593aa7..3f293c5 100644--- a/app/src/main/java/com/gotcha/tools/FileResolver.kt+++ b/app/src/main/java/com/gotcha/tools/FileResolver.kt@@ -38,7 +38,7 @@ class FileResolver(private val context: Context) {"This operation needs storage write permission. " +"Go to Settings → Permissions → Storage Write and grant it, then ask again."- var WORKING_DIR_BASE: String = "/storage/emulated/0/Gotcha"+ var WORKING_DIR_BASE: String = com.gotcha.data.GotchaStorage.root().absolutePathfun formatSizeStatic(bytes: Long): String = when {bytes >= 1024L * 1024 * 1024 -> "%.1f GB".format(bytes.toDouble() / (1024 * 1024 * 1024))diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktindex 4185a4b..4fd8158 100644--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -1,12 +1,10 @@package com.gotcha.toolsimport android.Manifest-import android.content.ContentValuesimport android.content.Contextimport android.content.pm.PackageManagerimport android.media.MediaRecorderimport android.os.Build-import android.provider.MediaStoreimport android.util.Logimport androidx.camera.core.CameraSelectorimport androidx.camera.core.ImageCapture@@ -47,8 +45,10 @@ class MediaCaptureTool(private val context: Context) {?: return ToolResult.error("Camera system is not ready yet. Try again in a moment.")return try {- val dir = File(FileResolver.WORKING_DIR_BASE, "Pictures")- dir.mkdirs()+ val dir = com.gotcha.data.GotchaStorage.subdir(+ File(FileResolver.WORKING_DIR_BASE),+ com.gotcha.data.GotchaStorage.Kind.PICTURES+ )val file = File(dir, "photo_${timestamp()}.jpg")val cameraSelector = if (camera?.trim()?.lowercase() == "front") {@@ -78,6 +78,7 @@ class MediaCaptureTool(private val context: Context) {object : ImageCapture.OnImageSavedCallback {override fun onImageSaved(output: ImageCapture.OutputFileResults) {Log.d(TAG, "takePhoto: image saved to ${file.absolutePath}")+ com.gotcha.data.GotchaStorage.publishToGallery(context, file)cont.resume(ToolResult.ok("Photo saved to ${file.absolutePath}."))}override fun onError(exception: ImageCaptureException) {@@ -118,15 +119,17 @@ class MediaCaptureTool(private val context: Context) {}return try {val file = if (!outputPath.isNullOrBlank()) {- val resolved = if (outputPath.startsWith("/")) {- outputPath- } else {- File(FileResolver.WORKING_DIR_BASE, outputPath).absolutePath+ val resolved = FileResolver(context).resolveForWrite(outputPath)+ when (resolved) {+ is FileResolver.ResolveResult.Ok -> resolved.file.also { it.parentFile?.mkdirs() }+ is FileResolver.ResolveResult.PermissionNeeded -> return resolved.result+ is FileResolver.ResolveResult.Error -> return ToolResult.error(resolved.message)}- File(resolved).also { it.parentFile?.mkdirs() }} else {- val dir = File(FileResolver.WORKING_DIR_BASE, "Recordings")- dir.mkdirs()+ val dir = com.gotcha.data.GotchaStorage.subdir(+ File(FileResolver.WORKING_DIR_BASE),+ com.gotcha.data.GotchaStorage.Kind.RECORDINGS+ )File(dir, "recording_${timestamp()}.m4a")}@@ -197,18 +200,8 @@ class MediaCaptureTool(private val context: Context) {val dur = (System.currentTimeMillis() - recordingStartTime) / 1000// Make the file accessible to other appsfile?.setReadable(true, false)- // Scan into MediaStore so music players can discover itif (file != null) {- try {- val values = ContentValues().apply {- put(MediaStore.Audio.Media.IS_PENDING, 0)- put(MediaStore.Audio.Media.DATA, file.absolutePath)- put(MediaStore.Audio.Media.TITLE, file.nameWithoutExtension)- put(MediaStore.Audio.Media.DURATION, dur * 1000)- put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp4")- }- context.contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)- } catch (_: Exception) { }+ com.gotcha.data.GotchaStorage.publishToGallery(context, file)}releaseRecorder()ToolResult.ok("Recording saved to $path (${dur / 60}m ${dur % 60}s).")diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xmlindex a8caec5..e59082d 100644--- a/app/src/main/res/xml/file_paths.xml+++ b/app/src/main/res/xml/file_paths.xml@@ -1,7 +1,7 @@<?xml version="1.0" encoding="utf-8"?><paths>- <!-- Captured photos live under getExternalFilesDir("Pictures"). -->- <external-files-path name="captures" path="." />+ <!-- All Gotcha-managed files live under /storage/emulated/0/Gotcha. -->+ <external-path name="gotcha" path="Gotcha/" /><!-- Lens-mode cropped images shared for "Copy Image" (content:// clip). --><cache-path name="lens" path="lens/" /></paths>diff --git a/app/src/test/java/com/gotcha/data/GotchaStorageTest.kt b/app/src/test/java/com/gotcha/data/GotchaStorageTest.ktnew file mode 100644index 0000000..daa0af9--- /dev/null+++ b/app/src/test/java/com/gotcha/data/GotchaStorageTest.kt@@ -0,0 +1,169 @@+package com.gotcha.data++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import java.io.File++class GotchaStorageTest {++ @get:Rule+ val tmp = TemporaryFolder()++ @Before+ fun setUp() {+ // Set before the getter is ever touched, so its Android-dependent+ // default (Environment.getExternalStorageDirectory()) is never+ // evaluated under plain JUnit.+ GotchaStorage.rootPath = tmp.newFolder("Gotcha").absolutePath+ }++ // ---- slugify ----++ @Test+ fun `slugify collapses non-alphanumeric runs to a single dash`() {+ assertEquals("Plan-my-trip-to-Goa", GotchaStorage.slugify("Plan my/trip: to Goa!!"))+ }++ @Test+ fun `slugify trims leading and trailing punctuation`() {+ assertEquals("hello", GotchaStorage.slugify("---hello---"))+ }++ @Test+ fun `slugify keeps unicode letters`() {+ assertEquals("Café-München", GotchaStorage.slugify("Café München"))+ }++ @Test+ fun `slugify collapses emoji to dashes`() {+ assertEquals("trip", GotchaStorage.slugify("🌴 trip 🚀"))+ }++ @Test+ fun `slugify truncates to 40 chars`() {+ val long = "a".repeat(60)+ assertEquals(40, GotchaStorage.slugify(long).length)+ }++ @Test+ fun `slugify falls back to New-Chat for blank or fully-punctuation input`() {+ assertEquals("New-Chat", GotchaStorage.slugify(""))+ assertEquals("New-Chat", GotchaStorage.slugify(" "))+ assertEquals("New-Chat", GotchaStorage.slugify("!!!"))+ }++ // ---- shortId / chatDirName ----++ @Test+ fun `shortId strips dashes and takes first 8 chars`() {+ assertEquals("a3f9c1d2", GotchaStorage.shortId("a3f9c1d2-1234-5678-9abc-def012345678"))+ }++ @Test+ fun `chatDirName combines slug and short id`() {+ assertEquals(+ "Plan-my-trip_a3f9c1d2",+ GotchaStorage.chatDirName("Plan my trip", "a3f9c1d2-1234-5678-9abc-def012345678")+ )+ }++ // ---- findChatDir ----++ @Test+ fun `findChatDir matches by short id suffix regardless of title part`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val dir = File(GotchaStorage.chatsRoot(), "Some-Old-Title_a3f9c1d2")+ dir.mkdirs()+ val found = GotchaStorage.findChatDir(sessionId)+ assertEquals(dir.absolutePath, found?.absolutePath)+ }++ @Test+ fun `findChatDir returns null when no dir matches`() {+ assertEquals(null, GotchaStorage.findChatDir("a3f9c1d2-1234-5678-9abc-def012345678"))+ }++ // ---- ensureChatDir ----++ @Test+ fun `ensureChatDir creates a new dir with readable name when none exists`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val dir = GotchaStorage.ensureChatDir(sessionId, "Plan my trip")+ assertTrue(dir.exists())+ assertEquals("Plan-my-trip_a3f9c1d2", dir.name)+ }++ @Test+ fun `ensureChatDir does not create the dir when create is false`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val dir = GotchaStorage.ensureChatDir(sessionId, "New Chat", create = false)+ assertFalse(dir.exists())+ }++ @Test+ fun `ensureChatDir renames an existing dir while preserving contents`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val oldDir = GotchaStorage.ensureChatDir(sessionId, "New Chat")+ File(oldDir, "notes.txt").writeText("hello")++ val renamed = GotchaStorage.ensureChatDir(sessionId, "Plan my trip to Goa")++ assertEquals("Plan-my-trip-to-Goa_a3f9c1d2", renamed.name)+ assertTrue(renamed.exists())+ assertFalse(oldDir.exists())+ assertEquals("hello", File(renamed, "notes.txt").readText())+ }++ @Test+ fun `ensureChatDir is idempotent on a second call with the same title`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val first = GotchaStorage.ensureChatDir(sessionId, "Plan my trip")+ File(first, "notes.txt").writeText("hello")+ val second = GotchaStorage.ensureChatDir(sessionId, "Plan my trip")++ assertEquals(first.absolutePath, second.absolutePath)+ assertEquals("hello", File(second, "notes.txt").readText())+ assertEquals(1, GotchaStorage.chatsRoot().listFiles()?.size)+ }++ // ---- archiveChatDir ----++ @Test+ fun `archiveChatDir moves the chat dir under old_chats preserving contents`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val dir = GotchaStorage.ensureChatDir(sessionId, "Plan my trip")+ File(dir, "notes.txt").writeText("hello")++ GotchaStorage.archiveChatDir(sessionId)++ assertFalse(dir.exists())+ val archived = File(GotchaStorage.archiveRoot(), dir.name)+ assertTrue(archived.exists())+ assertEquals("hello", File(archived, "notes.txt").readText())+ }++ @Test+ fun `archiveChatDir suffixes with a timestamp on name collision`() {+ val sessionId = "a3f9c1d2-1234-5678-9abc-def012345678"+ val dir = GotchaStorage.ensureChatDir(sessionId, "Plan my trip")+ GotchaStorage.archiveRoot().mkdirs()+ File(GotchaStorage.archiveRoot(), dir.name).mkdirs()++ GotchaStorage.archiveChatDir(sessionId)++ assertFalse(dir.exists())+ val entries = GotchaStorage.archiveRoot().listFiles().orEmpty()+ assertTrue(entries.any { it.name.startsWith("${dir.name}_") })+ }++ @Test+ fun `archiveChatDir is a no-op when the chat dir does not exist`() {+ GotchaStorage.archiveChatDir("a3f9c1d2-1234-5678-9abc-def012345678")+ assertFalse(GotchaStorage.archiveRoot().exists() && GotchaStorage.archiveRoot().listFiles()?.isNotEmpty() == true)+ }+}