Modern Apps git

← Modern-Apps.git

office: add tests for OfficeViewModel slice 3/4

Commit
dd0714d2b003a01ead8a4050f04700ef90216f01
Author
Vayun Mathur <[email protected]>
When
2026-11-07 03:00 UTC (29 days ago)
Parents
c304ec3
Adds JVM/Robolectric tests for the OfficeViewModel* family
(core, documents, text, sheet, slides, tables, tracked changes,
export, live presence and the SyncA/B/C sharing helpers), plus
Robolectric/Mockito test dependencies for office.

Coverage over the slice classes (OfficeViewModel* in the merged
report): 63.6% -> 85.9% (25257/29391 instructions; measured
before the sync tests at 18705/29391, with the non-sync classes
already at ~90% from earlier WIP rounds).

Bugs fixed: none. Untestable remainder: sync branches that need
a live relay response (verified key-epoch/member/title payloads,
shareCurrentDocument after successful device registration,
openOnlineDocument roster fetches), which cannot be exercised
without a real server.

Verified with gslot ./gradlew :office:createMergedCoverageReport
(full :office:testDevUnitTest suite passes).

(cherry picked from commit 130d81af4cfc2b404dc5651077655e56df037578)

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex c1e8600bd7..cb5daafab5 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -152,6 +152,8 @@ ringrtcAndroid = "2.72.1" # XML kxml2 = "2.3.0" robolectric = "4.17"+# Plain-JVM mocks for Android framework classes (Application, Context) in unit tests.+mockito = "5.15.2"  # Payments, telephony & auth stripe = "23.23.0"@@ -369,6 +371,7 @@ kxml2 = { module = "net.sf.kxml:kxml2", version.ref = "kxml2" }  # Testing robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }+mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockito" }  # Payments, telephony & auth stripe-android = { module = "com.stripe:stripe-android", version.ref = "stripe" }
office/build.gradle.kts
diff --git a/office/build.gradle.kts b/office/build.gradle.ktsindex 3ec8361c7e..309155aaf8 100644--- a/office/build.gradle.kts+++ b/office/build.gradle.kts@@ -32,4 +32,8 @@ dependencies {      // Provides a real XmlPullParser implementation for JVM unit tests (Android's is a stub).     testImplementation(libs.kxml2)+    // Android framework statics (Uri.parse/fromFile) for slice 3/4 ViewModel tests.+    testImplementation(libs.robolectric)+    // Plain-JVM mocks for Android framework classes (slice 3/4 ViewModel tests).+    testImplementation(libs.mockito.core) }
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelBranchesSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelBranchesSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelBranchesSlice3Test.ktnew file mode 100644index 0000000000..e8c86b6fc5--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelBranchesSlice3Test.kt@@ -0,0 +1,269 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4, round 3: branch coverage โ€” every shape kind through the slide-element+ * paths, all document variants through updateMetadata, field fallbacks, TOC levels,+ * list-backspace outdent, and image-block deletion.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelBranchesSlice3Test : OfficeViewModelSlice3Harness() {++    private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(+        title = "Doc",+        content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+    )++    private fun loadedText(vararg texts: String): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc(*texts))+        return vm+    }++    private fun textOf(vm: OfficeViewModel): OdfDocument.TextDocument =+        (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument++    private fun shapeDoc(vararg shapes: OdfShape): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Presentation(title = "D", slides = listOf(+                OdfSlide(name = "S", elements = shapes.map { OdfSlideElement.Shape(it) }))))+        return vm+    }++    private fun shapeText(kind: String): List<OdfParagraph> =+        listOf(OdfParagraph(listOf(OdfSpan("t-$kind"))))++    private fun allShapes(): Array<OdfShape> = arrayOf(+        OdfShape.Rect(0f, 0f, 10f, 10f, text = shapeText("rect")),+        OdfShape.Ellipse(0f, 0f, 10f, 10f, text = shapeText("ellipse")),+        OdfShape.Line(0f, 0f, 10f, 10f, x2 = 10f, y2 = 10f),+        OdfShape.CustomShape(0f, 0f, 10f, 10f, text = shapeText("custom")),+        OdfShape.Polyline(0f, 0f, 10f, 10f, text = shapeText("poly")),+    )++    private fun presOf(vm: OfficeViewModel): OdfDocument.Presentation =+        (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.Presentation++    @Test+    fun `all shape kinds through element text paths`() = runTest {+        val kinds = allShapes()+        val vm = shapeDoc(*kinds)+        for (i in kinds.indices) {+            vm.updateSlideElementText(0, i, "new-$i")+            val shape = (presOf(vm).slides[0].elements[i] as OdfSlideElement.Shape).shape+            val text = shape.text.joinToString("") { p -> p.spans.joinToString("") { it.text } }+            if (shape is OdfShape.Line) {+                // Line shapes carry no text; the write is still applied without crashing.+                assertTrue(text.isEmpty() || text == "new-$i")+            } else {+                assertEquals("new-$i", text)+            }+        }+        // Multi-line write rebuilds every paragraph from the first span's style.+        vm.updateSlideElementText(0, 0, "a\nb")+        assertEquals(2, (presOf(vm).slides[0].elements[0] as OdfSlideElement.Shape)+            .shape.text.size)+    }++    @Test+    fun `all shape kinds through rotation and recolor`() = runTest {+        val kinds = allShapes()+        val vm = shapeDoc(*kinds)+        for (i in kinds.indices) {+            vm.setSlideElementRotation(0, i, 10f)+            assertEquals(10f, (presOf(vm).slides[0].elements[i] as OdfSlideElement.Shape)+                .shape.rotationDegrees)+            vm.setSlideElementFill(0, i, 0xFFFF0000L)+            vm.setSlideElementStroke(0, i, 0xFF00FF00L)+            val s = (presOf(vm).slides[0].elements[i] as OdfSlideElement.Shape).shape+            assertEquals(0xFFFF0000L, s.fillColor)+            assertEquals(0xFF00FF00L, s.strokeColor)+        }+        // Clearing with nulls and set-flags off keeps prior colors on frames.+        val vm2 = loadedText("p")+        vm2.insertImageIntoSlide2()+        vm2.setSlideElementFill(0, 0, null)+        assertEquals(null, ((presOf(vm2).slides[0].elements[0] as OdfSlideElement.Frame)+            .frame.fillColor))+    }++    @Test+    fun `all shape kinds through span style and alignment`() = runTest {+        val kinds = allShapes()+        val vm = shapeDoc(*kinds)+        for (i in kinds.indices) {+            vm.toggleSlideElementBold(0, i)+            vm.toggleSlideElementItalic(0, i)+            vm.toggleSlideElementUnderline(0, i)+            vm.setSlideElementColor(0, i, 0xFF123456L)+            vm.setSlideElementAlignment(0, i, androidx.compose.ui.text.style.TextAlign.Justify)+            val el = presOf(vm).slides[0].elements[i] as OdfSlideElement.Shape+            val first = el.shape.text.firstOrNull()?.spans?.firstOrNull()+            // Line shapes have no text spans; the others take the style.+            if (el.shape is OdfShape.Line) assertEquals(null, first)+            else {+                assertEquals(true, first!!.bold)+                assertEquals(androidx.compose.ui.text.style.TextAlign.Justify,+                    el.shape.text[0].alignment)+            }+        }+    }++    @Test+    fun `updateMetadata covers every document variant`() = runTest {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Spreadsheet(title = "B", sheets = emptyList()))+        vm.updateMetadata { it.copy(title = "S2") }+        assertEquals("S2", ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).metadata.title)+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Presentation(title = "P", slides = emptyList()))+        vm.updateMetadata { it.copy(title = "P2") }+        assertEquals("P2", ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Presentation).metadata.title)+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Drawing(title = "G", pages = emptyList()))+        vm.updateMetadata { it.copy(title = "G2") }+        assertEquals("G2", ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Drawing).metadata.title)+        // Empty state is a no-op.+        idleVm().updateMetadata { it.copy(title = "N") }+    }++    @Test+    fun `field display fallbacks`() = runTest {+        val vm = loadedText("x")+        // No metadata anywhere: author falls back to creator then "", title to doc title.+        assertEquals("", vm.fieldDisplayValue("author-name"))+        assertEquals("Doc", vm.fieldDisplayValue("title"))+        // file-name falls back to the doc title ("Untitled" only with no document).+        assertEquals("B", idleVm().let {+            it.stateMutable.value = OfficeViewModel.ViewState.Loaded(+                OdfDocument.Spreadsheet(title = "B", sheets = emptyList()))+            it.fieldDisplayValue("file-name")+        })+        assertEquals("Untitled", idleVm().fieldDisplayValue("file-name"))+        assertEquals("", vm.fieldDisplayValue("subject"))+        assertEquals("", vm.fieldDisplayValue("description"))+        vm.updateMetadata { it.copy(creator = "C") }+        assertEquals("C", vm.fieldDisplayValue("author-name"))+        // file-name uses the doc title when metadata is absent.+        assertEquals("Doc", vm.fieldDisplayValue("file-name"))+    }++    @Test+    fun `toc collects all heading levels and skips blanks`() = runTest {+        val vm = loadedText("H1", "H2", "H3", "H4", "   ", "Body")+        vm.setParagraphStyle(0, ParagraphStyle.HEADING1)+        vm.setParagraphStyle(1, ParagraphStyle.HEADING2)+        vm.setParagraphStyle(2, ParagraphStyle.HEADING3)+        vm.setParagraphStyle(3, ParagraphStyle.HEADING4)+        vm.setParagraphStyle(4, ParagraphStyle.HEADING1) // blank text -> skipped+        vm.insertTableOfContents(5)+        val toc = textOf(vm).content.filterIsInstance<OdfContentBlock.TableOfContents>()+        assertEquals(1, toc.size)+        assertEquals(4, toc[0].entries.size)+        // Indent grows with level.+        val indents = toc[0].entries.map { it.marginLeft }+        assertTrue(indents[0] < indents[1] && indents[1] < indents[2] && indents[2] < indents[3])+    }++    @Test+    fun `list backspace outdents nested and exits top level`() = runTest {+        val vm = loadedText("item")+        vm.toggleListItem(0)+        vm.changeListLevel(0, 2)+        // Caret at run start (gPos 0) on nested item: outdent one level at a time.+        assertEquals(0, vm.handleListBackspace(0, 0, 0))+        assertEquals(ParagraphStyle.LIST_ITEM,+            (textOf(vm).content[0] as OdfContentBlock.Paragraph).paragraph.style)+        assertEquals(0, vm.handleListBackspace(0, 0, 0))+        // Now top-level: backspace exits the list to a body paragraph.+        assertEquals(0, vm.handleListBackspace(0, 0, 0))+        assertEquals(ParagraphStyle.BODY,+            (textOf(vm).content[0] as OdfContentBlock.Paragraph).paragraph.style)+        // Mid-line caret is a no-op (default delete).+        assertEquals(null, vm.handleListBackspace(0, 0, 2))+    }++    @Test+    fun `deleteBlockBefore drops image binary too`() = runTest {+        val vm = loadedText("p")+        vm.insertImage(0, "gone.png", byteArrayOf(1, 2))+        assertTrue(textOf(vm).images.containsKey("Pictures/gone.png"))+        // Image is the last block; a run starting right after it deletes it + its bytes.+        assertTrue(vm.deleteBlockBefore(2))+        assertTrue(textOf(vm).content.none { it is OdfContentBlock.Image })+        assertTrue(!textOf(vm).images.containsKey("Pictures/gone.png"))+        // Missing index and empty doc guards.+        assertTrue(!vm.deleteBlockBefore(0))+        assertTrue(!idleVm().deleteBlockBefore(1))+    }++    @Test+    fun `runLocate and charsToSpans edges`() = runTest {+        val vm = loadedText("ab", "c")+        // Separator consumption: gPos 3 (the newline) lands at the start of para 1.+        assertEquals(1 to 0, vm.runLocate(listOf(2, 1), 3))+        // Beyond everything clamps to the last paragraph end.+        assertEquals(1 to 1, vm.runLocate(listOf(2, 1), 99))+        // Empty lens guards.+        assertEquals(0 to 0, vm.runLocate(emptyList(), 5))+        // charsToSpans merges adjacent same-style chars and keeps distinct ones apart.+        val merged = vm.charsToSpans(listOf(OdfSpan("a", bold = true), OdfSpan("b", bold = true)))+        assertEquals(listOf("ab"), merged.map { it.text })+        assertEquals(true, merged[0].bold)+        assertEquals(0, vm.charsToSpans(emptyList()).size - 1) // single empty span+    }++    @Test+    fun `sheet floating mutate guards and text on shapes`() = runTest {+        val vm = newVm()+        val cell = com.vayunmathur.library.ui.odf.OdfCell("x")+        val row = com.vayunmathur.library.ui.odf.OdfRow(listOf(cell))+        val sheet = com.vayunmathur.library.ui.odf.OdfSheet("S", listOf(row))+        val oneCell = OdfDocument.Spreadsheet(title = "B", sheets = listOf(sheet))+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(oneCell)+        // Bad sheet index: no-op.+        vm.addShapeToSheet(9, "rect")+        vm.setSheetElementBounds(9, 0, 0f, 0f, 1f, 1f)+        vm.deleteSheetElement(9, 0)+        vm.updateSheetElementText(9, 0, "t")+        assertTrue(((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].floating.isEmpty())+        // Shape element text on a sheet + out-of-range element index.+        vm.addShapeToSheet(0, "rect")+        vm.updateSheetElementText(0, 0, "cell note")+        vm.updateSheetElementText(0, 9, "nope")+        val el = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].floating[0]+        assertTrue(el is OdfSlideElement.Shape)+    }++    private fun OfficeViewModel.insertImageIntoSlide2() {+        val imgPara = OdfParagraph(listOf(OdfSpan("f")))+        val frame = OdfSlideElement.Frame(+            OdfFrame(x = 0f, y = 0f, width = 10f, height = 10f,+                paragraphs = listOf(imgPara),+                image = OdfImage(path = "p", imageData = byteArrayOf())))+        val deck = OdfDocument.Presentation(title = "D", slides = listOf(+            OdfSlide(name = "S", elements = listOf(frame))))+        stateMutable.value = OfficeViewModel.ViewState.Loaded(deck)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelCoreSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelCoreSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelCoreSlice3Test.ktnew file mode 100644index 0000000000..f70a940a44--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelCoreSlice3Test.kt@@ -0,0 +1,252 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4: core [OfficeViewModel] state โ€” undo/redo, toggles, auto-save, settings persistence,+ * theme mode, roles/invite metadata, plain-text extraction and caret remapping.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelCoreSlice3Test : OfficeViewModelSlice3Harness() {++    private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(+        title = "Doc",+        content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+    )++    @Test+    fun `starts empty with defaults`() = runTest {+        val vm = idleVm()+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Empty)+        assertFalse(vm.isEditMode.value)+        assertFalse(vm.hasUnsavedChanges.value)+        assertFalse(vm.canUndo.value)+        assertFalse(vm.canRedo.value)+        assertFalse(vm.nightMode.value)+        assertEquals(OfficeViewModel.DocumentThemeMode.UNCHANGED, vm.documentThemeMode.value)+        assertEquals(60_000L, vm.autoSaveIntervalMs)+    }++    @Test+    fun `undo redo walk document history`() = runTest {+        val vm = idleVm()+        val first = textDoc("one")+        val second = textDoc("two")+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(first)+        vm.updateDocument(second)+        assertEquals(second, (vm.state.value as OfficeViewModel.ViewState.Loaded).document)+        assertTrue(vm.canUndo.value)+        assertTrue(vm.hasUnsavedChanges.value)++        vm.undo()+        assertEquals(first, (vm.state.value as OfficeViewModel.ViewState.Loaded).document)+        assertFalse(vm.canUndo.value)+        assertTrue(vm.canRedo.value)++        vm.redo()+        assertEquals(second, (vm.state.value as OfficeViewModel.ViewState.Loaded).document)+        assertTrue(vm.canUndo.value)+        assertFalse(vm.canRedo.value)+    }++    @Test+    fun `undo with empty state is a no-op`() = runTest {+        val vm = idleVm()+        vm.undo()+        vm.redo()+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Empty)+        assertFalse(vm.canUndo.value)+        assertFalse(vm.canRedo.value)+    }++    @Test+    fun `pushUndo caps the stack at MAX_UNDO and clears redo`() = runTest {+        val vm = idleVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc("base"))+        repeat(MAX_UNDO + 5) { i -> vm.updateDocument(textDoc("v$i")) }+        // Drained by undoing MAX_UNDO times; one more undo is a no-op.+        repeat(MAX_UNDO) { vm.undo() }+        assertTrue(vm.canRedo.value)+        val docBefore = (vm.state.value as OfficeViewModel.ViewState.Loaded).document+        vm.undo()+        assertEquals(docBefore, (vm.state.value as OfficeViewModel.ViewState.Loaded).document)+    }++    @Test+    fun `updateDocument without loaded doc is a no-op`() = runTest {+        val vm = idleVm()+        vm.updateDocument(textDoc("x"))+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Empty)+    }++    @Test+    fun `toggles flip their flows`() = runTest {+        val vm = idleVm()+        vm.toggleNightMode()+        assertTrue(vm.nightMode.value)+        vm.toggleEditMode()+        assertTrue(vm.isEditMode.value)+        vm.toggleDocumentDarkMode()+        assertEquals(OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM, vm.documentThemeMode.value)+        assertTrue(vm.documentDarkMode.value)+        vm.toggleDocumentDarkMode()+        assertEquals(OfficeViewModel.DocumentThemeMode.UNCHANGED, vm.documentThemeMode.value)+    }++    @Test+    fun `setAutoSave stores interval and gates the flag`() = runTest {+        val vm = idleVm()+        vm.setAutoSave(true, 30)+        assertEquals(30_000L, vm.autoSaveIntervalMs)+        assertTrue(vm.autoSaveEnabled.value)+        vm.setAutoSave(false)+        assertFalse(vm.autoSaveEnabled.value)+        dispatcher.scheduler.runCurrent()+    }++    @Test+    fun `saveSettings persists and restores`() = runTest {+        val vm = idleVm()+        vm.saveSettings(app, autoSave = true, autoSaveInterval = 45, defaultFontSize = 18f)+        assertTrue(vm.autoSaveEnabled.value)+        assertEquals(45_000L, vm.autoSaveIntervalMs)+        assertEquals(18f, vm.getDefaultFontSize(app))+        assertEquals(45, vm.getAutoSaveInterval(app))+        assertTrue(vm.getAutoSaveEnabled(app))++        val vm2 = idleVm()+        vm2.loadSettings(app)+        assertTrue(vm2.autoSaveEnabled.value)+        assertEquals(45_000L, vm2.autoSaveIntervalMs)+        // Cancel both auto-save loops: runTest's teardown advanceUntilIdle would chase+        // their infinite while(true){delay()} forever.+        vm.setAutoSave(false)+        vm2.setAutoSave(false)+    }++    @Test+    fun `theme mode persists through settings`() = runTest {+        val vm = idleVm()+        vm.setDocumentThemeMode(app, OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM)+        assertEquals(OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM, vm.getDocumentThemeMode(app))+        // Legacy dark-mode key migrates to the new mode on load.+        prefs.edit().clear()+            .putBoolean("document_dark_mode", true)+            .apply()+        val vm2 = idleVm()+        vm2.loadSettings(app)+        assertEquals(OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM, vm2.documentThemeMode.value)+    }++    @Test+    fun `DocumentThemeMode parse and toggle`() {+        assertEquals(+            OfficeViewModel.DocumentThemeMode.UNCHANGED,+            OfficeViewModel.DocumentThemeMode.parse(null),+        )+        assertEquals(+            OfficeViewModel.DocumentThemeMode.UNCHANGED,+            OfficeViewModel.DocumentThemeMode.parse("bogus"),+        )+        assertEquals(+            OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM,+            OfficeViewModel.DocumentThemeMode.parse("FOLLOW_SYSTEM"),+        )+        assertEquals(+            OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM,+            OfficeViewModel.DocumentThemeMode.UNCHANGED.toggled(),+        )+        assertEquals(+            OfficeViewModel.DocumentThemeMode.UNCHANGED,+            OfficeViewModel.DocumentThemeMode.FOLLOW_SYSTEM.toggled(),+        )+    }++    @Test+    fun `OfficeRoles canEdit`() {+        assertTrue(OfficeRoles.canEdit(OfficeRoles.OWNER))+        assertTrue(OfficeRoles.canEdit(OfficeRoles.EDITOR))+        assertFalse(OfficeRoles.canEdit(OfficeRoles.VIEWER))+        assertFalse(OfficeRoles.canEdit(OfficeRoles.REVOKED))+        assertFalse(OfficeRoles.canEdit("bogus"))+    }++    @Test+    fun `officeDocMetaFromInvite carries role and owner key`() {+        val inv = OfficeSync.Invite(+            docId = "d1", key = "keyB64", title = "Shared",+            charMode = true, role = OfficeRoles.VIEWER, ownerKey = "ownerB64", charKind = "text",+        )+        val meta = officeDocMetaFromInvite(inv)+        assertEquals("d1", meta.docId)+        assertEquals("Shared", meta.title)+        assertEquals("keyB64", meta.keyB64)+        assertEquals(false, meta.owner)+        assertEquals(true, meta.charMode)+        assertEquals(OfficeRoles.VIEWER, meta.role)+        assertEquals("ownerB64", meta.ownerKeyB64)+        assertEquals("text", meta.charKind)+    }++    @Test+    fun `docPlainText joins paragraph spans`() = runTest {+        val vm = idleVm()+        val doc = OdfDocument.TextDocument(+            title = "t",+            content = listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("a"), OdfSpan("b")))),+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("c")))),+            ),+        )+        assertEquals("ab\nc", vm.docPlainText(doc))+        assertNull(vm.docPlainText(OdfDocument.Spreadsheet(title = "s", sheets = emptyList())))+    }++    @Test+    fun `remapRemoteCarets shifts carets on text change`() = runTest {+        val vm = idleVm()+        val before = textDoc("hello world")+        val after = textDoc("hello brave world")+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(before)+        vm.remotePresenceMutable.value = listOf(+            // Caret at the insertion point stays left (change is at/after it).+            OfficePresence(id = "p1", name = "N", typing = false, ts = 0L, caret = 6),+            // Caret after the insertion shifts by the delta (+6).+            OfficePresence(id = "p3", name = "O", typing = false, ts = 0L, caret = 8),+            OfficePresence(id = "p2", name = "M", typing = false, ts = 0L, caret = null),+        )+        vm.updateDocument(after)+        val updated = vm.remotePresenceMutable.value+        assertEquals(6, updated.first { it.id == "p1" }.caret)+        assertEquals(14, updated.first { it.id == "p3" }.caret)+        assertNull(updated.first { it.id == "p2" }.caret)+    }++    @Test+    fun `remapRemoteCarets is a no-op without carets`() = runTest {+        val vm = idleVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc("a"))+        vm.updateDocument(textDoc("b"))+        assertTrue(vm.remotePresenceMutable.value.isEmpty())+    }++    @Test+    fun `ViewState variants hold their payloads`() {+        val doc = textDoc("x")+        val loaded = OfficeViewModel.ViewState.Loaded(doc)+        assertEquals(doc, loaded.document)+        val err = OfficeViewModel.ViewState.Error("boom")+        assertEquals("boom", err.message)+        assertTrue(OfficeViewModel.ViewState.Empty is OfficeViewModel.ViewState.Empty)+        assertTrue(OfficeViewModel.ViewState.Loading is OfficeViewModel.ViewState.Loading)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelDocsSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelDocsSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelDocsSlice3Test.ktnew file mode 100644index 0000000000..ac9c91ead1--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelDocsSlice3Test.kt@@ -0,0 +1,342 @@+package com.vayunmathur.office.util++import android.net.Uri+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfPageSetup+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableRow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.mockito.Mockito.`when`+import org.robolectric.RobolectricTestRunner++/**+ * Slice 3/4: documents/recent/save-as, tracked changes, footnotes/comments,+ * headers/footers, links, fields and in-text tables on [OfficeViewModel].+ *+ * Robolectric (not plain JVM): several paths use `Uri.parse`/`Uri.fromFile` statics,+ * which are stubs on the plain JVM.+ */+@RunWith(RobolectricTestRunner::class)+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelDocsSlice3Test : OfficeViewModelSlice3Harness() {++    private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(+        title = "Doc",+        content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+    )++    private fun loaded(vararg texts: String): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc(*texts))+        return vm+    }++    private fun textOf(vm: OfficeViewModel): OdfDocument.TextDocument =+        (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument++    @Test+    fun `createNewTextDocument and clearDocument`() = runTest {+        val vm = idleVm()+        vm.createNewTextDocument()+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Loaded)+        assertTrue(vm.isEditMode.value)+        assertTrue(vm.hasUnsavedChanges.value)+        vm.clearDocument()+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Empty)+        assertFalse(vm.isEditMode.value)+        assertFalse(vm.hasUnsavedChanges.value)+        assertFalse(vm.isOnline.value)+    }++    @Test+    fun `recent files add dedupe cap and clear`() = runTest {+        val vm = idleVm()+        val uri = Uri.parse("file:///tmp/a.odt")+        vm.addToRecent(app, uri, "a.odt")+        vm.addToRecent(app, uri, "a.odt")+        assertEquals(1, vm.getRecentFiles(app).size)+        assertEquals("a.odt", vm.getRecentFiles(app)[0].second)+        repeat(25) { i -> vm.addToRecent(app, Uri.parse("file:///tmp/$i.odt"), "$i.odt") }+        assertEquals(MAX_RECENT, vm.getRecentFiles(app).size)+        assertEquals("24.odt", vm.getRecentFiles(app)[0].second)+        vm.clearRecentFiles(app)+        assertTrue(vm.getRecentFiles(app).isEmpty())+    }++    @Test+    fun `needsSaveAs and isWritable for file uris`() = runTest {+        val vm = idleVm()+        assertTrue(vm.needsSaveAs())+        val missing = java.io.File(tmpDir, "nope.odt")+        vm.originalUri = Uri.fromFile(missing)+        // Non-existent file is not writable -> Save As needed.+        assertTrue(vm.needsSaveAs())+        val real = java.io.File(tmpDir, "doc.odt")+        real.writeText("x")+        vm.originalUri = Uri.fromFile(real)+        assertFalse(vm.needsSaveAs())+        assertTrue(vm.isWritable(Uri.fromFile(real)))+        assertFalse(vm.isWritable(Uri.fromFile(missing)))+    }++    @Test+    fun `needsSaveAs with content uri consults permission`() = runTest {+        val vm = idleVm()+        val uri = Uri.parse("content://com.example/docs/1")+        `when`(app.checkCallingOrSelfUriPermission(uri, android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION))+            .thenReturn(android.content.pm.PackageManager.PERMISSION_DENIED)+        vm.originalUri = uri+        assertTrue(vm.needsSaveAs())+    }++    @Test+    fun `save with no target is a no-op without loaded doc`() = runTest {+        val vm = idleVm()+        vm.save()+        assertFalse(vm.isSaving.value)+    }++    @Test+    fun `persistToAppStorage returns file uris inside docs dir`() = runTest {+        val vm = idleVm()+        val inside = java.io.File(java.io.File(tmpDir, "documents").apply { mkdirs() }, "x.odt")+        inside.writeText("x")+        val uri = Uri.fromFile(inside)+        assertEquals(uri, vm.persistToAppStorage(uri, "x.odt"))+    }++    @Test+    fun `accept reject change insertion and deletion`() = runTest {+        fun changeDoc() = textDoc("hello world").copy(+            changes = listOf(+                com.vayunmathur.library.ui.odf.OdfChange(id = "c1", type = "insertion"),+                com.vayunmathur.library.ui.odf.OdfChange(id = "c2", type = "deletion"),+            ),+            content = listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(+                    OdfSpan("hello "),+                    OdfSpan("brave ", changeId = "c1", changeKind = "insertion"),+                    OdfSpan("world", changeId = "c2", changeKind = "deletion"),+                ))),+            ),+        )+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        // Accept insertion: span stays, marker cleared.+        vm.acceptChange("c1")+        var doc = textOf(vm)+        assertTrue(doc.changes.none { it.id == "c1" })+        assertTrue(doc.content.joinToString("") {+            ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })+        }.contains("brave"))+        // Reject deletion: text kept, marker cleared.+        vm.rejectChange("c2")+        doc = textOf(vm)+        assertTrue(doc.changes.none { it.id == "c2" })+        assertTrue(textOf(vm).content.joinToString("") {+            ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })+        }.contains("world"))+        // Unknown id is a no-op.+        vm.acceptChange("nope")+        // Non-text doc is a no-op.+        val sheet = newVm()+        sheet.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Spreadsheet(title = "B", sheets = emptyList()))+        sheet.acceptChange("c1")+        sheet.rejectChange("c1")+    }++    @Test+    fun `acceptAll and rejectAll changes`() = runTest {+        fun changeDoc() = textDoc("ab").copy(+            changes = listOf(+                com.vayunmathur.library.ui.odf.OdfChange(id = "c1", type = "insertion"),+                com.vayunmathur.library.ui.odf.OdfChange(id = "c2", type = "deletion"),+            ),+            content = listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(+                    OdfSpan("a", changeId = "c1", changeKind = "insertion"),+                    OdfSpan("b", changeId = "c2", changeKind = "deletion"),+                ))),+            ),+        )+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        vm.acceptAllChanges()+        var text = textOf(vm).content.joinToString("") {+            ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })+        }+        // Insertion kept, deletion removed.+        assertEquals("a", text)+        assertTrue(textOf(vm).changes.isEmpty())+        val vm2 = newVm()+        vm2.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        vm2.rejectAllChanges()+        text = textOf(vm2).content.joinToString("") {+            ((it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text })+        }+        // Insertion removed, deletion kept.+        assertEquals("b", text)+    }++    @Test+    fun `page setup header footer footnote comment`() = runTest {+        val vm = loaded("body text")+        vm.setPageSetup(OdfPageSetup(widthPx = 100f, heightPx = 50f))+        assertEquals(true, textOf(vm).pageSetup!!.isLandscape)+        vm.setHeaderText("head\ntwo")+        vm.setFooterText("foot")+        assertEquals(2, textOf(vm).headerParagraphs.size)+        assertEquals(1, textOf(vm).footerParagraphs.size)+        vm.setHeaderText("  ")+        assertTrue(textOf(vm).headerParagraphs.isEmpty())+        vm.insertFootnote(0, 0, 9, "note body")+        assertEquals(1, textOf(vm).footnotes.size)+        assertEquals("note body", textOf(vm).footnotes[0].body[0].spans[0].text)+        assertTrue(paraHas(vm, "[1]"))+        vm.insertComment(0, "Ann", "nice")+        assertTrue(textOf(vm).content.joinToString("") {+            ((it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.any { s -> s.annotation != null } ?: false).toString()+        }.contains("true"))+        // Resolve the comment span (last span of block 0).+        val spans = (textOf(vm).content[0] as OdfContentBlock.Paragraph).paragraph.spans+        vm.resolveComment(0, spans.size - 1)+        assertFalse((textOf(vm).content[0] as OdfContentBlock.Paragraph)+            .paragraph.spans.any { it.annotation != null })+    }++    private fun paraHas(vm: OfficeViewModel, needle: String): Boolean =+        textOf(vm).content.any {+            ((it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text }+                ?: "").contains(needle)+        }++    @Test+    fun `links set inspect remove selected text`() = runTest {+        val vm = loaded("click here now")+        // runSelectedText reads the current run text.+        assertEquals("click", vm.runSelectedText(0, 0, 0, 5))+        vm.setLink(0, 0, 6, 10, "here", "https://example.com")+        val info = vm.linkAt(0, 0, 8)+        assertEquals("https://example.com", info!!.url)+        assertEquals("here", info.text)+        assertEquals(null, vm.linkAt(0, 0, 2))+        vm.removeLinkInRun(0, 0, 6, 10)+        assertEquals(null, vm.linkAt(0, 0, 8))+        assertTrue(paraHas(vm, "here"))+    }++    @Test+    fun `field insert and display values`() = runTest {+        val vm = loaded("today: ")+        vm.insertFieldInRun(0, 0, 7, "date", vm.fieldDisplayValue("date"))+        assertTrue(paraHas(vm, "-"))+        assertEquals("1", vm.fieldDisplayValue("page-number"))+        assertEquals("1", vm.fieldDisplayValue("page-count"))+        assertEquals("", vm.fieldDisplayValue("bogus-kind"))+        // Metadata-backed fields.+        vm.updateMetadata { it.copy(author = "Ann", title = "T", subject = "S", description = "D") }+        assertEquals("Ann", vm.fieldDisplayValue("author-name"))+        assertEquals("T", vm.fieldDisplayValue("title"))+        assertEquals("S", vm.fieldDisplayValue("subject"))+        assertEquals("D", vm.fieldDisplayValue("description"))+        assertTrue(vm.fieldDisplayValue("time").contains(":"))+    }++    @Test+    fun `in-text tables crud merge format`() = runTest {+        val vm = loaded("top")+        vm.insertTableForTest()+        var table = textOf(vm).tableAt(1)+        assertEquals(2, table.rows.size)+        assertEquals(2, table.rows[0].cells.size)+        vm.updateTextTableCell(1, 0, 0, "A\nB")+        assertEquals(2, textOf(vm).tableAt(1).rows[0].cells[0].paragraphs.size)+        vm.textTableAddRow(1, 0)+        vm.textTableAddColumn(1, 0)+        assertEquals(3, textOf(vm).tableAt(1).rows.size)+        assertEquals(3, textOf(vm).tableAt(1).rows[0].cells.size)+        vm.mergeTextTableCells(1, 0, 0, 1, 1)+        assertEquals(2, textOf(vm).tableAt(1).rows[0].cells[0].colSpan)+        assertTrue(textOf(vm).tableAt(1).rows[1].cells[1].isCovered)+        vm.unmergeTextTableCells(1, 0, 0)+        assertEquals(1, textOf(vm).tableAt(1).rows[0].cells[0].colSpan)+        vm.setTextTableCellSpanFormat(1, 0, 0) { it.copy(bold = true) }+        assertTrue(textOf(vm).tableAt(1).rows[0].cells[0].paragraphs.all { p ->+            p.spans.all { it.bold }+        })+        vm.setTextTableCellAlignment(1, 0, 0, androidx.compose.ui.text.style.TextAlign.Center)+        vm.setTextTableCellBackground(1, 0, 0, 0xFFFF0000L)+        assertEquals(0xFFFF0000L, textOf(vm).tableAt(1).rows[0].cells[0].backgroundColor)+        vm.textTableDeleteRow(1, 0)+        vm.textTableDeleteColumn(1, 0)+        assertEquals(2, textOf(vm).tableAt(1).rows.size)+        // Out-of-range row/col edits are contained no-ops.+        vm.updateTextTableCell(1, 9, 9, "z")+        vm.textTableDeleteRow(1, 9)+    }++    private fun OfficeViewModel.insertTableForTest() {+        insertTable(0, 2, 2)+    }++    private fun OdfDocument.TextDocument.tableAt(i: Int): OdfTable =+        (content[i] as OdfContentBlock.Table).table++    @Test+    fun `currentDocRole online id canEdit myDisplayName`() = runTest {+        val vm = idleVm()+        assertEquals(OfficeRoles.OWNER, vm.currentDocRole())+        assertEquals(null, vm.currentOnlineDocId())+        assertTrue(vm.canEditCurrent())+        // Offline docs are always editable; the role gate applies once online.+        vm.currentRole = OfficeRoles.VIEWER+        assertTrue(vm.canEditCurrent())+        vm.currentDocId = "d1"+        assertFalse(vm.canEditCurrent())+        assertEquals("d1", vm.currentOnlineDocId())+        assertTrue(vm.myDisplayName().startsWith("User "))+    }++    @Test+    fun `signing bytes builders are canonical`() = runTest {+        val vm = idleVm()+        val m = OfficeMember("id1", "Ann", OfficeRoles.EDITOR)+        assertEquals("doc|id1|editor",+            vm.memberSigningBytes("doc", m).decodeToString())+        assertEquals("doc|title|Hello",+            vm.titleSigningBytes("doc", "Hello").decodeToString())+        assertEquals("doc|owner|n1|keyB64",+            vm.ownerSigningBytes("doc", "n1", "keyB64").decodeToString())+        val epoch = vm.epochSigningBytes("doc", 2, mapOf("b" to "2", "a" to "1"))+        assertEquals("doc|2|a=1|b=2", epoch.decodeToString())+        assertEquals("https://maproj.org/of/share#id=d9&owner=${vm.syncDeviceId}",+            vm.shareLinkFor("d9"))+    }++    @Test+    fun `withTitle setLoadedTitle resolveShareTitle`() = runTest {+        val vm = loaded("x")+        val doc = textOf(vm)+        assertEquals("N", (vm.withTitle(doc, "N") as OdfDocument.TextDocument).title)+        vm.setLoadedTitle("Renamed")+        assertEquals("Renamed", textOf(vm).title)+        // First share: blank docName falls back to doc title.+        vm.currentDocId = null+        assertEquals("Doc", vm.resolveShareTitle("  ", "Doc"))+        // Later share keeps the stored online title.+        vm.currentDocId = "d1"+        vm.onlineDocsMutable.value = listOf(+            OfficeDocMeta(docId = "d1", title = "Stored", keyB64 = "", owner = true))+        assertEquals("Stored", vm.resolveShareTitle("New", "Doc"))+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelExportBranchesSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelExportBranchesSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelExportBranchesSlice3Test.ktnew file mode 100644index 0000000000..b32554286f--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelExportBranchesSlice3Test.kt@@ -0,0 +1,155 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableRow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4, round 4c: plain-text export branches on [OfficeViewModel] โ€” every+ * [OdfContentBlock] kind, multi-sheet spreadsheets with covered cells, and+ * frame-vs-shape slide/drawing elements.+ *+ * `exportAsPlainText`/`appendTextBlockPlain`/`appendSheetPlain`/+ * `appendSlideElementsPlain` carry the largest missed-instruction counts in the+ * non-sync slice files, and all branches run with pure in-memory documents.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelExportBranchesSlice3Test : OfficeViewModelSlice3Harness() {++    private fun loaded(doc: OdfDocument): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        return vm+    }++    private fun para(text: String) =+        OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++    @Test+    fun `plain text covers every text block kind`() = runTest {+        val chart = com.vayunmathur.library.ui.odf.OdfChart(+            type = com.vayunmathur.library.ui.odf.ChartType.BAR,+            categories = listOf("a"),+            series = listOf(com.vayunmathur.library.ui.odf.OdfChartSeries("s", listOf(1f))),+        )+        val doc = OdfDocument.TextDocument(+            title = "T",+            content = listOf(+                para("para one"),+                OdfContentBlock.Table(OdfTable("T", rows = listOf(+                    OdfTableRow(listOf(+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c00"))))),+                        OdfTableCell(+                            listOf(OdfParagraph(listOf(OdfSpan("hidden")))),+                            isCovered = true),+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c02"))))),+                    )),+                ))),+                OdfContentBlock.Image(OdfImage(path = "p", imageData = byteArrayOf())),+                OdfContentBlock.Chart(chart),+                OdfContentBlock.Formula(+                    "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">" ++                        "<mrow><mi>x</mi></mrow></math>"),+                OdfContentBlock.TableOfContents(+                    "Contents",+                    listOf(OdfParagraph(listOf(OdfSpan("entry one"))))),+                OdfContentBlock.SectionStart("S1"),+                OdfContentBlock.SectionEnd,+                OdfContentBlock.PageBreak,+            ),+        )+        val plain = loaded(doc).exportAsPlainText()+        assertTrue(plain.contains("para one"), plain)+        // Table row skips the covered cell but keeps the visible ones.+        assertTrue(plain.contains("c00"), plain)+        assertTrue(plain.contains("c02"), plain)+        assertTrue(!plain.contains("hidden"), plain)+        assertTrue(plain.contains("[Image]"), plain)+        assertTrue(plain.contains("[Chart]"), plain)+        assertTrue(plain.contains("[Formula]"), plain)+        assertTrue(plain.contains("Contents"), plain)+        assertTrue(plain.contains("entry one"), plain)+        assertTrue(plain.contains("---"), plain)+    }++    @Test+    fun `plain text covers multi-sheet spreadsheets`() = runTest {+        fun row(vararg texts: String) = OdfRow(texts.map { OdfCell(it) })+        val doc = OdfDocument.Spreadsheet(+            title = "B",+            sheets = listOf(+                OdfSheet("First", listOf(row("a1", "b1"))),+                OdfSheet(+                    "Second",+                    listOf(OdfRow(listOf(+                        OdfCell("v00"),+                        OdfCell("hidden", isCovered = true),+                        OdfCell("v02"),+                    ))),+                ),+            ),+        )+        val plain = loaded(doc).exportAsPlainText()+        assertTrue(plain.contains("=== First ==="), plain)+        assertTrue(plain.contains("=== Second ==="), plain)+        assertTrue(plain.contains("a1"), plain)+        assertTrue(plain.contains("v00"), plain)+        assertTrue(!plain.contains("hidden"), plain)+    }++    @Test+    fun `plain text covers frame and shape slide elements`() = runTest {+        val frameEl = OdfSlideElement.Frame(OdfFrame(+            x = 0f, y = 0f, width = 10f, height = 10f,+            paragraphs = listOf(OdfParagraph(listOf(OdfSpan("frame text"))))))+        val shapeEl = OdfSlideElement.Shape(com.vayunmathur.library.ui.odf.OdfShape.Rect(+            0f, 0f, 10f, 10f,+            text = listOf(OdfParagraph(listOf(OdfSpan("shape text"))))))+        val pres = OdfDocument.Presentation(+            title = "P",+            slides = listOf(OdfSlide(name = "S1", elements = listOf(frameEl, shapeEl))),+        )+        val plain = loaded(pres).exportAsPlainText()+        assertTrue(plain.contains("=== S1 ==="), plain)+        assertTrue(plain.contains("frame text"), plain)+        assertTrue(plain.contains("shape text"), plain)+        val drawing = OdfDocument.Drawing(+            title = "G",+            pages = listOf(OdfSlide(name = "Pg", elements = listOf(shapeEl))),+        )+        val dplain = loaded(drawing).exportAsPlainText()+        assertTrue(dplain.contains("=== Pg ==="), dplain)+        assertTrue(dplain.contains("shape text"), dplain)+    }++    @Test+    fun `plain text table with multi-paragraph cells`() = runTest {+        val cell = OdfTableCell(listOf(+            OdfParagraph(listOf(OdfSpan("l1"))),+            OdfParagraph(listOf(OdfSpan("l2"))),+        ))+        val doc = OdfDocument.TextDocument(+            title = "T",+            content = listOf(+                OdfContentBlock.Table(OdfTable("T", rows = listOf(OdfTableRow(listOf(cell))))),+            ),+        )+        val plain = loaded(doc).exportAsPlainText()+        assertTrue(plain.contains("l1 l2"), plain)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelLiveSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelLiveSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelLiveSlice3Test.ktnew file mode 100644index 0000000000..0ad7e6207d--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelLiveSlice3Test.kt@@ -0,0 +1,224 @@+package com.vayunmathur.office.util++import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.io.encoding.Base64+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4, round 4: live-channel dispatch + signed-op validation gates on+ * [OfficeViewModel], exercised with real PQC keys (no network).+ *+ * `handleLive`/`applySignedOp` verify author signatures via [Pqc.verify]+ * against the roster in `currentMembers` + `memberKeyCache`, so a test-owned+ * keypair drives the whole path without touching the server.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelLiveSlice3Test : OfficeViewModelSlice3Harness() {++    private fun textDoc() = OdfDocument.TextDocument(+        title = "Doc",+        content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi"))))),+    )++    /** Fresh PQC keypairs for two collaborators. */+    private fun keypairs(): Triple<ByteArray, ByteArray, ByteArray> {+        val (kemPubA, _) = Pqc.generateKem()+        val (dsaPubA, dsaPrivA) = Pqc.generateDsa()+        val bundleA = Pqc.bundle(kemPubA, dsaPubA)+        val (kemPubB, _) = Pqc.generateKem()+        val (dsaPubB, _) = Pqc.generateDsa()+        val bundleB = Pqc.bundle(kemPubB, dsaPubB)+        return Triple(bundleA, bundleB, dsaPrivA)+    }++    private fun setupRoster(vm: OfficeViewModel, selfId: String, peerId: String, peerBundle: ByteArray) {+        // Our own ops are always ours; the peer must be an editor with a cached key.+        vm.currentMembers[selfId] = OfficeRoles.OWNER+        vm.currentMembers[peerId] = OfficeRoles.EDITOR+        vm.memberKeyCache[peerId] = peerBundle+    }++    private fun signedOp(author: String, ops: String, dsaPriv: ByteArray): String {+        val sig = Base64.encode(Pqc.signWith(dsaPriv, ops.encodeToByteArray()))+        return vmJson().encodeToString(SignedOp(author, sig, ops))+    }++    private fun vmJson() = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }++    @Test+    fun `applySignedOp rejects malformed json`() = runTest {+        val vm = idleVm()+        val tree = DocumentTreeCrdt("self")+        try {+            assertFalse(vm.applySignedOp(tree, "not-json{{"))+        } finally {+            tree.close()+        }+    }++    @Test+    fun `applySignedOp rejects viewer-role authors`() = runTest {+        val (bundleA, bundleB, dsaPrivA) = keypairs()+        val vm = idleVm()+        vm.currentMembers["peer1"] = OfficeRoles.VIEWER+        vm.memberKeyCache["peer1"] = bundleB+        val tree = DocumentTreeCrdt("self")+        try {+            val plain = signedOp("peer1", "[]", dsaPrivA)+            assertFalse(vm.applySignedOp(tree, plain))+        } finally {+            tree.close()+        }+        // bundleA unused here other than keeping keygen honest; silence the warning.+        assertTrue(bundleA.isNotEmpty())+    }++    @Test+    fun `applySignedOp rejects unknown author without cached key`() = runTest {+        val (_, _, dsaPrivA) = keypairs()+        val vm = idleVm()+        vm.currentMembers["ghost"] = OfficeRoles.EDITOR+        val tree = DocumentTreeCrdt("self")+        try {+            // No memberKeyCache entry and OfficeSync.getKey hits network โ€” but the+            // role gate passes, so memberKey() would go to network. Instead verify the+            // author-not-in-roster path: unknown id defaults to VIEWER -> rejected.+            val plain = signedOp("stranger", "[]", dsaPrivA)+            assertFalse(vm.applySignedOp(tree, plain))+        } finally {+            tree.close()+        }+    }++    @Test+    fun `applySignedOp rejects bad signature`() = runTest {+        val (_, bundleB, _) = keypairs()+        val (_, _, dsaPrivOther) = keypairs()+        val vm = idleVm()+        vm.currentMembers["peer1"] = OfficeRoles.EDITOR+        vm.memberKeyCache["peer1"] = bundleB+        val tree = DocumentTreeCrdt("self")+        try {+            // Signed by a different key than the cached bundle -> verify fails.+            val plain = signedOp("peer1", "[]", dsaPrivOther)+            assertFalse(vm.applySignedOp(tree, plain))+        } finally {+            tree.close()+        }+    }++    @Test+    fun `applySignedOp accepts own op without roster`() = runTest {+        val (bundleA, _, dsaPrivA) = keypairs()+        val vm = idleVm()+        val selfId = "self-device"+        // Mirror OfficeSync.deviceId for the "own ops are always ours" branch.+        // We can't set deviceId (private setter), so use the real one:+        val realSelf = OfficeSync.deviceId+        vm.memberKeyCache[realSelf] = bundleA+        val tree = DocumentTreeCrdt(realSelf.ifBlank { "self-device" })+        try {+            // Own op with a signature that verifies against our cached key.+            val plain = signedOp(realSelf, "[]", dsaPrivA)+            // Even with an empty ops array, applyJson("[]") is a no-op merge -> true.+            val ok = vm.applySignedOp(tree, plain)+            assertTrue(ok)+            assertEquals(selfId.ifBlank { "self-device" }.let { "x" }, "x") // selfId kept for intent+        } finally {+            tree.close()+        }+    }++    @Test+    fun `applySignedOp accepts valid peer op`() = runTest {+        val (_, bundleB, _) = keypairs()+        val (kemC, _) = Pqc.generateKem()+        val (dsaPubB2, dsaPrivB) = Pqc.generateDsa()+        val bundleB2 = Pqc.bundle(kemC, dsaPubB2)+        val vm = idleVm()+        vm.currentMembers["peer1"] = OfficeRoles.EDITOR+        vm.memberKeyCache["peer1"] = bundleB2+        val tree = DocumentTreeCrdt("self")+        try {+            val plain = signedOp("peer1", "[]", dsaPrivB)+            assertTrue(vm.applySignedOp(tree, plain))+        } finally {+            tree.close()+        }+        assertTrue(bundleB.isNotEmpty())+    }++    @Test+    fun `handleLive ignores malformed payloads`() = runTest {+        val vm = idleVm()+        val before = vm.remotePresenceMutable.value+        vm.handleLive("not-json{{", "doc1", ByteArray(32))+        assertEquals(before, vm.remotePresenceMutable.value)+        // Unknown message type is ignored too.+        val raw = vmJson().encodeToString(+            kotlinx.serialization.json.buildJsonObject {+                put("t", kotlinx.serialization.json.JsonPrimitive("bogus"))+            })+        vm.handleLive(raw, "doc1", ByteArray(32))+        assertEquals(before, vm.remotePresenceMutable.value)+    }++    @Test+    fun `handleLive applies peer presence`() = runTest {+        val vm = idleVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc())+        val key = ByteArray(32) { it.toByte() }+        val p = OfficePresence("peer9", "Zed", typing = true, ts = 1, caret = 1)+        val blob = Base64.encode(E2ee.aesEncrypt(+            key, vmJson().encodeToString(OfficePresence.serializer(), p).encodeToByteArray()))+        val raw = vmJson().encodeToString(OfficeSync.LiveMsg(t = "presence", data = blob))+        vm.handleLive(raw, "doc1", key)+        val peers = vm.remotePresenceMutable.value+        assertEquals(1, peers.size)+        assertEquals("peer9", peers[0].id)+        assertTrue(peers[0].typing)+    }++    @Test+    fun `setLocalCaret and setLocalLocation update without doc`() = runTest {+        val vm = idleVm()+        // No currentDocId -> broadcastPresence early-returns, no network.+        vm.setLocalCaret(7)+        vm.setLocalLocation("Sheet 1 ยท B3")+        assertEquals(7, vm.localCaret)+        assertEquals("Sheet 1 ยท B3", vm.localLoc)+        vm.setLocalLocation(null)+        assertEquals(null, vm.localLoc)+    }++    @Test+    fun `onLocalEdit and syncCurrentDocument are no-ops offline`() = runTest {+        val vm = idleVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc())+        // No currentDocId/key -> both return before any network.+        vm.onLocalEdit()+        vm.syncCurrentDocument()+        assertTrue(vm.state.value is OfficeViewModel.ViewState.Loaded)+        dispatcher.scheduler.runCurrent()+    }++    @Test+    fun `startLive and handleLive actions branch needs tree`() = runTest {+        val vm = idleVm()+        // "actions" with no currentTree: applyLiveActions returns early inside the+        // mutex-guarded coroutine; just verify no crash and presence untouched.+        val raw = vmJson().encodeToString(OfficeSync.LiveMsg(t = "actions", seq = 1))+        vm.handleLive(raw, "doc1", ByteArray(32))+        dispatcher.scheduler.runCurrent()+        assertTrue(vm.remotePresenceMutable.value.isEmpty())+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSaveSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSaveSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSaveSlice3Test.ktnew file mode 100644index 0000000000..c93e4a37fd--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSaveSlice3Test.kt@@ -0,0 +1,180 @@+package com.vayunmathur.office.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain++/**+ * Slice 3/4, round 4b: Robolectric save/load round-trips on [OfficeViewModel].+ *+ * The plain-JVM Mockito harness can't serve `Uri.fromFile`/content-resolver calls,+ * so these use the real Robolectric Application: `persistToAppStorage` copies a+ * foreign file into `filesDir/documents`, and a real save to a tmp file followed+ * by `DocumentImporter.open` proves the packaged writer output parses.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelSaveSlice3Test : OfficeViewModelSlice3Harness() {++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext<android.app.Application>()++    private fun roboVm(): OfficeViewModel {+        // Real Robolectric Application: contentResolver serves file:// uris, so+        // persistToAppStorage + save/load round-trips run for real.+        Dispatchers.setMain(dispatcher)+        return OfficeViewModel(roboApp)+    }++    private fun textDoc(vararg texts: String) = OdfDocument.TextDocument(+        title = "Doc",+        content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+    )++    private fun roboLoaded(vararg texts: String): OfficeViewModel {+        val vm = roboVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(textDoc(*texts))+        return vm+    }++    private fun displayedText(vm: OfficeViewModel): String {+        val doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        return doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("\n") { it.paragraph.spans.joinToString("") { s -> s.text } }+    }++    private fun paragraphsOf(doc: OdfDocument.TextDocument): String =+        doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("\n") { it.paragraph.spans.joinToString("") { s -> s.text } }++    @Test+    fun `persistToAppStorage copies foreign files into docs dir`() = runTest {+        val vm = roboVm()+        val outside = java.io.File(tmpDir, "foreign.odt")+        outside.writeText("hello-foreign")+        val uri = android.net.Uri.fromFile(outside)+        val copied = vm.persistToAppStorage(uri, "foreign.odt")+        // Lands inside the app-private documents dir, with content preserved.+        assertTrue(copied.path!!.contains("documents"))+        val dest = java.io.File(copied.path!!)+        assertTrue(dest.exists())+        assertEquals("hello-foreign", dest.readText())+        // A second call on the copied uri short-circuits (already inside).+        assertEquals(copied, vm.persistToAppStorage(copied, "foreign.odt"))+    }++    @Test+    fun `save writes a package that re-imports`() = runTest {+        val vm = roboLoaded("saved line one", "saved line two")+        val target = java.io.File(tmpDir, "roundtrip.odt")+        val targetUri = android.net.Uri.fromFile(target)+        vm.documentUri = null+        vm.originalUri = targetUri+        vm.save()+        dispatcher.scheduler.runCurrent()+        // Let the IO-dispatched save coroutine finish (Robolectric runs it for real).+        var spins = 0+        while (!target.exists() && spins < 200) {+            Thread.sleep(25)+            spins+++        }+        assertTrue(target.exists(), "save should write ${target.absolutePath}")+        val reopened = com.vayunmathur.office.odf.DocumentImporter.open(+            roboApp, targetUri, "roundtrip.odt")+        val text = paragraphsOf(reopened as OdfDocument.TextDocument)+        assertTrue(text.contains("saved line one"), "round-trip text was: $text")+        assertTrue(text.contains("saved line two"))+        assertEquals("saved line one\nsaved line two", displayedText(vm))+    }++    @Test+    fun `save with source package preserves and rewrites`() = runTest {+        // First save a doc from scratch, then load it via DocumentImporter and save+        // again with the file as the source package (exercises copySourceEntries).+        val first = roboLoaded("v1 text")+        val target = java.io.File(tmpDir, "v1.odt")+        val targetUri = android.net.Uri.fromFile(target)+        first.documentUri = null+        first.originalUri = targetUri+        first.save()+        var spins = 0+        while (!target.exists() && spins < 200) {+            Thread.sleep(25)+            spins+++        }+        assertTrue(target.exists())+        val imported =+            com.vayunmathur.office.odf.DocumentImporter.open(roboApp, targetUri, "v1.odt")+        val vm2 = roboVm()+        vm2.stateMutable.value = OfficeViewModel.ViewState.Loaded(imported)+        vm2.documentUri = targetUri+        vm2.originalUri = targetUri+        vm2.updateParagraphText(0, "v2 text")+        vm2.save()+        spins = 0+        while (spins < 40) {+            Thread.sleep(25)+            spins+++        }+        val reopened =+            com.vayunmathur.office.odf.DocumentImporter.open(roboApp, targetUri, "v1.odt")+        val text = paragraphsOf(reopened as OdfDocument.TextDocument)+        assertTrue(text.contains("v2 text"), "rewritten text was: $text")+    }++    @Test+    fun `loadDocument imports a saved package`() = runTest {+        // Seed a real .odt via the writer, then loadDocument should import it+        // (exercises the IO coroutine: persistToAppStorage + DocumentImporter.open).+        val seed = roboLoaded("loaded line")+        val target = java.io.File(tmpDir, "seed.odt")+        val targetUri = android.net.Uri.fromFile(target)+        seed.documentUri = null+        seed.originalUri = targetUri+        seed.save()+        var spins = 0+        while (!target.exists() && spins < 200) {+            Thread.sleep(25)+            spins+++        }+        assertTrue(target.exists())+        val vm = roboVm()+        vm.loadDocument(targetUri, "seed.odt")+        spins = 0+        while (vm.state.value !is OfficeViewModel.ViewState.Loaded && spins < 200) {+            Thread.sleep(25)+            spins+++        }+        val state = vm.state.value+        assertTrue(state is OfficeViewModel.ViewState.Loaded, "state was $state")+        val text = paragraphsOf(state.document as OdfDocument.TextDocument)+        assertTrue(text.contains("loaded line"), "loaded text was: $text")+        assertTrue(vm.isEditMode.value)+    }++    @Test+    fun `loadDocument surfaces errors for missing files`() = runTest {+        val vm = roboVm()+        val missing = java.io.File(tmpDir, "does-not-exist.odt")+        vm.loadDocument(android.net.Uri.fromFile(missing), "does-not-exist.odt")+        var spins = 0+        while (vm.state.value is OfficeViewModel.ViewState.Loading && spins < 200) {+            Thread.sleep(25)+            spins+++        }+        assertTrue(+            vm.state.value is OfficeViewModel.ViewState.Error,+            "state was ${vm.state.value}")+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSheetSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSheetSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSheetSlice3Test.ktnew file mode 100644index 0000000000..41a5653e2c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSheetSlice3Test.kt@@ -0,0 +1,303 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfNumberFormat+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4: spreadsheet editing ops on [OfficeViewModel] โ€” cells, rows/columns,+ * sheets, formats, merge/sort/fill, comments and sizing.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelSheetSlice3Test : OfficeViewModelSlice3Harness() {++    private fun sheetDoc(+        rows: List<List<String>> = listOf(listOf("a1", "b1"), listOf("a2", "b2")),+        name: String = "Sheet 1",+    ) = OdfDocument.Spreadsheet(+        title = "Book",+        sheets = listOf(OdfSheet(name, rows.map { r -> OdfRow(r.map { OdfCell(text = it) }) })),+    )++    private fun loaded(): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(sheetDoc())+        return vm+    }++    private fun cells(vm: OfficeViewModel, sheet: Int = 0): List<OdfRow> =+        ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[sheet].rows++    @Test+    fun `updateCellText stores plain text and numbers`() = runTest {+        val vm = loaded()+        vm.updateCellText(0, 0, 0, "hello")+        var cell = cells(vm)[0].cells[0]+        assertEquals("hello", cell.text)+        assertEquals("string", cell.valueType)+        assertNull(cell.formula)+        vm.updateCellText(0, 0, 0, "3.5")+        cell = cells(vm)[0].cells[0]+        assertEquals(3.5, cell.numberValue)+        assertEquals("float", cell.valueType)+        assertTrue(vm.hasUnsavedChanges.value)+    }++    @Test+    fun `updateCellText apostrophe forces literal text`() = runTest {+        val vm = loaded()+        vm.updateCellText(0, 0, 0, "'=A1")+        val cell = cells(vm)[0].cells[0]+        assertEquals("=A1", cell.text)+        assertNull(cell.formula)+        vm.updateCellText(0, 0, 1, "'")+        assertEquals("", cells(vm)[0].cells[1].text)+    }++    @Test+    fun `updateCellText formula stores OpenFormula`() = runTest {+        val vm = loaded()+        vm.updateCellText(0, 0, 0, "=A2+B1")+        val cell = cells(vm)[0].cells[0]+        assertEquals("=A2+B1", cell.text)+        assertTrue(cell.formula!!.startsWith("of:="))+        assertEquals("float", cell.valueType)+        assertNull(cell.numberValue)+        // Text-producing function gets string type.+        vm.updateCellText(0, 1, 0, "=UPPER(A1)")+        assertEquals("string", cells(vm)[1].cells[0].valueType)+    }++    @Test+    fun `updateCellText out of bounds is a no-op`() = runTest {+        val vm = loaded()+        vm.updateCellText(0, 0, 9, "x")+        vm.updateCellText(0, 9, 0, "x")+        vm.updateCellText(9, 0, 0, "x")+        assertEquals("a1", cells(vm)[0].cells[0].text)+        assertFalse(vm.canUndo.value)+    }++    @Test+    fun `add delete rows and columns`() = runTest {+        val vm = loaded()+        vm.addRow(0, 0)+        assertEquals(3, cells(vm).size)+        assertEquals(2, cells(vm)[1].cells.size)+        vm.addColumn(0)+        assertEquals(3, cells(vm)[0].cells.size)+        vm.deleteColumn(0, 0)+        assertEquals(2, cells(vm)[0].cells.size)+        vm.deleteRow(0, 0)+        assertEquals(2, cells(vm).size)+        // Last row is protected.+        val single = newVm()+        single.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            sheetDoc(rows = listOf(listOf("only"))))+        single.deleteRow(0, 0)+        assertEquals(1, (((single.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].rows.size))+        single.deleteColumn(0, 0)+        assertEquals(1, (((single.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].rows[0].cells.size))+    }++    @Test+    fun `rename add delete sheet`() = runTest {+        val vm = loaded()+        vm.renameSheet(0, "Data")+        vm.addSheet()+        var doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet+        assertEquals("Data", doc.sheets[0].name)+        assertEquals(2, doc.sheets.size)+        assertEquals("Sheet 2", doc.sheets[1].name)+        assertEquals(10, doc.sheets[1].rows.size)+        vm.deleteSheet(1)+        doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet+        assertEquals(1, doc.sheets.size)+        // Sole sheet is protected.+        vm.deleteSheet(0)+        doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet+        assertEquals(1, doc.sheets.size)+        vm.deleteSheet(9)+        assertEquals(1, ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets.size)+    }++    @Test+    fun `cell formatting toggles`() = runTest {+        val vm = loaded()+        vm.setCellBold(0, 0, 0)+        vm.setCellItalic(0, 0, 0)+        vm.setCellColor(0, 0, 0, 0xFFFF0000L)+        vm.setCellBgColor(0, 0, 0, 0xFF00FF00L)+        vm.setCellAlignment(0, 0, 0, androidx.compose.ui.text.style.TextAlign.Right)+        vm.setCellBorder(0, 0, 0, 0xFF0000FFL)+        val cell = cells(vm)[0].cells[0]+        assertTrue(cell.bold)+        assertTrue(cell.italic)+        assertEquals(0xFFFF0000L, cell.textColor)+        assertEquals(0xFF00FF00L, cell.backgroundColor)+        assertEquals(androidx.compose.ui.text.style.TextAlign.Right, cell.alignment)+        assertEquals(0xFF0000FFL, cell.borderColor)+        vm.setCellBold(0, 0, 0)+        assertFalse(cells(vm)[0].cells[0].bold)+    }++    @Test+    fun `cell number format maps to value type`() = runTest {+        val vm = loaded()+        vm.setCellNumberFormat(0, 0, 0, OdfNumberFormat(isDate = true))+        assertEquals("date", cells(vm)[0].cells[0].valueType)+        vm.setCellNumberFormat(0, 0, 0, OdfNumberFormat(percent = true))+        assertEquals("percentage", cells(vm)[0].cells[0].valueType)+        vm.setCellNumberFormat(0, 0, 0, OdfNumberFormat(currencySymbol = "$"))+        assertEquals("currency", cells(vm)[0].cells[0].valueType)+        vm.setCellNumberFormat(0, 0, 0, OdfNumberFormat(decimals = 2))+        assertEquals("float", cells(vm)[0].cells[0].valueType)+        val before = cells(vm)[0].cells[0].valueType+        vm.setCellNumberFormat(0, 0, 0, null)+        assertEquals(before, cells(vm)[0].cells[0].valueType)+    }++    @Test+    fun `freeze panes clamps negatives`() = runTest {+        val vm = loaded()+        vm.setSheetFreeze(0, 1, 2)+        var sheet = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0]+        assertEquals(1, sheet.freezeRows)+        assertEquals(2, sheet.freezeCols)+        vm.setSheetFreeze(0, -3, -1)+        sheet = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0]+        assertEquals(0, sheet.freezeRows)+        assertEquals(0, sheet.freezeCols)+    }++    @Test+    fun `fillDown copies values and shifts formulas`() = runTest {+        val vm = loaded()+        vm.updateCellText(0, 0, 0, "v")+        vm.fillDown(0, 0, 0, 1)+        assertEquals("v", cells(vm)[1].cells[0].text)+        // Formula fill shifts the relative reference down one row.+        val vm2 = loaded()+        vm2.updateCellText(0, 0, 1, "=A1")+        vm2.fillDown(0, 0, 1, 1)+        assertEquals("=A2", cells(vm2)[1].cells[1].text)+        // fillDownToEnd reaches the last row.+        vm2.fillDownToEnd(0, 0, 0)+        assertEquals("a1", cells(vm2)[1].cells[0].text)+        // Backward range is a no-op.+        vm2.fillDown(0, 1, 0, 0)+    }++    @Test+    fun `merge and unmerge cells`() = runTest {+        val vm = loaded()+        vm.mergeCells(0, 0, 0, 1, 1)+        var topLeft = cells(vm)[0].cells[0]+        assertEquals(2, topLeft.spannedColumns)+        assertEquals(2, topLeft.rowSpan)+        assertTrue(cells(vm)[1].cells[1].isCovered)+        vm.unmergeCells(0, 0, 0)+        topLeft = cells(vm)[0].cells[0]+        assertEquals(1, topLeft.spannedColumns)+        assertFalse(cells(vm)[1].cells[1].isCovered)+        // Unmerging a plain cell is a no-op.+        vm.unmergeCells(0, 0, 0)+        assertFalse(cells(vm)[0].cells[0].isCovered)+    }++    @Test+    fun `sortRows orders numerically then lexically`() = runTest {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            sheetDoc(rows = listOf(listOf("b", "2"), listOf("a", "10"), listOf("c", "1"))))+        vm.sortRows(0, 1, ascending = true)+        assertEquals(listOf("1", "2", "10"), cells(vm).map { it.cells[1].text })+        vm.sortRows(0, 0, ascending = false)+        assertEquals(listOf("c", "b", "a"), cells(vm).map { it.cells[0].text })+    }++    @Test+    fun `cell comments set and clear`() = runTest {+        val vm = loaded()+        assertEquals("", vm.cellCommentText(0, 0, 0))+        vm.setCellComment(0, 0, 0, "Ann", "review this")+        assertEquals("review this", vm.cellCommentText(0, 0, 0))+        vm.setCellComment(0, 0, 0, "Ann", "")+        assertEquals("", vm.cellCommentText(0, 0, 0))+        assertEquals("", vm.cellCommentText(9, 0, 0))+    }++    @Test+    fun `column widths and row heights grow lists`() = runTest {+        val vm = loaded()+        vm.setColumnWidth(0, 3, 120f)+        vm.setRowHeight(0, 4, 30f)+        val sheet = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0]+        assertEquals(120f, sheet.columnWidths[3])+        assertEquals(30f, sheet.rowHeights[4])+        vm.setColumnWidth(0, 0, null)+        assertNull(((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].columnWidths[0])+    }++    @Test+    fun `floating shapes images charts elements`() = runTest {+        val vm = loaded()+        vm.addShapeToSheet(0, "ellipse")+        vm.insertChartIntoSheet(0, com.vayunmathur.library.ui.odf.OdfChart(+            type = com.vayunmathur.library.ui.odf.ChartType.PIE,+            categories = listOf("a"),+            series = listOf(com.vayunmathur.library.ui.odf.OdfChartSeries("s", listOf(1f))),+        ))+        vm.insertImageIntoSheet(0, "f.png", byteArrayOf(7))+        var floating = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].floating+        assertEquals(3, floating.size)+        vm.updateSheetElementText(0, 0, "shape text")+        vm.setSheetElementBounds(0, 0, 1f, 2f, 50f, 60f)+        vm.rotateSheetImage(0, 2, 45f)+        val img = ((floating[2] as com.vayunmathur.library.ui.odf.OdfSlideElement.Frame).frame.image)!!+        // rotateSheetImage ran before the re-read; verify via fresh state below.+        assertEquals(0f, img.rotationDegrees)+        floating = ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].floating+        val rotated = ((floating[2] as com.vayunmathur.library.ui.odf.OdfSlideElement.Frame).frame.image)!!+        assertEquals(45f, rotated.rotationDegrees)+        vm.setSheetImageCrop(0, 2, 0.1f, 0f, 0f, 0f)+        vm.replaceSheetImage(0, 2, "g.png", byteArrayOf(8))+        vm.deleteSheetElement(0, 0)+        assertEquals(2, ((vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].floating.size)+    }++    @Test+    fun `createNewSpreadsheet builds default grid`() = runTest {+        val vm = idleVm()+        vm.createNewSpreadsheet()+        val doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet+        assertEquals("Untitled Spreadsheet", doc.title)+        assertEquals(10, doc.sheets[0].rows.size)+        assertEquals(5, doc.sheets[0].rows[0].cells.size)+        assertTrue(vm.isEditMode.value)+        assertTrue(vm.hasUnsavedChanges.value)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlice3Harness.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlice3Harness.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlice3Harness.ktnew file mode 100644index 0000000000..d1c53d6799--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlice3Harness.kt@@ -0,0 +1,115 @@+package com.vayunmathur.office.util++import android.app.Application+import android.content.Context+import android.content.SharedPreferences+import java.io.File+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.mockito.Mockito.mock+import org.mockito.Mockito.`when`++/** In-memory [SharedPreferences] so settings paths run for real on the plain JVM. */+class FakeSharedPreferences : SharedPreferences {+    private val data = mutableMapOf<String, Any?>()+    private val listeners = mutableSetOf<SharedPreferences.OnSharedPreferenceChangeListener>()++    override fun getAll(): Map<String, *> = data.toMap()+    override fun getString(key: String, defValue: String?): String? =+        if (data.containsKey(key)) data[key] as String? else defValue+    override fun getStringSet(key: String, defValues: Set<String>?): Set<String>? =+        if (data.containsKey(key)) @Suppress("UNCHECKED_CAST") (data[key] as Set<String>?) else defValues+    override fun getInt(key: String, defValue: Int): Int = (data[key] as Int?) ?: defValue+    override fun getLong(key: String, defValue: Long): Long = (data[key] as Long?) ?: defValue+    override fun getFloat(key: String, defValue: Float): Float = (data[key] as Float?) ?: defValue+    override fun getBoolean(key: String, defValue: Boolean): Boolean = (data[key] as Boolean?) ?: defValue+    override fun contains(key: String): Boolean = data.containsKey(key)+    override fun edit(): SharedPreferences.Editor = FakeEditor()+    override fun registerOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener) {+        listeners.add(l)+    }+    override fun unregisterOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener) {+        listeners.remove(l)+    }++    private inner class FakeEditor : SharedPreferences.Editor {+        private val pending = mutableMapOf<String, Any?>()+        private var clear = false++        override fun putString(k: String, v: String?): SharedPreferences.Editor = apply { pending[k] = v }+        override fun putStringSet(k: String, v: Set<String>?): SharedPreferences.Editor = apply { pending[k] = v }+        override fun putInt(k: String, v: Int): SharedPreferences.Editor = apply { pending[k] = v }+        override fun putLong(k: String, v: Long): SharedPreferences.Editor = apply { pending[k] = v }+        override fun putFloat(k: String, v: Float): SharedPreferences.Editor = apply { pending[k] = v }+        override fun putBoolean(k: String, v: Boolean): SharedPreferences.Editor = apply { pending[k] = v }+        override fun remove(k: String): SharedPreferences.Editor = apply { pending[k] = null }+        override fun clear(): SharedPreferences.Editor = apply { clear = true }+        override fun commit(): Boolean {+            apply()+            return true+        }+        override fun apply() {+            if (clear) data.clear()+            for ((k, v) in pending) {+                if (v == null) data.remove(k) else data[k] = v+            }+            pending.clear()+        }+    }+}++/**+ * Slice 3/4 shared harness: an [OfficeViewModel] on the plain JVM with a mocked [Application].+ *+ * The mock answers `applicationContext`/`filesDir` (a real temp dir, so the DataStore-backed+ * `hasOnlineIdentity()` in `init` resolves to false) and `getSharedPreferences` (in-memory fakes,+ * so the settings paths run for real). `Dispatchers.setMain` serves `viewModelScope`.+ */+@OptIn(ExperimentalCoroutinesApi::class)+abstract class OfficeViewModelSlice3Harness {+    val dispatcher = StandardTestDispatcher()+    lateinit var tmpDir: File+    lateinit var app: Application+    val prefs = FakeSharedPreferences()++    @BeforeTest+    fun harnessSetUp() {+        Dispatchers.setMain(dispatcher)+        tmpDir = Files.createTempDirectory("office-vm-test").toFile()+        app = mock(Application::class.java)+        `when`(app.applicationContext).thenReturn(app)+        `when`(app.filesDir).thenReturn(tmpDir)+        `when`(app.getSharedPreferences(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyInt()))+            .thenReturn(prefs)+    }++    @AfterTest+    fun harnessTearDown() {+        Dispatchers.resetMain()+        tmpDir.deleteRecursively()+    }++    fun newVm(): OfficeViewModel = OfficeViewModel(app)++    suspend fun idleVm(): OfficeViewModel {+        val vm = newVm()+        // NOTE: runCurrent(), never advanceUntilIdle(): enabling auto-save starts an+        // infinite while(true){delay()} loop on viewModelScope, which advanceUntilIdle+        // would chase forever. runCurrent only runs tasks due at the current virtual time.+        dispatcher.scheduler.runCurrent()+        return vm+    }++    fun loadedVm(doc: com.vayunmathur.library.ui.odf.OdfDocument): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        return vm+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlidesSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlidesSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlidesSlice3Test.ktnew file mode 100644index 0000000000..12b0ff5bb3--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSlidesSlice3Test.kt@@ -0,0 +1,314 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.ChartType+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4: presentation editing ops on [OfficeViewModel] โ€” slides, elements,+ * notes/chrome, rotation, colors and bounds.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)+class OfficeViewModelSlidesSlice3Test : OfficeViewModelSlice3Harness() {++    private fun frame(text: String) = OdfSlideElement.Frame(+        OdfFrame(x = 10f, y = 10f, width = 100f, height = 50f,+            paragraphs = listOf(OdfParagraph(listOf(OdfSpan(text))))))++    private fun slideDoc() = OdfDocument.Presentation(+        title = "Deck",+        slides = listOf(+            OdfSlide(name = "Slide 1", elements = listOf(frame("one"))),+            OdfSlide(name = "Slide 2", elements = listOf(frame("two"))),+        ),+    )++    private fun loaded(): OfficeViewModel {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(slideDoc())+        return vm+    }++    private fun docOf(vm: OfficeViewModel): OdfDocument.Presentation =+        (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.Presentation++    private fun barChart() = OdfChart(+        type = ChartType.BAR,+        categories = listOf("a"),+        series = listOf(OdfChartSeries("s", listOf(1f))),+    )++    @Test+    fun `add delete duplicate move slides`() = runTest {+        val vm = loaded()+        vm.addSlide(0)+        assertEquals(3, docOf(vm).slides.size)+        assertEquals("Slide 3", docOf(vm).slides[1].name)+        vm.duplicateSlide(0)+        assertTrue(docOf(vm).slides[1].name.endsWith("(copy)"))+        vm.moveSlideUp(1)+        assertTrue(docOf(vm).slides[0].name.endsWith("(copy)"))+        vm.moveSlideDown(0)+        assertTrue(docOf(vm).slides[1].name.endsWith("(copy)"))+        // Boundary moves are no-ops.+        vm.moveSlideUp(0)+        vm.moveSlideDown(docOf(vm).slides.size - 1)+        vm.deleteSlide(0)+        assertEquals(3, docOf(vm).slides.size)+        // Sole slide is protected.+        val single = newVm()+        single.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Presentation(title = "D", slides = listOf(+                OdfSlide(name = "Only", elements = emptyList()))))+        single.deleteSlide(0)+        assertEquals(1, ((single.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Presentation).slides.size)+    }++    @Test+    fun `updateSlideElementText for frame and shape`() = runTest {+        val vm = loaded()+        vm.updateSlideElementText(0, 0, "new\nlines")+        val paras = (docOf(vm).slides[0].elements[0] as OdfSlideElement.Frame).frame.paragraphs+        assertEquals(listOf("new", "lines"), paras.map { it.spans.joinToString("") { s -> s.text } })+        // Shape element path.+        vm.addShapeToSlide(0, "rect")+        vm.updateSlideElementText(0, 1, "shaped")+        val shape = (docOf(vm).slides[0].elements[1] as OdfSlideElement.Shape).shape+        assertEquals("shaped", shape.text.joinToString("") { p -> p.spans.joinToString("") { it.text } })+    }++    @Test+    fun `addTextBox addShape insertImage insertChart`() = runTest {+        val vm = loaded()+        vm.addTextBoxToSlide(0)+        vm.addShapeToSlide(0, "ellipse")+        vm.addShapeToSlide(0, "line")+        vm.addShapeToSlide(0, "bogus-kind-defaults-to-rect")+        vm.insertImageIntoSlide(0, "s.png", byteArrayOf(1))+        vm.insertChartIntoSlide(0, barChart())+        val els = docOf(vm).slides[0].elements+        assertEquals(7, els.size)+        assertTrue(els[5] is OdfSlideElement.Frame)+        val imgFrame = (els[5] as OdfSlideElement.Frame).frame+        assertEquals("Pictures/s.png", imgFrame.image!!.path)+        assertTrue(docOf(vm).images.containsKey("Pictures/s.png"))+        assertTrue((els[6] as OdfSlideElement.Frame).frame.chart != null)+        assertTrue(els[2] is OdfSlideElement.Shape)+    }++    @Test+    fun `slide notes background transition`() = runTest {+        val vm = loaded()+        vm.setSlideNotes(0, "line1\nline2")+        assertEquals("line1\nline2", vm.slideNotesText(0))+        vm.setSlideNotes(0, "  ")+        assertEquals("", vm.slideNotesText(0))+        assertEquals("", vm.slideNotesText(9))+        vm.setSlideBackgroundColor(0, 0xFFFF0000L)+        assertEquals(0xFFFF0000L, docOf(vm).slides[0].backgroundColor)+        vm.setSlideBackgroundColor(0, null)+        assertEquals(null, docOf(vm).slides[0].backgroundColor)+        vm.setSlideTransition(0, "fade", "fast")+        assertEquals("fade", docOf(vm).slides[0].transitionType)+        assertEquals("fast", docOf(vm).slides[0].transitionSpeed)+    }++    @Test+    fun `slide element text style toggles`() = runTest {+        val vm = loaded()+        vm.toggleSlideElementBold(0, 0)+        vm.toggleSlideElementItalic(0, 0)+        vm.toggleSlideElementUnderline(0, 0)+        vm.setSlideElementColor(0, 0, 0xFF00FF00L)+        val span = (docOf(vm).slides[0].elements[0] as OdfSlideElement.Frame)+            .frame.paragraphs[0].spans[0]+        assertTrue(span.bold)+        assertTrue(span.italic)+        assertTrue(span.underline)+        assertEquals(0xFF00FF00L, span.color)+        vm.toggleSlideElementBold(0, 0)+        assertFalse((docOf(vm).slides[0].elements[0] as OdfSlideElement.Frame)+            .frame.paragraphs[0].spans[0].bold)+        vm.setSlideElementAlignment(0, 0, androidx.compose.ui.text.style.TextAlign.Center)+        assertEquals(androidx.compose.ui.text.style.TextAlign.Center,+            (docOf(vm).slides[0].elements[0] as OdfSlideElement.Frame)+                .frame.paragraphs[0].alignment)+    }++    @Test+    fun `element bounds move and delete duplicate reorder`() = runTest {+        val vm = loaded()+        vm.addTextBoxToSlide(0)+        vm.setSlideElementBounds(0, 1, 5f, 6f, 70f, 80f)+        val b = (docOf(vm).slides[0].elements[1] as OdfSlideElement.Frame).frame+        assertEquals(5f, b.x)+        assertEquals(70f, b.width)+        vm.duplicateSlideElement(0, 1)+        assertEquals(3, docOf(vm).slides[0].elements.size)+        val dup = (docOf(vm).slides[0].elements[2] as OdfSlideElement.Frame).frame+        assertEquals(25f, dup.x)+        assertEquals(26f, dup.y)+        // Reorder to front moves the original first element last.+        vm.reorderSlideElement(0, 0, toFront = true)+        val moved = docOf(vm).slides[0].elements.last() as OdfSlideElement.Frame+        assertEquals("one", moved.frame.paragraphs[0].spans[0].text)+        vm.deleteSlideElement(0, 0)+        assertEquals(2, docOf(vm).slides[0].elements.size)+        // Out-of-range delete is a no-op.+        vm.deleteSlideElement(0, 9)+        assertEquals(2, docOf(vm).slides[0].elements.size)+    }++    @Test+    fun `rotation for shapes and image frames`() = runTest {+        val vm = loaded()+        vm.addShapeToSlide(0, "rect")+        vm.setSlideElementRotation(0, 1, 30f)+        assertEquals(30f, (docOf(vm).slides[0].elements[1] as OdfSlideElement.Shape).shape.rotationDegrees)+        // Frame without an image: rotation is a no-op that keeps the element.+        vm.setSlideElementRotation(0, 0, 15f)+        assertTrue(docOf(vm).slides[0].elements[0] is OdfSlideElement.Frame)+        // Frame with an image rotates the image.+        vm.insertImageIntoSlide(0, "r.png", byteArrayOf(2))+        vm.setSlideElementRotation(0, 2, 45f)+        assertEquals(45f, (docOf(vm).slides[0].elements[2] as OdfSlideElement.Frame).frame.image!!.rotationDegrees)+        // Legacy rotateSlideImage path.+        vm.rotateSlideImage(0, 2, 45f)+        assertEquals(90f, (docOf(vm).slides[0].elements[2] as OdfSlideElement.Frame).frame.image!!.rotationDegrees)+    }++    @Test+    fun `slide image crop fill stroke recolor`() = runTest {+        val vm = loaded()+        vm.insertImageIntoSlide(0, "c.png", byteArrayOf(3))+        vm.setSlideImageCrop(0, 1, 0.1f, 0.2f, 0.3f, 0.4f)+        assertEquals(0.1f, (docOf(vm).slides[0].elements[1] as OdfSlideElement.Frame).frame.image!!.cropLeftPct)+        vm.setSlideElementFill(0, 1, 0xFFFF0000L)+        vm.setSlideElementStroke(0, 1, 0xFF00FF00L)+        val frame = (docOf(vm).slides[0].elements[1] as OdfSlideElement.Frame).frame+        assertEquals(0xFFFF0000L, frame.fillColor)+        assertEquals(0xFF00FF00L, frame.strokeColor)+        // Shape recolor across all shape kinds.+        vm.addShapeToSlide(0, "ellipse")+        vm.setSlideElementFill(0, 2, 0xFF0000FFL)+        assertEquals(0xFF0000FFL, ((docOf(vm).slides[0].elements[2] as OdfSlideElement.Shape).shape as OdfShape.Ellipse).fillColor)+        // Crop on a non-image frame leaves the element unchanged.+        val before = docOf(vm).slides[0].elements[0]+        vm.setSlideImageCrop(0, 0, 0.5f, 0.5f, 0.5f, 0.5f)+        assertEquals(before, docOf(vm).slides[0].elements[0])+        // Replace bytes resets crop/rotation and registers the new path.+        vm.replaceSlideImage(0, 1, "d.png", byteArrayOf(4))+        val replaced = (docOf(vm).slides[0].elements[1] as OdfSlideElement.Frame).frame.image!!+        assertEquals("Pictures/d.png", replaced.path)+        assertEquals(0f, replaced.rotationDegrees)+        assertTrue(docOf(vm).images.containsKey("Pictures/d.png"))+    }++    @Test+    fun `createNewPresentation builds title slide`() = runTest {+        val vm = idleVm()+        vm.createNewPresentation()+        val doc = (vm.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Presentation+        assertEquals("Untitled Presentation", doc.title)+        assertEquals(1, doc.slides.size)+        assertTrue(vm.isEditMode.value)+        assertTrue(vm.hasUnsavedChanges.value)+    }++    @Test+    fun `exportCsv quotes and delimits`() = runTest {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Spreadsheet(title = "B", sheets = listOf(+                com.vayunmathur.library.ui.odf.OdfSheet("S", listOf(+                    com.vayunmathur.library.ui.odf.OdfRow(listOf(+                        com.vayunmathur.library.ui.odf.OdfCell("a,b"),+                        com.vayunmathur.library.ui.odf.OdfCell("q\"q"),+                    )),+                    com.vayunmathur.library.ui.odf.OdfRow(listOf(+                        com.vayunmathur.library.ui.odf.OdfCell("plain"),+                        com.vayunmathur.library.ui.odf.OdfCell("multi\nline"),+                    )),+                )))))+        val csv = vm.exportCsv()+        assertTrue(csv.contains("\"a,b\""))+        assertTrue(csv.contains("\"q\"\"q\""))+        assertTrue(csv.contains("\"multi\nline\""))+        val semi = vm.exportCsv(';')+        assertTrue(semi.contains(";"))+        // Non-spreadsheet doc exports empty.+        val text = newVm()+        text.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(title = "T", content = emptyList()))+        assertEquals("", text.exportCsv())+        val empty = newVm()+        assertEquals("", empty.exportCsv())+    }++    @Test+    fun `exportAsPlainText covers all doc kinds`() = runTest {+        val text = newVm()+        text.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(title = "T", content = listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi")))),+                OdfContentBlock.PageBreak,+                OdfContentBlock.Image(com.vayunmathur.library.ui.odf.OdfImage(+                    path = "p", imageData = byteArrayOf())),+                OdfContentBlock.TableOfContents("TOC", listOf(OdfParagraph(listOf(OdfSpan("e"))))),+            )))+        val plain = text.exportAsPlainText()+        assertTrue(plain.contains("hi"))+        assertTrue(plain.contains("---"))+        assertTrue(plain.contains("[Image]"))+        assertTrue(plain.contains("TOC"))+        val pres = loaded()+        assertTrue(pres.exportAsPlainText().contains("Slide 1"))+        assertTrue(pres.exportFlat().isNotEmpty())+        assertEquals("pptx", pres.ooxmlExtension())+        val empty = newVm()+        assertEquals("", empty.exportAsPlainText())+        assertEquals("", empty.exportFlat())+    }++    @Test+    fun `exportMarkdown html rtf latex epub pdf ooxml`() = runTest {+        val vm = newVm()+        vm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(title = "T", content = listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hello")))))))+        assertTrue(vm.exportMarkdown().contains("hello"))+        assertTrue(vm.exportHtml().contains("hello"))+        assertTrue(vm.exportRtf().isNotEmpty())+        assertTrue(vm.exportLatex().isNotEmpty())+        assertTrue(vm.exportEpub().isNotEmpty())+        assertTrue(vm.exportPdf().isNotEmpty())+        assertTrue(vm.exportOoxml().isNotEmpty())+        val sheetVm = newVm()+        sheetVm.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.Spreadsheet(title = "B", sheets = listOf(+                com.vayunmathur.library.ui.odf.OdfSheet("S", listOf(+                    com.vayunmathur.library.ui.odf.OdfRow(listOf(+                        com.vayunmathur.library.ui.odf.OdfCell("x"))))))))+        assertEquals("xlsx", sheetVm.ooxmlExtension())+        assertEquals("", sheetVm.exportMarkdown())+        assertEquals("", sheetVm.exportHtml())+        val empty = newVm()+        assertEquals("", empty.exportMarkdown())+        assertEquals(0, empty.exportOoxml().size)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSyncSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSyncSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSyncSlice3Test.ktnew file mode 100644index 0000000000..a91f589584--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelSyncSlice3Test.kt@@ -0,0 +1,721 @@+package com.vayunmathur.office.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.util.DataStoreUtils+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.mockito.ArgumentMatchers.anyBoolean+import org.mockito.ArgumentMatchers.anyLong+import org.mockito.ArgumentMatchers.anyString+import org.mockito.Mockito.mock+import org.mockito.Mockito.`when`++/**+ * Slice 3/4: SyncA/B/C ViewModel helpers with no real network.+ *+ * A test PQC identity is installed on [OfficeSync] so signing/sealing runs+ * for real; every server call fails fast on DNS (devserver has no route to+ * the relay), so the production code's offline/null-result branches are the+ * behaviour under test. DataStore-backed helpers are driven against either+ * the real Robolectric store or a map-backed mock.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class OfficeViewModelSyncSlice3Test {++    private class MemStore : E2eeKeyStore {+        private val m = HashMap<String, ByteArray>()+        override suspend fun getBytes(name: String): ByteArray? = m[name]+        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+            if (onlyIfAbsent && m.containsKey(name)) return+            m[name] = value+        }+    }++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext()++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(UnconfinedTestDispatcher())+        runBlocking {+            if (runCatching { OfficeSync.identity }.isFailure) {+                OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "slice3sync")+            }+        }+    }++    @AfterTest+    fun tearDown() {+        OfficeSync.stopLive()+        Dispatchers.resetMain()+    }++    private fun vm(): OfficeViewModel = OfficeViewModel(roboApp)++    private fun loadedVm(text: String = "sync line"): OfficeViewModel {+        val v = vm()+        v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(+                title = "Doc",+                content = listOf(+                    OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))+        return v+    }++    private fun realDs(): DataStoreUtils = DataStoreUtils.getInstance(roboApp)++    /** Map-backed DataStoreUtils mock for the ds-taking helpers. */+    private fun mockDs(+        strings: MutableMap<String, String?> = mutableMapOf(),+        longs: MutableMap<String, Long?> = mutableMapOf(),+    ): DataStoreUtils {+        val ds = mock(DataStoreUtils::class.java)+        `when`(ds.getString(anyString())).thenAnswer { strings[it.arguments[0] as String] }+        `when`(ds.getLong(anyString())).thenAnswer { longs[it.arguments[0] as String] }+        runBlocking {+            `when`(ds.setString(anyString(), anyString(), anyBoolean())).thenAnswer {+                strings[it.arguments[0] as String] = it.arguments[1] as String+                null+            }+            `when`(ds.setLong(anyString(), anyLong(), anyBoolean())).thenAnswer {+                longs[it.arguments[0] as String] = it.arguments[1] as Long+                null+            }+        }+        return ds+    }++    private fun await(timeoutMs: Long = 10_000, cond: () -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return true+            Thread.sleep(20)+        }+        return cond()+    }++    private fun stopJobs(v: OfficeViewModel) {+        OfficeSync.stopLive()+        v.livePollJob?.cancel()+        v.presenceTickJob?.cancel()+        v.caretPresenceJob?.cancel()+        v.livePushJob?.cancel()+    }++    // ---- SyncB: index / requests against a mock store ----++    @Test+    fun `pullInboxInvites returns empty inbox result offline`() = runTest {+        val v = vm()+        val ds = mockDs()+        val res = v.pullInboxInvites(ds)+        assertNotNull(res)+        assertTrue(res.invites.isEmpty())+        assertEquals(0, res.seq)+    }++    @Test+    fun `mergeRequests keeps only owned deduped requests`() = runTest {+        val v = vm()+        val strings = mutableMapOf<String, String?>()+        val ds = mockDs(strings)+        v.saveIndex(ds, listOf(+            OfficeDocMeta(docId = "owned", title = "O", keyB64 = "aw==", owner = true),+            OfficeDocMeta(docId = "foreign", title = "F", keyB64 = "aw==", owner = false)))+        val req = OfficeSync.JoinRequest(docId = "owned", requesterId = "r1", name = "Ann")+        val res = OfficeSync.InboxResult(+            invites = emptyList(),+            requests = listOf(+                req, req,+                OfficeSync.JoinRequest(docId = "foreign", requesterId = "r2"),+                OfficeSync.JoinRequest(docId = "owned", requesterId = "r1")),+            seq = 4)+        v.mergeRequests(ds, res)+        assertEquals(listOf(req), v.loadRequests(ds))+        assertEquals(listOf(req), v.pendingRequestsMutable.value)+        // Empty request list is a no-op.+        v.mergeRequests(ds, OfficeSync.InboxResult(emptyList(), emptyList(), 5))+        assertEquals(listOf(req), v.loadRequests(ds))+    }++    @Test+    fun `refreshTitles tolerates bad keys and offline fetches`() = runTest {+        val v = vm()+        val ds = mockDs()+        val metas = listOf(+            OfficeDocMeta(docId = "bad", title = "B", keyB64 = "!!!", owner = false),+            OfficeDocMeta(+                docId = "good", title = "G",+                keyB64 = Base64.encode(ByteArray(32)), owner = false,+                ownerKeyB64 = Base64.encode(OfficeSync.publicBundle)))+        v.saveIndex(ds, metas)+        v.refreshTitles(ds)+        // No title could be fetched offline, so the index is unchanged.+        assertEquals(metas, v.loadIndex(ds))+    }++    @Test+    fun `loadTree and saveTree round-trip through store`() = runTest {+        val v = loadedVm("tree text")+        val strings = mutableMapOf<String, String?>()+        val ds = mockDs(strings)+        assertNull(v.loadTree(ds, "missing"))+        val tree = DocumentTreeCrdt("dev-tree")+        try {+            tree.updateJson(v.exportFlat())+            v.saveTree(ds, "d-tree", tree)+            assertTrue(strings.containsKey("crdt:d-tree"))+            val back = v.loadTree(ds, "d-tree")+            assertNotNull(back)+            try {+                assertEquals(tree.render(), back.render())+            } finally {+                back.close()+            }+        } finally {+            tree.close()+        }+    }++    @Test+    fun `parseFlat parses exported doc and rejects garbage`() = runTest {+        val v = loadedVm("flat text")+        val parsed = v.parseFlat(v.exportFlat())+        assertNotNull(parsed)+        // DocumentImporter titles the import after the temp file name.+        assertEquals("merge.fodt", parsed.title)+        val text = (parsed as OdfDocument.TextDocument).content+            .filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }+        assertTrue(text.contains("flat text"), text)+    }++    // ---- SyncB: syncDoc / share helpers ----++    @Test+    fun `syncDoc pushes local ops and persists tree offline`() = runTest {+        val v = loadedVm("synced text")+        val key = ByteArray(32) { it.toByte() }+        v.currentRole = OfficeRoles.EDITOR+        val tree = DocumentTreeCrdt("dev-sync")+        v.currentTree = tree+        v.syncDoc("doc-sync-1", key)+        // Tree was persisted under the doc id and renders the local text.+        val stored = realDs().getString("crdt:doc-sync-1")+        assertNotNull(stored)+        assertTrue(tree.render().contains("synced text"), tree.render())+        assertEquals(0L, realDs().getLong("crdtCursor:doc-sync-1") ?: -1L)+    }++    @Test+    fun `syncDoc viewer does not push and adopts stored tree`() = runTest {+        val v = loadedVm("viewer text")+        val key = ByteArray(32) { 7 }+        v.currentRole = OfficeRoles.VIEWER+        v.currentTree = null+        v.syncDoc("doc-sync-viewer", key)+        assertNotNull(v.currentTree)+        assertTrue(v.currentTree!!.render().contains("viewer text"))+    }++    @Test+    fun `share title and registration helpers`() = runTest {+        val v = loadedVm()+        // Offline registration fails (relay unreachable) with a human error.+        val err = v.ensureShareRegistration()+        assertNotNull(err)+        assertTrue(err.contains("register", ignoreCase = true), err)+        // First share: explicit name wins, blank falls back to doc title.+        v.currentDocId = null+        assertEquals("Named", v.resolveShareTitle("  Named  ", "DocTitle"))+        assertEquals("DocTitle", v.resolveShareTitle(" ", "DocTitle"))+        assertEquals("Document", v.resolveShareTitle("", null))+        // Later shares keep the stored online title.+        v.currentDocId = "d9"+        v.onlineDocsMutable.value = listOf(+            OfficeDocMeta(docId = "d9", title = "Stored", keyB64 = "", owner = true))+        assertEquals("Stored", v.resolveShareTitle("Other", "DocTitle"))+    }++    @Test+    fun `initShareOwnership claims owner role and retitles`() = runTest {+        val v = loadedVm()+        val key = ByteArray(32)+        v.initShareOwnership("Online Name", key, hasDoc = true)+        assertEquals(OfficeRoles.OWNER, v.currentRole)+        assertEquals(0, v.currentEpoch)+        assertTrue(key.contentEquals(v.currentBaseKey!!))+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        assertEquals("Online Name", doc.title)+        assertEquals(+            OfficeRoles.OWNER, v.currentMembers[OfficeSync.deviceId])+    }++    @Test+    fun `prepareShareTarget records index and starts live`() = runTest {+        val v = loadedVm("share me")+        v.currentRole = OfficeRoles.OWNER+        val strings = mutableMapOf<String, String?>()+        val ds = mockDs(strings)+        val key = ByteArray(32) { 3 }+        try {+            val ownerKeyB64 = v.prepareShareTarget(ds, "doc-share-1", key, "Shared Doc")+            assertEquals(Base64.encode(OfficeSync.publicBundle), ownerKeyB64)+            assertEquals("doc-share-1", v.currentDocId)+            assertTrue(v.isOnlineMutable.value)+            val index = v.loadIndex(ds)+            assertEquals(1, index.size)+            assertEquals("Shared Doc", index[0].title)+            assertTrue(index[0].owner)+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `pushShareInvite reports undeliverable invite offline`() = runTest {+        val v = loadedVm()+        v.currentRole = OfficeRoles.OWNER+        val key = ByteArray(32) { 5 }+        val err = v.pushShareInvite("doc-share-2", key, "T", "ghost-device", OfficeRoles.EDITOR, "ownerB64")+        assertNotNull(err)+        assertTrue(err.contains("deliver", ignoreCase = true), err)+    }++    // ---- SyncC: members / keys / titles ----++    @Test+    fun `fetchMembers and fetchTitle handle missing owner key and offline`() = runTest {+        val v = vm()+        val key = ByteArray(32)+        assertTrue(v.fetchMembers("d1", key, null).isEmpty())+        v.currentMembers["stale"] = OfficeRoles.EDITOR+        assertTrue(v.fetchMembers("d1", key, OfficeSync.publicBundle).isEmpty())+        assertTrue(v.currentMembers.isEmpty())+        assertNull(v.fetchTitle("d1", key, null))+        assertNull(v.fetchTitle("d1", key, OfficeSync.publicBundle))+    }++    @Test+    fun `fetchCurrentKey falls back to invite key offline`() = runTest {+        val v = vm()+        val invite = ByteArray(32) { 9 }+        val (epochNull, keyNull) = v.fetchCurrentKey("d1", invite, null)+        assertEquals(0, epochNull)+        assertTrue(invite.contentEquals(keyNull))+        val (epoch, key) = v.fetchCurrentKey("d1", invite, OfficeSync.publicBundle)+        assertEquals(0, epoch)+        assertTrue(invite.contentEquals(key))+    }++    @Test+    fun `fetchOwnerKey validates base key offline`() = runTest {+        val v = vm()+        assertNull(v.fetchOwnerKey("d1", ""))+        assertNull(v.fetchOwnerKey("d1", "!!!not-base64!!!"))+        val base = OfficeSync.publicBundle+        val resolved = v.fetchOwnerKey("d1", Base64.encode(base))+        assertNotNull(resolved)+        assertTrue(base.contentEquals(resolved))+    }++    @Test+    fun `signing bytes are deterministic and scoped`() = runTest {+        val v = vm()+        val m = OfficeMember("peer", "Ann", OfficeRoles.EDITOR)+        assertEquals("d1|peer|editor", v.memberSigningBytes("d1", m).decodeToString())+        assertEquals("d1|title|New", v.titleSigningBytes("d1", "New").decodeToString())+        assertEquals(+            "d1|owner|peer|a2V5", v.ownerSigningBytes("d1", "peer", "a2V5").decodeToString())+        val wraps = mapOf("b" to "2", "a" to "1")+        assertEquals(+            "d1|3|a=1|b=2", v.epochSigningBytes("d1", 3, wraps).decodeToString())+    }++    @Test+    fun `writeMembers signs and memberKey uses cache`() = runTest {+        val v = vm()+        v.currentRole = OfficeRoles.OWNER+        // No server: append fails silently inside runCatching, call completes.+        v.writeMembers("d1", ByteArray(32), listOf(OfficeMember("p1", "", OfficeRoles.VIEWER)))+        v.recordMembers("d1", ByteArray(32), listOf(OfficeMember("p2")))+        val bundle = OfficeSync.publicBundle+        v.memberKeyCache["cached-peer"] = bundle+        assertTrue(bundle.contentEquals(v.memberKey("cached-peer")!!))+        // Cache miss goes to the (unreachable) relay and yields null.+        assertNull(v.memberKey("no-such-device-slice3"))+    }++    @Test+    fun `rotateKey mints epoch and rebaselines tree`() = runTest {+        val v = loadedVm("rotate text")+        v.currentRole = OfficeRoles.OWNER+        v.currentEpoch = 0+        val oldKey = ByteArray(32) { 1 }+        v.currentDocKey = oldKey+        v.currentOwnerKey = OfficeSync.publicBundle+        val tree = DocumentTreeCrdt("dev-rotate")+        tree.updateJson(v.exportFlat())+        v.currentTree = tree+        try {+            v.rotateKey("doc-rotate")+            assertEquals(1, v.currentEpoch)+            assertNotNull(v.currentDocKey)+            assertFalse(oldKey.contentEquals(v.currentDocKey!!))+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `pollTitle ignores foreign docs and offline titles`() = runTest {+        val v = loadedVm()+        v.currentDocId = "mine"+        v.currentOwnerKey = OfficeSync.publicBundle+        // Foreign doc id: immediate return.+        v.pollTitle("other", ByteArray(32))+        // Own doc but no signed title on the (unreachable) relay: no change.+        v.pollTitle("mine", ByteArray(32))+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        assertEquals("Doc", doc.title)+    }++    // ---- SyncA: presence / live / local edits ----++    @Test+    fun `broadcastPresence and onLocalEdit schedule jobs for online doc`() = runTest {+        val v = loadedVm()+        v.currentDocId = "doc-live-1"+        v.currentDocKey = ByteArray(32) { 2 }+        v.currentRole = OfficeRoles.EDITOR+        v.setLocalCaret(4)+        assertNotNull(v.caretPresenceJob)+        v.onLocalEdit()+        assertNotNull(v.livePushJob)+        // While applying a remote merge, onLocalEdit is suppressed.+        v.applyingRemote = true+        val pushBefore = v.livePushJob+        v.onLocalEdit()+        assertEquals(pushBefore, v.livePushJob)+        v.applyingRemote = false+        stopJobs(v)+    }++    @Test+    fun `pushLiveOps and applyLiveActions merge signed peer ops`() = runTest {+        val v = loadedVm("base text")+        val key = ByteArray(32) { 11 }+        v.currentDocId = "doc-live-2"+        v.currentDocKey = key+        v.currentRole = OfficeRoles.EDITOR+        val tree = DocumentTreeCrdt("dev-live")+        v.currentTree = tree+        try {+            // Direct push: live socket is down, HTTP append fails offline, no throw.+            v.pushLiveOps("doc-live-2", key, "[]")+            // Actions path with no incoming blobs still folds local edits in.+            v.applyLiveActions(OfficeSync.LiveMsg(t = "actions", seq = 3), "doc-live-2", key)+            assertTrue(tree.render().contains("base text"), tree.render())+            assertEquals(3L, realDs().getLong("crdtCursor:doc-live-2") ?: -1L)+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `mergeLiveTree renders changed tree into editor`() = runTest {+        val v = loadedVm("before merge")+        val tree = DocumentTreeCrdt("dev-merge")+        v.currentTree = tree+        try {+            val other = loadedVm("after merge")+            tree.updateJson(other.exportFlat())+            v.mergeLiveTree("doc-merge-1", 7, tree, "stale-local-xml", v.editVersion)+            val doc = (v.state.value as OfficeViewModel.ViewState.Loaded)+                .document as OdfDocument.TextDocument+            val text = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+                .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }+            assertTrue(text.contains("after merge"), text)+            assertEquals(7L, realDs().getLong("crdtCursor:doc-merge-1") ?: -1L)+            // Identical render is a no-op for the editor.+            val stateBefore = v.state.value+            v.mergeLiveTree("doc-merge-1", 8, tree, tree.render(), v.editVersion)+            assertEquals(stateBefore, v.state.value)+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `startLive presence tick clears stale typing`() = runTest {+        val v = loadedVm("tick text")+        v.currentTree = DocumentTreeCrdt("dev-tick")+        val now = System.currentTimeMillis()+        v.remotePresenceMutable.value = listOf(+            OfficePresence("peer-tick", "Ann", typing = true, ts = now, typingTs = 0L))+        try {+            v.startLive("doc-tick", ByteArray(32) { 4 })+            assertTrue(+                await(12_000) { v.remotePresenceMutable.value.firstOrNull()?.typing == false },+                "presence tick should clear stale typing, was ${v.remotePresenceMutable.value}")+        } finally {+            stopJobs(v)+            v.currentTree?.close()+        }+    }++    // ---- Public launchers (IO coroutines, offline relay) ----++    @Test+    fun `requestToJoin and securityCode report failure offline`() {+        val v = vm()+        val joinLatch = CountDownLatch(1)+        var joinOk: Boolean? = null+        v.requestToJoin("doc-j", "owner-x") { joinOk = it; joinLatch.countDown() }+        assertTrue(joinLatch.await(10, TimeUnit.SECONDS), "join callback")+        assertEquals(false, joinOk)++        val codeLatch = CountDownLatch(1)+        var code: String? = "unset"+        v.securityCodeWith("no-such-peer") { code = it; codeLatch.countDown() }+        assertTrue(codeLatch.await(10, TimeUnit.SECONDS), "code callback")+        assertNull(code)+    }++    @Test+    fun `approve and deny join requests update pending list`() = runTest {+        val v = vm()+        val ds = realDs()+        v.saveIndex(ds, listOf(+            OfficeDocMeta(+                docId = "doc-appr", title = "Owned", keyB64 = Base64.encode(ByteArray(32)),+                owner = true)))+        v.saveRequests(ds, listOf(+            OfficeSync.JoinRequest(docId = "doc-appr", requesterId = "req-1"),+            OfficeSync.JoinRequest(docId = "doc-appr", requesterId = "req-2")))+        // Approve req-1: invite cannot be delivered offline, so result is+        // false and the request stays pending.+        val latch = CountDownLatch(1)+        var ok: Boolean? = null+        v.approveJoinRequest("doc-appr", "req-1") { ok = it; latch.countDown() }+        assertTrue(latch.await(10, TimeUnit.SECONDS), "approve callback")+        assertEquals(false, ok)+        // Deny req-2: removed locally without any grant.+        v.denyRequest("doc-appr", "req-2")+        assertTrue(await { v.pendingRequestsMutable.value.none { it.requesterId == "req-2" } })+        assertTrue(v.loadRequests(ds).any { it.requesterId == "req-1" })+        // Approving an unknown doc also reports false.+        val latch2 = CountDownLatch(1)+        var ok2: Boolean? = null+        v.approveJoinRequest("no-doc", "req-9") { ok2 = it; latch2.countDown() }+        assertTrue(latch2.await(10, TimeUnit.SECONDS))+        assertEquals(false, ok2)+    }++    @Test+    fun `documentMembers setMemberRole and transfer guards and owner paths`() {+        val v = loadedVm()+        // Guards: nothing open online.+        var guardMembers: List<OfficeMember>? = null+        v.documentMembers { guardMembers = it }+        assertEquals(emptyList(), guardMembers)+        var guardRole: Boolean? = null+        v.setMemberRole("p1", OfficeRoles.VIEWER) { guardRole = it }+        assertEquals(false, guardRole)+        var guardTransfer: Boolean? = null+        v.transferOwnership("p1") { guardTransfer = it }+        assertEquals(false, guardTransfer)++        // Owner paths against the offline relay.+        v.currentDocId = "doc-members"+        v.currentDocKey = ByteArray(32) { 6 }+        v.currentRole = OfficeRoles.OWNER+        v.currentOwnerKey = OfficeSync.publicBundle+        val memLatch = CountDownLatch(1)+        var members: List<OfficeMember>? = null+        v.documentMembers { members = it; memLatch.countDown() }+        assertTrue(memLatch.await(10, TimeUnit.SECONDS))+        assertEquals(emptyList(), members)++        var roleOk: Boolean? = null+        val roleLatch = CountDownLatch(1)+        v.setMemberRole("p1", OfficeRoles.VIEWER) { roleOk = it; roleLatch.countDown() }+        assertTrue(roleLatch.await(10, TimeUnit.SECONDS))+        assertEquals(true, roleOk)++        // Transfer to a cached member succeeds (records signed roster offline).+        v.memberKeyCache["new-owner"] = OfficeSync.publicBundle+        var transferOk: Boolean? = null+        val transferLatch = CountDownLatch(1)+        v.transferOwnership("new-owner") { transferOk = it; transferLatch.countDown() }+        assertTrue(transferLatch.await(10, TimeUnit.SECONDS))+        assertEquals(true, transferOk)+        assertEquals(OfficeRoles.EDITOR, v.currentRole)+        stopJobs(v)+    }++    @Test+    fun `renameDocument owner path updates title and index`() = runTest {+        val v = loadedVm()+        // Guards first.+        var guard: Boolean? = null+        v.renameDocument("X") { guard = it }+        assertEquals(false, guard)+        v.currentDocId = "doc-rename"+        v.currentDocKey = ByteArray(32) { 8 }+        v.currentRole = OfficeRoles.VIEWER+        var viewerGuard: Boolean? = null+        v.renameDocument("X") { viewerGuard = it }+        assertEquals(false, viewerGuard)++        v.currentRole = OfficeRoles.OWNER+        val ds = realDs()+        v.saveIndex(ds, listOf(+            OfficeDocMeta(docId = "doc-rename", title = "Old", keyB64 = "", owner = true)))+        val latch = CountDownLatch(1)+        var ok: Boolean? = null+        v.renameDocument("  Fresh Name  ") { ok = it; latch.countDown() }+        assertTrue(latch.await(10, TimeUnit.SECONDS), "rename callback")+        assertEquals(true, ok)+        assertTrue(await { v.onlineDocsMutable.value.firstOrNull()?.title == "Fresh Name" })+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        assertEquals("Fresh Name", doc.title)+        // Blank name is refused.+        var blank: Boolean? = null+        v.renameDocument("   ") { blank = it }+        assertEquals(false, blank)+    }++    @Test+    fun `shareCurrentDocument reports registration failure offline`() {+        val v = loadedVm()+        val latch = CountDownLatch(1)+        var err: String? = null+        var called = false+        v.shareCurrentDocument("recipient-x") { err = it; called = true; latch.countDown() }+        assertTrue(latch.await(10, TimeUnit.SECONDS), "share callback")+        assertTrue(called)+        assertNotNull(err)+        assertTrue(err!!.contains("register", ignoreCase = true), err!!)+    }++    @Test+    fun `openOnlineDocument with no readable content errors`() {+        val v = vm()+        val meta = OfficeDocMeta(+            docId = "doc-empty-online", title = "Empty",+            keyB64 = Base64.encode(ByteArray(32) { 12 }),+            owner = false, role = OfficeRoles.VIEWER, ownerKeyB64 = "")+        v.openOnlineDocument(meta)+        assertTrue(+            await(12_000) { v.state.value is OfficeViewModel.ViewState.Error },+            "state was ${v.state.value}")+        val msg = (v.state.value as OfficeViewModel.ViewState.Error).message+        assertTrue(msg.contains("no readable content"), msg)+        stopJobs(v)+    }++    @Test+    fun `syncCurrentDocument and refreshOnline run offline`() = runTest {+        val v = loadedVm("current sync")+        v.currentDocId = "doc-current"+        v.currentDocKey = ByteArray(32) { 13 }+        v.currentTree = DocumentTreeCrdt("dev-current")+        v.onlineEnabledMutable.value = true+        v.syncCurrentDocument()+        // syncDoc persists the tree + cursor as its offline completion signal.+        assertTrue(await(12_000) { realDs().getString("crdt:doc-current") != null })+        v.refreshOnline()+        assertTrue(await(12_000) { realDs().getLong("officeInboxCursor") != null })+        stopJobs(v)+    }++    @Test+    fun `presence and live-push jobs complete offline`() = runTest {+        val v = loadedVm("job text")+        v.currentDocId = "doc-jobs"+        v.currentDocKey = ByteArray(32) { 21 }+        v.currentRole = OfficeRoles.EDITOR+        v.currentTree = DocumentTreeCrdt("dev-jobs")+        v.setLocalCaret(2)+        // Joining (not sleeping) waits for the debounced presence send, which+        // is a no-op without a live socket.+        v.caretPresenceJob?.join()+        v.onLocalEdit()+        // The live-push job syncs via the unreachable relay and completes.+        v.livePushJob?.join()+        assertTrue(realDs().getString("crdt:doc-jobs") != null)+        stopJobs(v)+    }++    @Test+    fun `openOnlineDocument with seeded tree loads document`() = runTest {+        val seed = loadedVm("seeded online text")+        val tree = DocumentTreeCrdt("dev-seed")+        tree.updateJson(seed.exportFlat())+        val ds = realDs()+        ds.setString("crdt:doc-seeded", tree.serialize())+        tree.close()+        assertTrue(await { ds.getString("crdt:doc-seeded") != null })+        val v = vm()+        val meta = OfficeDocMeta(+            docId = "doc-seeded", title = "Seeded",+            keyB64 = Base64.encode(ByteArray(32) { 22 }),+            owner = false, role = OfficeRoles.EDITOR, ownerKeyB64 = "")+        v.openOnlineDocument(meta)+        assertTrue(+            await(15_000) { v.state.value is OfficeViewModel.ViewState.Loaded },+            "state was ${v.state.value}")+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        val text = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }+        assertTrue(text.contains("seeded online text"), text)+        assertEquals("doc-seeded", v.currentDocId)+        assertNotNull(v.currentTree)+        stopJobs(v)+    }++    @Test+    fun `initSync loads local index when identity exists`() = runTest {+        val v = vm()+        val ds = realDs()+        // Provision identity keys in the real store so hasOnlineIdentity passes.+        ds.setByteArray("officeKemPub", byteArrayOf(1))+        ds.setByteArray("officeDsaPub", byteArrayOf(2))+        ds.setString("officeDeviceId", "slice3-device")+        val metas = listOf(+            OfficeDocMeta(docId = "doc-init", title = "Indexed", keyB64 = "", owner = false))+        v.saveIndex(ds, metas)+        // The store's sync getters read the eager snapshot; wait for hydration.+        assertTrue(await { v.hasOnlineIdentity() }, "identity should hydrate")+        v.initSync()+        assertTrue(await(12_000) { v.onlineDocsMutable.value == metas },+            "onlineDocs=${v.onlineDocsMutable.value}")+        assertTrue(v.onlineEnabledMutable.value)+        stopJobs(v)+    }+}
office/src/test/java/com/vayunmathur/office/util/OfficeViewModelTextSlice3Test.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelTextSlice3Test.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelTextSlice3Test.ktnew file mode 100644index 0000000000..d1c4ac6749--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeViewModelTextSlice3Test.kt@@ -0,0 +1,353 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest++/**+ * Slice 3/4: text-document editing ops on [OfficeViewModel] โ€” paragraph CRUD, span+ * formatting, list handling, find/replace, links, fields, comments and tables.+ */+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi

Diff truncated.