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(chats): a versioned chat backup and an importer for every chat file (#83)
Durganshu764a1756b4e5
diff --git a/app/src/main/java/com/gotcha/data/ChatArchive.kt b/app/src/main/java/com/gotcha/data/ChatArchive.ktnew file mode 100644index 0000000..a3e3dae--- /dev/null+++ b/app/src/main/java/com/gotcha/data/ChatArchive.kt@@ -0,0 +1,68 @@+package com.gotcha.data++import com.gotcha.agent.ComposerAttachment+import com.gotcha.llm.ChatMessage+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive++/**+ * The lossless chat backup ("Back up chat" / "Back up all chats", issue #83):+ * whole [ChatSession]s, exactly as they are stored, wrapped with a format tag+ * and a version so an import can tell a backup from any other JSON and refuse+ * one written by a newer Gotcha than it understands.+ *+ * Versioning: add fields with defaults and keep [VERSION]; bump it only for a+ * change an older reader would get wrong, and teach [ChatImporter] the old one.+ */+@Serializable+data class ChatArchive(+ val format: String = FORMAT,+ val version: Int = VERSION,+ val exportedAt: Long,+ val appVersion: String = "",+ /** False when images were left out of the backup; see [withoutImages]. */+ val includesImages: Boolean = true,+ val sessions: List<ChatSession>+) {+ companion object {+ const val FORMAT = "gotcha-chats"+ const val VERSION = 1++ /** File extension the backup is saved with, so it reads as Gotcha's. */+ const val FILE_SUFFIX = ".gotcha.json"++ val json = Json {+ ignoreUnknownKeys = true+ encodeDefaults = true+ }++ fun encode(archive: ChatArchive): String = json.encodeToString(serializer(), archive)++ /**+ * [session] with every image taken out: the vision parts of its LLM+ * history, the screenshots and picked photos of its transcript. Images+ * are most of a backup's size and can show more than the words do, so+ * the export asks before including them.+ */+ fun withoutImages(session: ChatSession): ChatSession = session.copy(+ messages = session.messages.map(::withoutImageParts),+ displayMessages = session.displayMessages.map { ui ->+ ui.copy(+ imageBase64 = null,+ attachments = ui.attachments.filterNot { it is ComposerAttachment.Image }+ )+ }+ )++ private fun withoutImageParts(message: ChatMessage): ChatMessage {+ val parts = message.content as? JsonArray ?: return message+ val kept = parts.filterNot { part ->+ ((part as? JsonObject)?.get("type") as? JsonPrimitive)?.content == "image_url"+ }+ return if (kept.size == parts.size) message else message.copy(content = JsonArray(kept))+ }+ }+}diff --git a/app/src/main/java/com/gotcha/data/ChatImporter.kt b/app/src/main/java/com/gotcha/data/ChatImporter.ktnew file mode 100644index 0000000..bc8e5ed--- /dev/null+++ b/app/src/main/java/com/gotcha/data/ChatImporter.kt@@ -0,0 +1,320 @@+package com.gotcha.data++import com.gotcha.llm.ChatMessage+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.intOrNull+import java.util.UUID++/** Which kind of file an import was read from. */+enum class ImportFormat(val label: String) {+ /** A [ChatArchive]: "Back up chat" or "Back up all chats". Lossless. */+ BACKUP("Gotcha backup"),++ /** One bare [ChatSession] file, as Gotcha stores it on the device. Lossless. */+ CHAT_FILE("Gotcha chat file"),++ /** The Markdown "Export chat". Text only; see [ChatMarkdown]. */+ MARKDOWN("Markdown chat export")+}++/** How an incoming chat relates to the ones already on the device. */+enum class ImportStatus {+ /** No chat with its id exists. */+ NEW,++ /** A chat with its id exists and holds the same conversation, so importing would change nothing. */+ IDENTICAL,++ /** A chat with its id exists but differs; the [DuplicateStrategy] decides. */+ CONFLICT+}++/** What to do with an incoming chat whose id is already taken by a different chat. */+enum class DuplicateStrategy(val label: String) {+ KEEP_BOTH("Keep both"),+ REPLACE("Replace mine"),+ SKIP("Skip")+}++data class ImportItem(val session: ChatSession, val status: ImportStatus)++/** A chat that was not imported, named as well as the file allows, and why. */+data class ImportProblem(val title: String, val reason: String)++/** A readable import file, before anything is written. */+data class ImportPreview(+ val format: ImportFormat,+ val items: List<ImportItem>,+ /** Chats in the file that failed validation and will not be imported. */+ val rejected: List<ImportProblem>,+ /** Things that were repaired or guessed while reading, for the report. */+ val warnings: List<String>+) {+ val newCount: Int get() = items.count { it.status == ImportStatus.NEW }+ val identicalCount: Int get() = items.count { it.status == ImportStatus.IDENTICAL }+ val conflictCount: Int get() = items.count { it.status == ImportStatus.CONFLICT }+}++sealed class ImportParseResult {+ data class Ready(val preview: ImportPreview) : ImportParseResult()++ /** The file as a whole can't be imported; [message] says why, for the user. */+ data class Failed(val message: String) : ImportParseResult()+}++data class ImportResult(+ val imported: Int,+ val replaced: Int,+ val skipped: Int,+ val failed: List<ImportProblem>,+ /** Ids of every chat written, new or replaced. */+ val writtenIds: List<String>+)++/**+ * Reads chats back into Gotcha (issue #83), from any of the three files Gotcha+ * writes: a [ChatArchive] backup, a single stored [ChatSession] file, or the+ * Markdown export. Two steps, so the user sees what a file holds before it+ * touches their chats: [preview] reads and validates, [commit] writes.+ *+ * Validation is per chat: one damaged chat in a backup is reported and the rest+ * still import. A file is refused as a whole only when it is too large, is not+ * one of the three formats, or comes from a newer backup version.+ */+class ChatImporter(+ private val repository: ChatHistoryRepository,+ private val now: () -> Long = System::currentTimeMillis,+ private val newId: () -> String = { UUID.randomUUID().toString() }+) {++ suspend fun preview(bytes: ByteArray): ImportParseResult {+ if (bytes.size > MAX_BYTES) {+ return ImportParseResult.Failed(+ "The file is ${bytes.size / (1024 * 1024)} MB; the most Gotcha imports at once is " ++ "${MAX_BYTES / (1024 * 1024)} MB."+ )+ }+ val text = bytes.toString(Charsets.UTF_8).removePrefix(BYTE_ORDER_MARK)+ if (text.isBlank()) return ImportParseResult.Failed("The file is empty.")++ val read = when {+ text.trimStart().startsWith("{") -> readJson(text)+ ChatMarkdown.looksLikeExport(text) -> readMarkdown(text)+ else -> return ImportParseResult.Failed(NOT_RECOGNISED)+ }+ if (read is ImportParseResult.Failed) return read+ val parsed = (read as ImportParseResult.Ready).preview++ // Check what each chat is, once repaired: a clash with a stored chat, or+ // with another chat earlier in the same file.+ val warnings = parsed.warnings.toMutableList()+ val seenIds = mutableSetOf<String>()+ val items = parsed.items.map { item ->+ var session = item.session+ if (!seenIds.add(session.id)) {+ warnings += "\"${session.title}\" shares its id with another chat in the file; imported as a separate chat."+ session = session.copy(id = newId())+ seenIds += session.id+ }+ ImportItem(session, statusOf(session, parsed.format))+ }+ if (items.isEmpty() && parsed.rejected.isEmpty()) {+ return ImportParseResult.Failed("The file holds no chats.")+ }+ return ImportParseResult.Ready(parsed.copy(items = items, warnings = warnings))+ }++ /**+ * Writes [preview]'s chats. Status is checked again rather than trusted from+ * the preview, since a chat may have been saved in between. Chats in+ * [protectedIds] (the one a task is running in) are never replaced: the+ * running task would write its own copy straight back over the import.+ */+ suspend fun commit(+ preview: ImportPreview,+ strategy: DuplicateStrategy,+ protectedIds: Set<String> = emptySet()+ ): ImportResult {+ var imported = 0+ var replaced = 0+ var skipped = 0+ val failed = mutableListOf<ImportProblem>()+ val written = mutableListOf<String>()++ suspend fun write(session: ChatSession): Boolean {+ val ok = repository.saveSession(session, touch = false)+ if (ok) written += session.id else failed += ImportProblem(session.title, "It couldn't be saved.")+ return ok+ }++ for (item in preview.items) {+ val session = item.session+ when (statusOf(session, preview.format)) {+ ImportStatus.NEW -> if (write(session)) imported+++ ImportStatus.IDENTICAL -> skipped+++ ImportStatus.CONFLICT -> when (strategy) {+ DuplicateStrategy.SKIP -> skipped+++ DuplicateStrategy.KEEP_BOTH ->+ if (write(session.copy(id = newId(), title = "${session.title} (imported)"))) imported+++ DuplicateStrategy.REPLACE ->+ if (session.id in protectedIds) {+ failed += ImportProblem(session.title, "A task is running in that chat; try again when it's done.")+ } else if (write(session)) {+ replaced+++ }+ }+ }+ }+ return ImportResult(imported, replaced, skipped, failed + preview.rejected, written)+ }++ private suspend fun statusOf(session: ChatSession, format: ImportFormat): ImportStatus {+ val existing = repository.loadSession(session.id) ?: return ImportStatus.NEW+ val same = if (format == ImportFormat.MARKDOWN) {+ // A Markdown export carries less than the stored chat, so compare+ // what the export would show of each rather than the chats themselves.+ ChatMarkdown.export(existing.messages, session.id, null, now = 0) ==+ ChatMarkdown.export(session.messages, session.id, null, now = 0)+ } else {+ existing.messages == session.messages && existing.displayMessages == session.displayMessages+ }+ return if (same) ImportStatus.IDENTICAL else ImportStatus.CONFLICT+ }++ private fun readJson(text: String): ImportParseResult {+ val root = try {+ ChatArchive.json.parseToJsonElement(text)+ } catch (_: Exception) {+ return ImportParseResult.Failed("The file isn't valid JSON; it may be damaged or cut short.")+ }+ val obj = root as? JsonObject ?: return ImportParseResult.Failed(NOT_RECOGNISED)+ val format = (obj["format"] as? JsonPrimitive)?.content++ if (format == null && "id" in obj && "messages" in obj) {+ return collect(ImportFormat.CHAT_FILE, listOf(obj), emptyList())+ }+ if (format != ChatArchive.FORMAT) return ImportParseResult.Failed(NOT_RECOGNISED)++ val version = (obj["version"] as? JsonPrimitive)?.intOrNull+ ?: return ImportParseResult.Failed("The backup has no version number; it may be damaged.")+ if (version > ChatArchive.VERSION) {+ return ImportParseResult.Failed(+ "This backup was made by a newer version of Gotcha (format $version). Update Gotcha to import it."+ )+ }+ val sessions = obj["sessions"] as? JsonArray+ ?: return ImportParseResult.Failed("The backup has no chat list; it may be damaged.")+ val warnings = if ((obj["includesImages"] as? JsonPrimitive)?.content == "false") {+ listOf("This backup was made without images, so imported chats show none.")+ } else {+ emptyList()+ }+ return collect(ImportFormat.BACKUP, sessions, warnings)+ }++ /** Decodes and validates each chat of a JSON file on its own, so one bad chat can't sink the rest. */+ private fun collect(+ format: ImportFormat,+ elements: List<JsonElement>,+ warnings: List<String>+ ): ImportParseResult {+ val items = mutableListOf<ImportItem>()+ val rejected = mutableListOf<ImportProblem>()+ val notes = warnings.toMutableList()+ elements.forEachIndexed { index, element ->+ val fallbackTitle = ((element as? JsonObject)?.get("title") as? JsonPrimitive)?.content+ ?.takeIf { it.isNotBlank() }+ ?: "Chat ${index + 1}"+ val session = try {+ ChatArchive.json.decodeFromJsonElement(ChatSession.serializer(), element)+ } catch (_: Exception) {+ rejected += ImportProblem(fallbackTitle, "Its data is damaged or incomplete.")+ return@forEachIndexed+ }+ when (val checked = validate(session, notes)) {+ is Validated.Ok -> items += ImportItem(checked.session, ImportStatus.NEW)+ is Validated.Rejected -> rejected += ImportProblem(fallbackTitle, checked.reason)+ }+ }+ return ImportParseResult.Ready(ImportPreview(format, items, rejected, notes))+ }++ private fun readMarkdown(text: String): ImportParseResult {+ val parsed = try {+ ChatMarkdown.parse(text)+ } catch (e: IllegalArgumentException) {+ return ImportParseResult.Failed(e.message ?: NOT_RECOGNISED)+ }+ val notes = parsed.warnings.toMutableList()+ val session = ChatSession(+ id = parsed.sessionId ?: newId(),+ title = parsed.title.orEmpty(),+ lastModified = parsed.exportedAt ?: now(),+ messages = parsed.messages,+ // Rough, like the engine's own trimming estimate; the next turn recounts.+ tokenCount = parsed.messages.sumOf { it.textContent.length } / 4+ )+ notes += "A Markdown export holds text only: images, attached documents and full tool " ++ "arguments are not part of it."+ return when (val checked = validate(session, notes)) {+ is Validated.Ok -> ImportParseResult.Ready(+ ImportPreview(+ ImportFormat.MARKDOWN,+ listOf(ImportItem(checked.session, ImportStatus.NEW)),+ emptyList(),+ notes+ )+ )+ is Validated.Rejected -> ImportParseResult.Failed("The export can't be imported: ${checked.reason}")+ }+ }++ private sealed class Validated {+ data class Ok(val session: ChatSession) : Validated()+ data class Rejected(val reason: String) : Validated()+ }++ /**+ * Refuses a chat that would break Gotcha when opened, and repairs what can be+ * repaired. The id becomes a file name, so anything but a plain token (a+ * path, say) is replaced rather than trusted.+ */+ private fun validate(session: ChatSession, notes: MutableList<String>): Validated {+ if (session.messages.isEmpty()) return Validated.Rejected("It has no messages.")+ session.messages.firstOrNull { it.role !in ROLES }?.let {+ return Validated.Rejected("It has a message of unknown kind \"${it.role.take(20)}\".")+ }+ var repaired = session+ if (!SAFE_ID.matches(session.id)) {+ repaired = repaired.copy(id = newId())+ }+ if (repaired.title.isBlank()) {+ repaired = repaired.copy(title = fallbackTitle(repaired.messages))+ }+ val latest = now() + CLOCK_SKEW_MS+ if (repaired.lastModified <= 0 || repaired.lastModified > latest) {+ repaired = repaired.copy(lastModified = now())+ notes += "\"${repaired.title}\" had no usable date; it is dated today."+ }+ return Validated.Ok(repaired)+ }++ /** The engine's own untitled fallback, so a title is still generated for it later. */+ private fun fallbackTitle(messages: List<ChatMessage>): String =+ messages.firstOrNull { it.role == "user" }?.textContent?.take(30)?.takeIf { it.isNotBlank() }+ ?: "Imported chat"++ companion object {+ /** A backup with every image in it can be large, but it is read into memory whole. */+ const val MAX_BYTES = 64 * 1024 * 1024++ private const val CLOCK_SKEW_MS = 24 * 60 * 60 * 1000L+ private val ROLES = setOf("user", "assistant", "tool", "system")+ private val SAFE_ID = Regex("[A-Za-z0-9_-]{1,100}")+ private const val NOT_RECOGNISED =+ "This isn't a Gotcha chat file. Choose a backup (.gotcha.json) or a chat exported as Markdown."+ }+}diff --git a/app/src/test/java/com/gotcha/data/ChatImporterTest.kt b/app/src/test/java/com/gotcha/data/ChatImporterTest.ktnew file mode 100644index 0000000..5c8ca5e--- /dev/null+++ b/app/src/test/java/com/gotcha/data/ChatImporterTest.kt@@ -0,0 +1,311 @@+package com.gotcha.data++import com.gotcha.agent.ComposerAttachment+import com.gotcha.agent.MessageKind+import com.gotcha.agent.UiMessage+import com.gotcha.llm.ChatMessage+import com.gotcha.llm.visionUserMessage+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNull+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++/**+ * Chat import (issue #83): every file Gotcha writes imports back unchanged,+ * damaged input is refused with a reason (per chat where possible), and a+ * clash with an existing chat is resolved the way the user chose.+ */+class ChatImporterTest {++ @get:Rule+ val tmp = TemporaryFolder()++ private lateinit var dir: File+ private lateinit var repo: ChatHistoryRepository+ private var idCounter = 0+ private val now = 1_790_000_000_000L++ private fun importer() = ChatImporter(repo, now = { now }, newId = { "new-${idCounter++}" })++ @Before+ fun setUp() {+ dir = tmp.newFolder("chats")+ repo = ChatHistoryRepository(dir)+ }++ private fun text(role: String, text: String) = ChatMessage(role = role, content = JsonPrimitive(text))++ /** A chat using every field a session stores, so a lossless import is checked field by field. */+ private fun fullSession(id: String = "chat-1", title: String = "Trip plans") = ChatSession(+ id = id,+ title = title,+ lastModified = 1_700_000_000_000L,+ messages = listOf(visionUserMessage("Where is this?", "QUJD", "jpeg"), text("assistant", "Lisbon.")),+ tokenCount = 321,+ displayMessages = listOf(+ UiMessage(+ 0,+ MessageKind.USER,+ "Where is this?",+ attachments = listOf(ComposerAttachment.Image("a1", "photo.jpg", "QUJD"))+ ),+ UiMessage(1, MessageKind.ASSISTANT, "Lisbon.", imageBase64 = "U0NS")+ ),+ agentMode = "OPERATOR",+ runSummaries = listOf(+ RunSummary(+ startedAt = 1L,+ endedAt = 2L,+ userPrompt = "Where is this?",+ finalReply = "Lisbon.",+ model = "m",+ agentMode = "OPERATOR",+ delegated = false,+ succeeded = true,+ toolCalls = emptyList()+ )+ ),+ personaId = "guide"+ )++ private fun backup(vararg sessions: ChatSession, includeImages: Boolean = true): ByteArray =+ ChatArchive.encode(+ ChatArchive(+ exportedAt = now,+ includesImages = includeImages,+ sessions = if (includeImages) sessions.toList() else sessions.map(ChatArchive::withoutImages)+ )+ ).toByteArray()++ private fun ready(result: ImportParseResult): ImportPreview =+ (result as? ImportParseResult.Ready)?.preview ?: error("expected a preview, got $result")++ private fun failure(result: ImportParseResult): String =+ (result as? ImportParseResult.Failed)?.message ?: error("expected a failure, got $result")++ // ---- round trips ----++ @Test+ fun `a backup imports back exactly`() = runBlocking {+ val original = fullSession()+ val preview = ready(importer().preview(backup(original)))+ assertEquals(ImportFormat.BACKUP, preview.format)+ assertEquals(1, preview.newCount)++ val result = importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ assertEquals(1, result.imported)+ assertEquals(original, repo.loadSession("chat-1"))+ }++ @Test+ fun `a stored chat file imports as it is`() = runBlocking {+ val bytes = ChatArchive.json.encodeToString(ChatSession.serializer(), fullSession()).toByteArray()+ val preview = ready(importer().preview(bytes))+ assertEquals(ImportFormat.CHAT_FILE, preview.format)+ importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ assertEquals(fullSession(), repo.loadSession("chat-1"))+ }++ @Test+ fun `a markdown export imports as a continuable chat`() = runBlocking {+ val markdown = ChatMarkdown.export(+ listOf(text("user", "Plan a trip to Lisbon"), text("assistant", "Here's a plan.")),+ "md-chat",+ "Lisbon trip",+ now = 1_700_000_000_000L+ )+ val preview = ready(importer().preview(markdown.toByteArray()))+ assertEquals(ImportFormat.MARKDOWN, preview.format)+ assertTrue(preview.warnings.any { "text only" in it })++ importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ val saved = repo.loadSession("md-chat")!!+ assertEquals("Lisbon trip", saved.title)+ assertEquals(listOf("Plan a trip to Lisbon", "Here's a plan."), saved.messages.map { it.textContent })+ assertEquals(1_700_000_000_000L / 1000 * 1000, saved.lastModified)+ assertTrue(saved.displayMessages.isEmpty()) // rebuilt from messages when opened+ }++ @Test+ fun `a markdown export without a title is named from its first message`() = runBlocking {+ val markdown = ChatMarkdown.export(listOf(text("user", "Remind me to call mum tomorrow at nine")), "x", null)+ val saved = ready(importer().preview(markdown.toByteArray())).items.single().session+ assertEquals("Remind me to call mum tomorrow at nine".take(30), saved.title)+ }++ @Test+ fun `a backup without images drops every image but keeps the words`() = runBlocking {+ val preview = ready(importer().preview(backup(fullSession(), includeImages = false)))+ assertTrue(preview.warnings.any { "without images" in it })+ val session = preview.items.single().session+ assertEquals(0, session.messages.sumOf { it.imageCount })+ assertEquals("Where is this?", session.messages[0].textContent)+ assertTrue(session.displayMessages.all { it.imageBase64 == null && it.attachments.isEmpty() })+ }++ // ---- refusing a file ----++ @Test+ fun `files that aren't Gotcha chats are refused with a reason`() = runBlocking {+ assertTrue("empty" in failure(importer().preview(ByteArray(0))))+ assertTrue("valid JSON" in failure(importer().preview("{\"format\": ".toByteArray())))+ assertTrue("isn't a Gotcha" in failure(importer().preview("""{"hello":"world"}""".toByteArray())))+ assertTrue("isn't a Gotcha" in failure(importer().preview("just some notes".toByteArray())))+ assertTrue("isn't a Gotcha" in failure(importer().preview("[1,2,3]".toByteArray())))+ }++ @Test+ fun `a backup from a newer version is refused`() = runBlocking {+ val bytes = """{"format":"gotcha-chats","version":99,"exportedAt":0,"sessions":[]}""".toByteArray()+ assertTrue("newer version" in failure(importer().preview(bytes)))+ }++ @Test+ fun `an oversized file is refused before it is parsed`() = runBlocking {+ val bytes = ByteArray(ChatImporter.MAX_BYTES + 1)+ assertTrue("MB" in failure(importer().preview(bytes)))+ }++ @Test+ fun `a backup with no chats is refused`() = runBlocking {+ assertTrue("no chats" in failure(importer().preview(backup())))+ }++ // ---- per-chat validation ----++ @Test+ fun `a damaged chat is reported and the rest still import`() = runBlocking {+ val good = ChatArchive.json.encodeToString(ChatSession.serializer(), fullSession())+ val bytes = """+ {"format":"gotcha-chats","version":1,"exportedAt":0,"sessions":[+ $good,+ {"id":"broken","title":"Broken chat","messages":"not a list"},+ {"id":"empty","title":"Empty chat","lastModified":1,"messages":[]},+ {"id":"odd","title":"Odd chat","lastModified":1,"messages":[{"role":"wizard","content":"hi"}]}+ ]}+ """.trimIndent().toByteArray()+ val preview = ready(importer().preview(bytes))+ assertEquals(1, preview.items.size)+ assertEquals(listOf("Broken chat", "Empty chat", "Odd chat"), preview.rejected.map { it.title })++ val result = importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ assertEquals(1, result.imported)+ assertEquals(3, result.failed.size)+ assertNull(repo.loadSession("broken"))+ }++ @Test+ fun `an id that could escape the chats folder is replaced`() = runBlocking {+ val sneaky = fullSession(id = "../../shared_prefs/settings")+ val preview = ready(importer().preview(backup(sneaky)))+ val id = preview.items.single().session.id+ assertEquals("new-0", id)+ importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ assertEquals(listOf("new-0.json"), dir.list()!!.toList())+ }++ @Test+ fun `a missing title and an impossible date are repaired`() = runBlocking {+ val session = fullSession().copy(title = "", lastModified = now * 10)+ val repaired = ready(importer().preview(backup(session))).items.single().session+ assertEquals("Where is this?", repaired.title)+ assertEquals(now, repaired.lastModified)+ }++ @Test+ fun `two chats sharing an id in one file both import`() = runBlocking {+ val preview = ready(importer().preview(backup(fullSession(title = "A"), fullSession(title = "B"))))+ assertEquals(2, preview.items.map { it.session.id }.toSet().size)+ assertEquals(2, importer().commit(preview, DuplicateStrategy.KEEP_BOTH).imported)+ assertEquals(2, repo.listSessions().size)+ }++ // ---- duplicates ----++ @Test+ fun `importing a chat that is already here changes nothing`() = runBlocking {+ repo.saveSession(fullSession(), touch = false)+ val preview = ready(importer().preview(backup(fullSession())))+ assertEquals(1, preview.identicalCount)++ val result = importer().commit(preview, DuplicateStrategy.REPLACE)+ assertEquals(ImportResult(0, 0, 1, emptyList(), emptyList()), result)+ assertEquals(1, repo.listSessions().size)+ }++ @Test+ fun `re-importing a chat's own markdown export is recognised as a duplicate`() = runBlocking {+ val stored = fullSession()+ repo.saveSession(stored, touch = false)+ val markdown = ChatMarkdown.export(stored.messages, stored.id, stored.title)+ assertEquals(1, ready(importer().preview(markdown.toByteArray())).identicalCount)+ }++ private suspend fun conflictPreview(): ImportPreview {+ repo.saveSession(fullSession(), touch = false)+ val changed = fullSession().copy(messages = fullSession().messages + text("user", "And the weather?"))+ return ready(importer().preview(backup(changed))).also { assertEquals(1, it.conflictCount) }+ }++ @Test+ fun `keep both imports a changed chat beside the original`() = runBlocking {+ val result = importer().commit(conflictPreview(), DuplicateStrategy.KEEP_BOTH)+ assertEquals(1, result.imported)+ assertEquals(2, fullSession().messages.size.let { repo.loadSession("chat-1")!!.messages.size })+ val copy = repo.loadSession(result.writtenIds.single())!!+ assertEquals("Trip plans (imported)", copy.title)+ assertEquals(3, copy.messages.size)+ }++ @Test+ fun `replace overwrites the original`() = runBlocking {+ val result = importer().commit(conflictPreview(), DuplicateStrategy.REPLACE)+ assertEquals(1, result.replaced)+ assertEquals(3, repo.loadSession("chat-1")!!.messages.size)+ assertEquals(1, repo.listSessions().size)+ }++ @Test+ fun `skip leaves the original alone`() = runBlocking {+ val result = importer().commit(conflictPreview(), DuplicateStrategy.SKIP)+ assertEquals(1, result.skipped)+ assertEquals(2, repo.loadSession("chat-1")!!.messages.size)+ }++ @Test+ fun `a chat with a running task is never replaced`() = runBlocking {+ val result = importer().commit(conflictPreview(), DuplicateStrategy.REPLACE, protectedIds = setOf("chat-1"))+ assertEquals(0, result.replaced)+ assertTrue(result.failed.single().reason.contains("running"))+ assertEquals(2, repo.loadSession("chat-1")!!.messages.size)+ }++ @Test+ fun `a chat saved between preview and import is treated as a clash`() = runBlocking {+ val preview = ready(importer().preview(backup(fullSession())))+ assertEquals(1, preview.newCount)+ repo.saveSession(fullSession().copy(messages = listOf(text("user", "other"))), touch = false)++ val result = importer().commit(preview, DuplicateStrategy.KEEP_BOTH)+ assertNotEquals("chat-1", result.writtenIds.single())+ assertEquals("other", repo.loadSession("chat-1")!!.messages.single().textContent)+ }++ @Test+ fun `withoutImages leaves a chat with no images untouched`() {+ val plain = fullSession().copy(+ messages = listOf(text("user", "hi")),+ displayMessages = listOf(UiMessage(0, MessageKind.USER, "hi"))+ )+ assertEquals(plain, ChatArchive.withoutImages(plain))+ assertFalse(ChatArchive.encode(ChatArchive(exportedAt = 0, sessions = listOf(plain))).isBlank())+ }+}