Modern Apps git

← Modern-Apps.git

everysync: add pass-3 tests for relay, merge, snapshots and UI

Commit
0809c0b730459b5c5d1c13dda9585f314c79e64b
Author
Vayun Mathur <[email protected]>
When
2026-11-07 12:22 UTC (29 days ago)
Parents
fff90b8
Coverage 56.8% -> 88.2% merged INSTRUCTION (21782/38496 ->
33962/38496). 42 new tests in 12 files, all against an
in-memory FakeRelay (RelaySync.transportForTest seam) and fake
IPC/system ContentProviders (FakeIpcProvider): no test touches
the network or the AndroidKeyStore, so the suite is valid on
the CI box which has internet.

- RelaySuccessTest: record/inbox round trips, undecryptable
  logs, roster last-wins + forged envelopes, key epoch
  rotation/revocation, ownership chain, blob push/pull/delete.
- E2eeDriveTest: full notes/passwords/todos merge cycles
  (push, remote edit, tombstone, PULL/PUSH direction rules,
  relay-down abort), relay stores, snapshot take/restore/prune,
  key wrapping via the keystore seams.
- SystemVaultDriveTest: contacts/calendar vault cycles with
  stamped write-back, vault auto-creation on first sync,
  purgeType per type, snapshots+restore for every type
  (incl. note blobs).
- VaultsFlowTest/VaultJoinTest: create/invite/join/approve/
  deny, safety codes, joined-vault adoption with signed title
  (forgery rejected) via EverySyncViewModel.
- ViewModel2Test: sync-error code mapping, toggle-type
  snapshot+purge, snapshot restore.
- AppEntryTest: MainActivity (plain + join link + warm start),
  Navigation, SyncEngine outcomes, SyncWorker/SnapshotWorker
  via TestListenableWorkerBuilder (new testImplementation on
  the existing androidx.work.testing catalog entry), scheduler,
  BootReceiver, Authenticator, Route serialization.
- UiScreens2Test/BinderScreensTest: stateless and
  ViewModel-bound Accounts/AddAccount/AccountDetail/Settings/
  VaultSharing screens with recording actions.
- Formats2Test/Sinks2Test: ICalendar TZID/folding/defaults,
  VCard structured names, todo/note sink feeds, keystore
  fail-closed branches.

Seams are in their own commit; two real bugs found by these
tests (join-request discriminator, relay-log fold) are fixed
in their own commits. Verified: gslot
./gradlew :everysync:createMergedCoverageReport BUILD
SUCCESSFUL (full suite green), :everysync:lint passes.
Untestable remainder: RelaySync.startLive WebSocket (needs a
live socket; tests must not touch the network) and the
AndroidKeyStore branches of TokenStore/VaultKeyStore/
SnapshotKeyStore.secretKey (Robolectric has no KeyStore;
covered via the software-key seams instead).

(cherry picked from commit f076441a88ae6a2b588a806c08cb27d7321fb8b5)

Diff

everysync/build.gradle.kts
diff --git a/everysync/build.gradle.kts b/everysync/build.gradle.ktsindex 018239a18b..327ceef714 100644--- a/everysync/build.gradle.kts+++ b/everysync/build.gradle.kts@@ -26,4 +26,6 @@ dependencies {     // End-to-end encryption for personal relay vaults (PQC identity + AES content keys)     implementation(project(":library:e2ee-p2p")) +    // Worker construction in unit tests (TestListenableWorkerBuilder)+    testImplementation(libs.androidx.work.testing) }
everysync/src/test/java/com/vayunmathur/everysync/AppEntryTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/AppEntryTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/AppEntryTest.ktnew file mode 100644index 0000000000..470091bf2e--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/AppEntryTest.kt@@ -0,0 +1,170 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.compose.ui.test.ExperimentalTestApi+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.work.Data+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.platform.BootReceiver+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.sync.SnapshotWorker+import com.vayunmathur.everysync.sync.SyncEngine+import com.vayunmathur.everysync.sync.SyncScheduler+import com.vayunmathur.everysync.sync.SyncWorker+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.serialization.json.Json+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/** App entry points: MainActivity/Navigation, sync engine, workers, boot, routes. */+@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class AppEntryTest {+    @get:Rule val rule = createComposeRule()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        try {+            androidx.work.WorkManager.initialize(ctx, androidx.work.Configuration.Builder().build())+        } catch (_: IllegalStateException) { /* already initialised */ }+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); relay.uninstall() }++    @Test fun authenticatorIsAllNoOps() {+        val auth = com.vayunmathur.everysync.auth.Authenticator(ctx)+        val account = android.accounts.Account("alice", "com.vayunmathur.everysync")+        assertEquals(null, auth.editProperties(null, "t"))+        assertEquals(null, auth.addAccount(null, "t", "tok", null, null))+        assertEquals(null, auth.confirmCredentials(null, account, null))+        assertEquals(null, auth.getAuthToken(null, account, "tok", null))+        assertEquals(null, auth.getAuthTokenLabel("tok"))+        assertEquals(null, auth.updateCredentials(null, account, "tok", null))+        assertEquals(null, auth.hasFeatures(null, account, arrayOf("f")))+        val service = com.vayunmathur.everysync.auth.AuthenticatorService()+        assertNotNull(service)+        // Provider metadata is stable+        val provider = com.vayunmathur.everysync.provider.ProviderRegistry.get("e2ee")+        assertEquals("e2ee", provider?.id)+        assertEquals(com.vayunmathur.everysync.provider.AuthType.RELAY, provider?.authType)+    }++    @Test fun routesRoundTripThroughSerialization() {+        val routes: List<Route> = listOf(Route.Accounts, Route.AddAccount, Route.AccountDetail("alice"), Route.Settings)+        for (route in routes) {+            val encoded = Json.encodeToString(Route.serializer(), route)+            assertEquals(route, Json.decodeFromString(Route.serializer(), encoded), encoded)+        }+        assertEquals("alice", (Json.decodeFromString(Route.serializer(), Json.encodeToString(Route.serializer(), Route.AccountDetail("alice"))) as Route.AccountDetail).accountName)+    }++    @Test fun syncEngineRecordsSuccessAndSkipsUnknown() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val store = AccountStore.getInstance(ctx)+        store.upsert(AccountConfig("eng-acc", "e2ee", emptySet()))+        // Enabled types empty: provider syncs nothing and succeeds+        SyncEngine.syncAccount(ctx, "eng-acc")+        val after = store.get("eng-acc")+        assertNotNull(after?.lastSyncEpochMs?.takeIf { it > 0 })+        assertEquals(null, after?.lastSyncError)+        // Unknown account and unknown provider return quietly+        SyncEngine.syncAccount(ctx, "ghost")+        store.upsert(AccountConfig("bad-provider", "nope", emptySet()))+        SyncEngine.syncAccount(ctx, "bad-provider")+        SyncEngine.syncAll(ctx)+        // A notes-enabled account goes through the real provider against the fake relay+        store.upsert(AccountConfig("eng-notes", "e2ee", setOf(DataType.NOTES)))+        SyncEngine.syncAccount(ctx, "eng-notes")+        assertEquals(null, store.get("eng-notes")?.lastSyncError)+    } }++    @Test fun workersAndSchedulerAndBoot() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val store = AccountStore.getInstance(ctx)+        store.upsert(AccountConfig("worker-acc", "e2ee", emptySet()))+        val allWorker = TestListenableWorkerBuilder<SyncWorker>(ctx).build()+        assertEquals(androidx.work.ListenableWorker.Result.success(), allWorker.startWork().get())+        val oneWorker = TestListenableWorkerBuilder<SyncWorker>(ctx)+            .setInputData(Data.Builder().putString(SyncWorker.KEY_ACCOUNT, "worker-acc").build())+            .build()+        assertEquals(androidx.work.ListenableWorker.Result.success(), oneWorker.startWork().get())+        val snapshotWorker = TestListenableWorkerBuilder<SnapshotWorker>(ctx).build()+        assertEquals(androidx.work.ListenableWorker.Result.success(), snapshotWorker.startWork().get())+        // Scheduler enqueues without crashing (WorkManager initialised above)+        SyncScheduler.schedulePeriodic(ctx)+        SyncScheduler.syncNow(ctx, "worker-acc")+        SyncScheduler.syncAllNow(ctx)+        SnapshotWorker.scheduleDaily(ctx)+        SnapshotWorker.cancel(ctx)+        SnapshotWorker.scheduleDaily(ctx)+        // Boot receiver reschedules on boot / update, ignores other actions+        val receiver = BootReceiver()+        receiver.onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED))+        receiver.onReceive(ctx, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))+        receiver.onReceive(ctx, Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED))+        Unit+    } }++    @Test fun navigationShowsAccountsAndRoutes() {+        org.robolectric.Shadows.shadowOf(ctx as Application).grantPermissions(+            android.Manifest.permission.READ_CONTACTS, android.Manifest.permission.WRITE_CONTACTS,+            android.Manifest.permission.READ_CALENDAR, android.Manifest.permission.WRITE_CALENDAR,+        )+        val store = AccountStore.getInstance(ctx)+        runBlocking { store.upsert(AccountConfig("nav-acc", "e2ee", setOf(DataType.NOTES))) }+        val vm = com.vayunmathur.everysync.platform.EverySyncViewModel(ctx as Application)+        rule.setContent { Navigation(vm) }+        rule.waitForIdle()+        rule.onNodeWithText("nav-acc").assertExists()+    }++    @Test fun mainActivityPlainAndJoinLink() {+        // Plain launch shows the accounts content+        val controller = Robolectric.buildActivity(MainActivity::class.java).setup()+        controller.pause().stop().destroy()+        // Join link launch fires the sealed join request path (fake relay answers)+        runBlocking { assertTrue(RelaySync.init(ctx)) }+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("everysync://join/v-join-1?owner=${RelaySync.deviceId}&type=notes"))+        val c2 = Robolectric.buildActivity(MainActivity::class.java, intent).setup()+        val activity = c2.get()+        // Warm-start a second join link through onNewIntent+        val intent2 = Intent(Intent.ACTION_VIEW, Uri.parse("everysync://join/v-join-2?owner=${RelaySync.deviceId}&type=todos"))+        c2.newIntent(intent2)+        // Non-join intents are ignored by the parser+        c2.newIntent(Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/other")))+        c2.pause().stop().destroy()+        // The application class boots (scheduling + migration) via a fresh instance+        val freshApp = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()+            .newApplication(EverySyncApplication::class.java.classLoader, EverySyncApplication::class.java.name, ctx) as EverySyncApplication+        freshApp.onCreate()+        assertNotNull(freshApp)+    }+}
everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.ktnew file mode 100644index 0000000000..47d85e8363--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/E2eeDriveTest.kt@@ -0,0 +1,254 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.data.RemoteTodoList+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.readKey+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.data.sink.TodoListIpcSink+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.impl.E2eeProvider+import com.vayunmathur.everysync.sync.NoteRelayStore+import com.vayunmathur.everysync.sync.PasswordRelayStore+import com.vayunmathur.everysync.sync.RelaySnapshot+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import com.vayunmathur.everysync.sync.SnapshotStore+import com.vayunmathur.everysync.sync.TodoListRelayStore+import com.vayunmathur.everysync.sync.TodoRelayStore+import com.vayunmathur.everysync.sync.adapters.NoteKind+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.assertFalse++/**+ * Full merge cycles (E2eeProvider.driveMerge) and the store/snapshot layers+ * against the fake relay and fake IPC providers. No network, no AndroidKeyStore.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class E2eeDriveTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(ctx).secretKeyForTest = softwareKey+    }++    private suspend fun makeVault(type: String, vaultId: String): Pair<VaultMeta, ByteArray> {+        val key = RelaySync.newVaultKey()+        val meta = VaultMeta(+            vaultId = vaultId, dataType = type, title = "T-$type",+            keyB64 = Base64.encode(key), ownerDeviceId = RelaySync.deviceId,+            ownerKeyB64 = Base64.encode(RelaySync.publicBundle), isOwner = true,+        )+        VaultStore.upsert(ctx, meta)+        com.vayunmathur.everysync.provider.SyncState.set(ctx, ACCOUNT, "e2ee_vault_$type", vaultId)+        return VaultStore.get(ctx, vaultId)!! to key+    }++    private fun config(vararg types: DataType) = AccountConfig(ACCOUNT, "e2ee", types.toSet())++    @Test fun keyWrappingRoundTrips() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, key) = makeVault("notes", "v-keywrap")+        // Stored value is sealed, the read key is the original vault key+        assertTrue(com.vayunmathur.everysync.data.VaultKeyStore.looksSealed(meta.keyB64), meta.keyB64.take(8))+        assertTrue(meta.readKey(ctx)!!.contentEquals(key))+        // TokenStore sync keys round-trip and clear+        val tokens = TokenStore.getInstance(ctx)+        tokens.putSyncKey(ACCOUNT, "notes", "sekrit")+        assertEquals("sekrit", tokens.getSyncKey(ACCOUNT, "notes"))+        assertNull(tokens.getSyncKey(ACCOUNT, "todos"))+        tokens.clear(ACCOUNT)+        // SnapshotKeyStore seal/unseal+        val sealed = SnapshotKeyStore.seal(ctx, "payload".encodeToByteArray())+        assertNotNull(sealed)+        assertEquals("payload", SnapshotKeyStore.unseal(ctx, sealed)?.decodeToString())+        assertNull(SnapshotKeyStore.unseal(ctx, byteArrayOf(1, 2, 3)))+    } }++    @Test fun notesVaultFullCycle() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, key) = makeVault("notes", "v-notes1")+        val provider = E2eeProvider()+        val channel = RelaySync.recordChannel("notes", meta.vaultId)+        // Empty vault syncs cleanly in every direction+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH)+        assertTrue(relay.channel(channel).isEmpty())+        // Local note is pushed encrypted+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "n1", title = "First", content = "body", updatedAt = 1_000))+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH)+        assertEquals(1, relay.channel(channel).size)+        val pulled = RelaySync.pullRecords(channel, key, 0)+        assertEquals("n1", NoteKind.fromJson(pulled!!.items.single())?.uid)+        // Second cycle is a no-op (baseline clean)+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH)+        assertEquals(1, relay.channel(channel).size)+        // Remote edit wins locally+        RelaySync.appendRecords(channel, key, listOf(NoteKind.toJson(RemoteNote(uid = "n1", title = "Edited remotely", content = "body", updatedAt = 2_000))))+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH)+        assertEquals("Edited remotely", NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "n1" }.title)+        // Remote tombstone soft-deletes locally+        RelaySync.appendRecords(channel, key, listOf(NoteKind.toJson(RemoteNote(uid = "n1", title = "Edited remotely", deleted = true, updatedAt = 3_000))))+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH)+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).single { it.uid == "n1" }.deleted)+        // PULL never appends: a fresh local note stays off the relay+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "n2", title = "Local only", updatedAt = 4_000))+        val before = relay.channel(channel).size+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.PULL)+        assertEquals(before, relay.channel(channel).size)+        // PUSH appends local edits but does not apply remote state+        RelaySync.appendRecords(channel, key, listOf(NoteKind.toJson(RemoteNote(uid = "n3", title = "Remote only", updatedAt = 5_000))))+        provider.sync(ctx, config(DataType.NOTES), SyncDirection.PUSH)+        assertTrue(relay.channel(channel).size > before)+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).none { it.uid == "n3" })+        // Relay down: sync surfaces the relay-unavailable abort, state untouched+        relay.transportDown = true+        // init is already done, so the abort comes from the pull instead+        val ex = runCatching { provider.sync(ctx, config(DataType.NOTES), SyncDirection.BOTH) }.exceptionOrNull()+        assertTrue(ex is com.vayunmathur.everysync.provider.impl.VaultSyncAbort, "$ex")+        relay.transportDown = false+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).any { it.uid == "n2" })+    } }++    @Test fun passwordsVaultHardDeleteCycle() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, key) = makeVault("passwords", "v-pass1")+        val provider = E2eeProvider()+        val channel = RelaySync.recordChannel("passwords", meta.vaultId)+        PasswordSink.upsert(ctx, meta.vaultId, RemotePassword(uid = "p1", name = "Mail", username = "alice", password = "s3cret", updatedAt = 1_000))+        PasswordSink.upsert(ctx, meta.vaultId, RemotePassword(uid = "k1", isPasskey = true, rpId = "example.com", credentialId = "cred1", updatedAt = 1_000))+        provider.sync(ctx, config(DataType.PASSWORDS), SyncDirection.BOTH)+        assertEquals(2, relay.channel(channel).size)+        assertEquals(2, PasswordSink.listLocalOrThrow(ctx, meta.vaultId).size)+        // Hard delete locally propagates a tombstone to the relay+        PasswordSink.delete(ctx, meta.vaultId, "p1")+        provider.sync(ctx, config(DataType.PASSWORDS), SyncDirection.BOTH)+        val items = RelaySync.pullRecords(channel, key, 0)!!.items+            .mapNotNull { com.vayunmathur.everysync.sync.adapters.PasswordKind.fromJson(it) }+        assertTrue(items.any { it.uid == "p1" && it.deleted }, items.toString())+        assertTrue(PasswordSink.listLocalOrThrow(ctx, meta.vaultId).none { it.uid == "p1" })+        assertTrue(PasswordSink.listLocalOrThrow(ctx, meta.vaultId).any { it.uid == "k1" })+    } }++    @Test fun todosVaultAndListsCycle() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, key) = makeVault("todos", "v-todo1")+        val provider = E2eeProvider()+        TodoIpcSink.upsert(ctx, meta.vaultId, RemoteTodo(uid = "t1", title = "Buy milk", dueAt = 123L, updatedAt = 1_000))+        TodoListIpcSink.upsertAll(ctx, meta.vaultId, listOf(RemoteTodoList(uid = "l1", name = "Home", updatedAt = 1_000)))+        provider.sync(ctx, config(DataType.TODOS), SyncDirection.BOTH)+        assertEquals(1, relay.channel(RelaySync.recordChannel("todos", meta.vaultId)).size)+        assertEquals(1, relay.channel(RelaySync.recordChannel("todolists", meta.vaultId)).size)+        assertTrue(TodoListIpcSink.isSupported(ctx, meta.vaultId))+        // Remote todo arrives locally+        RelaySync.appendRecords(+            RelaySync.recordChannel("todos", meta.vaultId), key,+            listOf(com.vayunmathur.everysync.sync.adapters.TodoKind.toJson(RemoteTodo(uid = "t2", title = "From peer", updatedAt = 2_000))),+        )+        provider.sync(ctx, config(DataType.TODOS), SyncDirection.BOTH)+        assertTrue(TodoIpcSink.listLocal(ctx, meta.vaultId).any { it.uid == "t2" && it.title == "From peer" })+    } }++    @Test fun relayStoresDirectly() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, _) = makeVault("notes", "v-store1")+        val store = NoteRelayStore(ctx, meta.vaultId)+        assertNull(store.parseRemote("not json"))+        assertNull(store.parseRemote(NoteKind.toJson(RemoteNote(uid = "", title = "blank"))))+        val note = RemoteNote(uid = "s1", title = "Stored", updatedAt = 7)+        assertEquals(note, store.parseRemote(store.serializeForRemote(note)))+        store.upsertLocal(listOf(note))+        assertEquals(listOf(note), store.listLocal())+        assertTrue(store.listLocalOk)+        store.saveSnapshots(listOf(RelaySnapshot("s1", "note", "hash", 7, 7, 1)))+        assertEquals("hash", store.loadBaseline()["s1"]?.contentHash)+        store.removeSnapshots(listOf("s1"))+        // DataStoreUtils sync reads lag the suspend edit briefly under load+        val deadline = System.currentTimeMillis() + 10_000+        while (store.loadBaseline().isNotEmpty() && System.currentTimeMillis() < deadline) Thread.sleep(25)+        assertTrue(store.loadBaseline().isEmpty())+        store.deleteLocal(listOf(note))+        assertTrue(store.listLocal().single().deleted)++        val passStore = PasswordRelayStore(ctx, meta.vaultId)+        val pw = RemotePassword(uid = "pw1", name = "Bank", updatedAt = 3)+        passStore.upsertLocal(listOf(pw))+        assertEquals(listOf(pw), passStore.listLocal())+        passStore.deleteLocal(listOf(pw))+        assertTrue(passStore.listLocal().isEmpty())++        val todoStore = TodoRelayStore(ctx, meta.vaultId)+        val todo = RemoteTodo(uid = "td1", title = "Task", updatedAt = 3)+        todoStore.upsertLocal(listOf(todo))+        assertEquals(listOf(todo), todoStore.listLocal())+        todoStore.deleteLocal(listOf(todo))+        assertTrue(todoStore.listLocal().single().deleted)++        val listStore = TodoListRelayStore(ctx, meta.vaultId)+        val list = RemoteTodoList(uid = "tl1", name = "Work", updatedAt = 3)+        listStore.upsertLocal(listOf(list))+        assertEquals(listOf(list), listStore.listLocal())+        assertEquals(list, listStore.parseRemote(listStore.serializeForRemote(list)))+    } }++    @Test fun snapshotTakeRestoreAndPrune() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (meta, _) = makeVault("notes", "v-snap1")+        NoteSink.upsert(ctx, meta.vaultId, RemoteNote(uid = "sn1", title = "Snap me", updatedAt = 10))+        assertFalse(SnapshotStore.takenToday(ctx, meta.vaultId))+        assertTrue(SnapshotStore.snapshotVault(ctx, meta.vaultId, "notes"))+        assertTrue(SnapshotStore.takenToday(ctx, meta.vaultId))+        val all = SnapshotStore.listAll(ctx)+        val mine = all.first { it.vaultId == meta.vaultId }+        assertEquals(1, mine.recordCount)+        assertEquals(listOf(mine), SnapshotStore.listForVault(ctx, meta.vaultId))+        // Same-day snapshotAll is a no-op for this vault+        SnapshotStore.snapshotAll(ctx)+        assertEquals(1, SnapshotStore.listForVault(ctx, meta.vaultId).size)+        // Purge local state, then restore brings the record back+        NoteSink.purge(ctx, ACCOUNT, meta.vaultId)+        assertTrue(NoteSink.listLocal(ctx, meta.vaultId).isEmpty())+        assertEquals(1, SnapshotStore.restore(ctx, mine))+        assertEquals("Snap me", NoteSink.listLocal(ctx, meta.vaultId).single().title)+        // Restoring a snapshot whose file is gone fails closed+        assertNull(SnapshotStore.restore(ctx, SnapshotStore.SnapshotMeta("ghost", "notes", 86_400_000L, 1)))+        // Unknown type cannot snapshot+        assertFalse(SnapshotStore.snapshotVault(ctx, meta.vaultId, "bogus-type"))+        // An old snapshot is pruned by age+        val oldDay = System.currentTimeMillis() - 40L * 24 * 60 * 60 * 1000+        assertTrue(SnapshotStore.snapshotVault(ctx, meta.vaultId, "notes", nowMs = oldDay))+        assertEquals(2, SnapshotStore.listForVault(ctx, meta.vaultId).size)+        SnapshotStore.pruneExpired(ctx)+        assertEquals(1, SnapshotStore.listForVault(ctx, meta.vaultId).size)+    } }++    private companion object { const val ACCOUNT = "alice" }+}
everysync/src/test/java/com/vayunmathur/everysync/FakeIpcProvider.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/FakeIpcProvider.kt b/everysync/src/test/java/com/vayunmathur/everysync/FakeIpcProvider.ktnew file mode 100644index 0000000000..c202c794cb--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/FakeIpcProvider.kt@@ -0,0 +1,137 @@+package com.vayunmathur.everysync++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull+import kotlinx.serialization.json.put+import org.robolectric.shadows.ShadowContentResolver++/**+ * In-memory ContentProvider standing in for the sibling apps' relay+ * providers (notes/passwords/todo). Implements exactly the contract the+ * everysync IPC sinks use: rows are envelope JSON in `payloadJson`, keyed by+ * the envelope's `uid`; base-table queries list full state (tombstones+ * included), `querySince` filters by `updatedAt`, a `syncId = ?` delete+ * tombstones one row, and `deleteByVault` purges the table.+ *+ * One instance backs every table under its authority; tables are keyed by+ * the URI's last-but-one path segment shape (`vault/<id>/<table>`).+ */+class FakeIpcProvider : ContentProvider() {+    data class Row(var syncId: String, var updatedAt: Long, var deleted: Boolean, var payloadJson: String)++    val tables = linkedMapOf<String, LinkedHashMap<String, Row>>()++    override fun onCreate(): Boolean = true++    private fun table(uri: Uri): LinkedHashMap<String, Row> {+        val key = uri.pathSegments.dropLastWhile { it in OPS }.joinToString("/")+        return tables.getOrPut(key) { linkedMapOf() }+    }++    private fun parseRow(payload: String): Row? {+        val obj = runCatching { Json.parseToJsonElement(payload).jsonObject }.getOrNull() ?: return null+        val uid = runCatching { obj["uid"]?.jsonPrimitive?.content }.getOrNull()?.takeIf { it.isNotBlank() } ?: return null+        return Row(+            syncId = uid,+            updatedAt = obj["updatedAt"]?.jsonPrimitive?.longOrNull ?: 0L,+            deleted = obj["deleted"]?.jsonPrimitive?.booleanOrNull ?: false,+            payloadJson = payload,+        )+    }++    override fun query(+        uri: Uri, projection: Array<out String>?, selection: String?,+        selectionArgs: Array<out String>?, sortOrder: String?,+    ): Cursor {+        val cols = projection?.toList() ?: listOf(COL_PAYLOAD)+        var rows = table(uri).values.toList()+        val since = uri.getQueryParameter("since")?.toLongOrNull()+        if (since != null) rows = rows.filter { it.updatedAt > since }+        if (selection?.contains("deleted = 0") == true) rows = rows.filter { !it.deleted }+        if (selection?.contains("syncId = ?") == true && !selectionArgs.isNullOrEmpty()) {+            rows = rows.filter { it.syncId == selectionArgs[0] }+        }+        val cursor = MatrixCursor(cols.toTypedArray())+        for (row in rows) {+            cursor.addRow(cols.map { col ->+                val value: Any? = when (col) {+                    COL_SYNC_ID -> row.syncId+                    COL_UPDATED_AT -> row.updatedAt+                    COL_DELETED -> if (row.deleted) 1 else 0+                    COL_PAYLOAD -> row.payloadJson+                    COL_HASH -> "hash"+                    else -> null+                }+                value+            }.toTypedArray())+        }+        return cursor+    }++    override fun insert(uri: Uri, values: ContentValues?): Uri {+        val payload = values?.getAsString(COL_PAYLOAD) ?: return uri+        val row = parseRow(payload) ?: return uri+        table(uri)[row.syncId] = row+        return uri+    }++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {+        val table = table(uri)+        if (uri.lastPathSegment == OP_PURGE || selection == null && uri.pathSegments.lastOrNull() in OPS) {+            val n = table.size; table.clear(); return n+        }+        val id = selectionArgs?.firstOrNull() ?: return 0+        // Passwords hard-delete locally; notes/todos soft-delete (tombstone).+        if (uri.authority == "com.vayunmathur.passwords.relay") {+            return if (table.remove(id) != null) 1 else 0+        }+        val row = table[id] ?: return 0+        // Soft-delete: tombstone the row and flip its envelope's deleted flag+        row.deleted = true+        row.payloadJson = runCatching {+            val obj = Json.parseToJsonElement(row.payloadJson).jsonObject+            buildJsonObject {+                for ((k, v) in obj) put(k, v)+                put("deleted", JsonPrimitive(true))+            }.toString()+        }.getOrDefault(row.payloadJson)+        return 1+    }++    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {+        insert(uri, values); return 1+    }++    override fun getType(uri: Uri): String = "vnd.android.cursor.dir/vnd.fake.relay"++    companion object {+        private const val COL_SYNC_ID = "syncId"+        private const val COL_UPDATED_AT = "updatedAt"+        private const val COL_DELETED = "deleted"+        private const val COL_PAYLOAD = "payloadJson"+        private const val COL_HASH = "contentHash"+        private const val OP_PURGE = "deleteByVault"+        private val OPS = setOf("querySince", "upsertRaw", "deleteByVault")++        /** Registers one fake provider per authority (idempotent per authority). */+        fun install(vararg authorities: String): Map<String, FakeIpcProvider> {+            val out = mutableMapOf<String, FakeIpcProvider>()+            for (authority in authorities) {+                val provider = FakeIpcProvider()+                ShadowContentResolver.registerProviderInternal(authority, provider)+                out[authority] = provider+            }+            return out+        }+    }+}
everysync/src/test/java/com/vayunmathur/everysync/Sinks2Test.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/Sinks2Test.kt b/everysync/src/test/java/com/vayunmathur/everysync/Sinks2Test.ktnew file mode 100644index 0000000000..3136a4af23--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/Sinks2Test.kt@@ -0,0 +1,116 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.data.RemoteTodo+import com.vayunmathur.everysync.data.VaultKeyStore+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.readKey+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** IPC sink operations the merge does not exercise directly, and keystore failure branches. */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class Sinks2Test {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @BeforeTest fun setUp() {+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 17 + 9).toByte() }, "AES")+        VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+    }++    @Test fun todoSinkOperations() {+        val v = "v-sink-todo"+        TodoIpcSink.upsert(ctx, v, RemoteTodo(uid = "a", title = "A", updatedAt = 100))+        TodoIpcSink.upsert(ctx, v, RemoteTodo(uid = "b", title = "B", updatedAt = 200))+        TodoIpcSink.upsert(ctx, v, RemoteTodo(uid = "c", title = "C", updatedAt = 300))+        assertEquals(3, TodoIpcSink.listLocal(ctx, v).size)+        assertTrue(TodoIpcSink.lastListLocalOk)+        // etag map + since-deltas+        assertEquals(mapOf("a" to 100L, "b" to 200L, "c" to 300L), TodoIpcSink.localUidToEtag(ctx, v))+        val changes = TodoIpcSink.getLocalChanges(ctx, v, since = 150)+        assertEquals(setOf("b", "c"), changes.map { it.syncId }.toSet())+        assertTrue(changes.all { !it.deleted && it.todo != null })+        // upsert replaces by uid+        TodoIpcSink.upsert(ctx, v, RemoteTodo(uid = "a", title = "A2", updatedAt = 400))+        assertEquals("A2", TodoIpcSink.listLocal(ctx, v).first { it.uid == "a" }.title)+        // delete tombstones; the change feed reports it deleted with no body+        TodoIpcSink.delete(ctx, v, "b")+        val afterDelete = TodoIpcSink.getLocalChanges(ctx, v, since = 0)+        assertTrue(afterDelete.first { it.syncId == "b" }.deleted)+        assertNull(afterDelete.first { it.syncId == "b" }.todo)+        assertEquals(3, TodoIpcSink.listLocal(ctx, v).size)+        // purge empties the vault table+        TodoIpcSink.purge(ctx, "acc", v)+        assertTrue(TodoIpcSink.listLocal(ctx, v).isEmpty())+        // JSON conversion paths+        val todo = RemoteTodo(uid = "j1", title = "Json", notes = "n", done = true, priority = 2, tags = listOf("x"))+        assertEquals(todo, TodoIpcSink.fromRelayJson(TodoIpcSink.toRelayJson(todo)))+        assertNull(TodoIpcSink.fromRelayJson("not json"))+        assertTrue(TodoIpcSink.todosUri(v).toString().contains(v))+    }++    @Test fun noteSinkOperations() {+        val v = "v-sink-note"+        NoteSink.upsertAll(ctx, v, listOf(+            RemoteNote(uid = "n1", title = "One", updatedAt = 10),+            RemoteNote(uid = "n2", title = "Two", updatedAt = 20),+        ))+        assertEquals(2, NoteSink.listLocal(ctx, v).size)+        assertEquals(mapOf("n1" to 10L, "n2" to 20L), NoteSink.localUidToEtag(ctx, v))+        val changes = NoteSink.getLocalChanges(ctx, v, since = 15)+        assertEquals(listOf("n2"), changes.map { it.syncId })+        NoteSink.deleteAll(ctx, v, listOf("n1"))+        assertTrue(NoteSink.listLocal(ctx, v).first { it.uid == "n1" }.deleted)+        assertTrue(NoteSink.getLocalChanges(ctx, v).first { it.syncId == "n1" }.deleted)+        NoteSink.purge(ctx, "acc", v)+        assertTrue(NoteSink.listLocal(ctx, v).isEmpty())+        NoteSink.purge(ctx, v) // back-compat overload (vault id as account)+        // Conversion helpers: native fallback, relay first, corrupt skipped+        val note = RemoteNote(uid = "nx", title = "T", content = "C", position = 1.5, updatedAt = 9)+        assertEquals(note, NoteSink.fromPayload(NoteSink.toRelayJson(note)))+        assertEquals(note, NoteSink.fromPayload(NoteSink.toNativeJson(note)))+        assertEquals(note, NoteSink.fromNativeJson(NoteSink.toNativeJson(note)))+        assertNull(NoteSink.fromPayload("{broken"))+        assertTrue(NoteSink.toNativeJson(note).contains("\"syncId\":\"nx\""))+    }++    @Test fun keyStoreCorruptInputsFailClosed() {+        // Unseal rejects non-sealed, non-base64, and truncated sealed values+        assertNull(VaultKeyStore.unseal(ctx, "plain-b64"))+        assertNull(VaultKeyStore.unseal(ctx, "v1:!!!"))+        assertNull(VaultKeyStore.unseal(ctx, "v1:" + Base64.encode(byteArrayOf(1, 2))))+        assertNull(SnapshotKeyStore.unseal(ctx, byteArrayOf(0, 0, 0)))+        assertNull(SnapshotKeyStore.unseal(ctx, ByteArray(0)))+        // readKey on corrupt/absent material is null, never a crash+        val corrupt = VaultMeta("vx", "notes", "T", keyB64 = "v1:" + Base64.encode(byteArrayOf(5, 5, 5)), ownerDeviceId = "d")+        assertNull(corrupt.readKey(ctx))+        val blank = VaultMeta("vy", "notes", "T", keyB64 = "", ownerDeviceId = "d")+        assertNull(blank.readKey(ctx))+        val notB64 = VaultMeta("vz", "notes", "T", keyB64 = "v1:AAAA", ownerDeviceId = "d")+        assertNull(notB64.readKey(ctx))+        // Seal produces a v1-prefixed value that round-trips through readKey+        val keyB64 = Base64.encode(ByteArray(32) { it.toByte() })+        val sealed = VaultKeyStore.seal(ctx, keyB64)+        assertTrue(sealed != null && VaultKeyStore.looksSealed(sealed))+        val meta = VaultMeta("vw", "notes", "T", keyB64 = sealed!!, ownerDeviceId = "d")+        assertTrue(meta.readKey(ctx)!!.contentEquals(ByteArray(32) { it.toByte() }))+    }+}
everysync/src/test/java/com/vayunmathur/everysync/SystemVaultDriveTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/SystemVaultDriveTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/SystemVaultDriveTest.ktnew file mode 100644index 0000000000..2a4cd865b0--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/SystemVaultDriveTest.kt@@ -0,0 +1,240 @@+package com.vayunmathur.everysync++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.CalendarContract+import android.provider.ContactsContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.RemoteContact+import com.vayunmathur.everysync.data.RemoteEvent+import com.vayunmathur.everysync.data.RemotePassword+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.CalendarSink+import com.vayunmathur.everysync.data.sink.ContactsSink+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.SyncState+import com.vayunmathur.everysync.provider.impl.E2eeProvider+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import com.vayunmathur.everysync.sync.SnapshotStore+import com.vayunmathur.everysync.sync.adapters.ContactKind+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Contacts/calendar vault cycles against fake system providers, plus the+ * per-type snapshot/restore and purge paths. No network, no AndroidKeyStore.+ */+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class SystemVaultDriveTest {+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    class StoreProvider : ContentProvider() {+        val tables = mutableMapOf<String, MutableList<MutableMap<String, Any?>>>()+        var insertCount = 0+        override fun onCreate() = true+        private fun table(uri: Uri) = uri.pathSegments.lastOrNull { it !in setOf("upsertRaw", "querySince", "deleteByVault") } ?: ""+        override fun query(uri: Uri, projection: Array<String>?, sel: String?, args: Array<String>?, sort: String?): Cursor {+            val cols = projection ?: arrayOf("_id")+            val c = MatrixCursor(cols)+            for (row in tables[table(uri)].orEmpty()) c.addRow(cols.map { row[it] }.toTypedArray())+            return c+        }+        override fun insert(uri: Uri, values: ContentValues?): Uri? {+            insertCount+++            val row = mutableMapOf<String, Any?>()+            values?.keySet()?.forEach { row[it] = values.get(it) }+            if (row.isNotEmpty()) tables.getOrPut(table(uri)) { mutableListOf() }.add(row)+            return Uri.withAppendedPath(uri, "99")+        }+        override fun delete(uri: Uri, s: String?, a: Array<String>?) = 1+        override fun update(uri: Uri, v: ContentValues?, s: String?, a: Array<String>?) = 1+        override fun getType(uri: Uri) = "vnd.test"+    }++    private lateinit var contacts: StoreProvider+    private lateinit var calendars: StoreProvider++    @BeforeTest fun setUp() {+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        contacts = StoreProvider(); ShadowContentResolver.registerProviderInternal(ContactsContract.AUTHORITY, contacts)+        calendars = StoreProvider(); ShadowContentResolver.registerProviderInternal(CalendarContract.AUTHORITY, calendars)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 13 + 7).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(ctx).secretKeyForTest = softwareKey+    }++    private suspend fun makeVault(type: String, vaultId: String, bind: Boolean = true): Pair<VaultMeta, ByteArray> {+        val key = RelaySync.newVaultKey()+        val meta = VaultMeta(vaultId, type, "T-$type", Base64.encode(key), RelaySync.deviceId, Base64.encode(RelaySync.publicBundle), isOwner = true)+        VaultStore.upsert(ctx, meta)+        if (bind) SyncState.set(ctx, ACCOUNT, "e2ee_vault_$type", vaultId)+        return VaultStore.get(ctx, vaultId)!! to key+    }++    private fun seedContact() {+        contacts.tables["raw_contacts"] = mutableListOf(+            mutableMapOf("_id" to 7L, "source_id" to "c1", "sync1" to "100", "deleted" to 0),+        )+        contacts.tables["data"] = mutableListOf(+            mutableMapOf("mimetype" to "vnd.android.cursor.item/name", "data1" to "Ann Lee", "data2" to "Ann", "data3" to "Lee"),+            mutableMapOf("mimetype" to "vnd.android.cursor.item/phone_v2", "data1" to "+123", "data2" to 2),+        )+    }++    @Test fun contactsAndCalendarVaultCycles() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        // CONTACTS: local row pushes to the relay; a remote edit is stamped back locally+        val (cMeta, cKey) = makeVault("contacts", "v-sys-contacts")+        seedContact()+        val provider = E2eeProvider()+        val cConfig = AccountConfig(ACCOUNT, "e2ee", setOf(DataType.CONTACTS))+        provider.sync(ctx, cConfig, SyncDirection.BOTH)+        val cChannel = RelaySync.recordChannel("contacts", cMeta.vaultId)+        assertEquals(1, relay.channel(cChannel).size)+        val cPulled = RelaySync.pullRecords(cChannel, cKey, 0)+        assertEquals("Ann Lee", ContactKind.fromJson(cPulled!!.items.single())?.displayName)+        // Remote newer version of the same contact+        val remoteContact = ContactKind.fromJson(cPulled.items.single())!!.copy(displayName = "Ann Lee-Remote", updatedAt = 9_999)+        RelaySync.appendRecords(cChannel, cKey, listOf(ContactKind.toJson(remoteContact)))+        val insertsBefore = contacts.insertCount+        provider.sync(ctx, cConfig, SyncDirection.BOTH)+        assertTrue(contacts.insertCount > insertsBefore, "stamped write-back should insert/update")++        // CALENDAR: getOrCreate finds calendar 5, local event pushes, cycle is clean after+        val (eMeta, eKey) = makeVault("calendar", "v-sys-calendar")+        calendars.tables["calendars"] = mutableListOf(mutableMapOf("_id" to 5L))+        CalendarSink.upsertEvent(ctx, ACCOUNT, 5L, RemoteEvent(uid = "ev1", calendarId = "5", summary = "Standup", startMillis = 1_000, endMillis = 2_000, updatedAt = 100))+        val eConfig = AccountConfig(ACCOUNT, "e2ee", setOf(DataType.CALENDAR))+        provider.sync(ctx, eConfig, SyncDirection.BOTH)+        val eChannel = RelaySync.recordChannel("calendar", eMeta.vaultId)+        assertTrue(relay.channel(eChannel).isNotEmpty())+        val ePulled = RelaySync.pullRecords(eChannel, eKey, 0)+        assertTrue(ePulled!!.items.any { it.contains("ev1") })++        // MULTI-TYPE sync runs both vaults in one call (abort-free)+        val both = AccountConfig(ACCOUNT, "e2ee", setOf(DataType.CONTACTS, DataType.CALENDAR))+        provider.sync(ctx, both, SyncDirection.BOTH)+        // PULL-only and PUSH-only directions also complete+        provider.sync(ctx, both, SyncDirection.PULL)+        provider.sync(ctx, both, SyncDirection.PUSH)+        Unit+    } }++    @Test fun resolveCreatesVaultWhenUnboundAndNoneExists() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        // A fresh account with no vaults at all: sync creates + adopts one for the type.+        // Use a dedicated account name so the binding lookup starts empty.+        val fresh = AccountConfig("fresh-acc", "e2ee", setOf(DataType.NOTES))+        // Remove any notes vaults other tests in this class may have made: create path+        // only triggers when VaultStore has no notes vault and no binding.+        for (m in VaultStore.getAll(ctx).filter { it.dataType == "notes" }) VaultStore.remove(ctx, m.vaultId)+        E2eeProvider().sync(ctx, fresh, SyncDirection.BOTH)+        val created = VaultStore.getAll(ctx).filter { it.dataType == "notes" }+        assertEquals(1, created.size)+        assertTrue(created.single().isOwner)+        assertEquals(created.single().vaultId, E2eeProvider.vaultIdFor(ctx, "fresh-acc", "notes"))+        // Syncing again reuses the same vault (no duplicate creation)+        E2eeProvider().sync(ctx, fresh, SyncDirection.BOTH)+        assertEquals(1, VaultStore.getAll(ctx).filter { it.dataType == "notes" }.size)+    } }++    @Test fun purgeTypeSnapshotsThenClears() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val (nMeta, _) = makeVault("notes", "v-purge-notes")+        NoteSink.upsert(ctx, nMeta.vaultId, com.vayunmathur.everysync.data.RemoteNote(uid = "pn1", title = "Bye", updatedAt = 1))+        val (pMeta, _) = makeVault("passwords", "v-purge-pass")+        PasswordSink.upsert(ctx, pMeta.vaultId, RemotePassword(uid = "pp1", name = "X", updatedAt = 1))+        E2eeProvider.purgeType(ctx, ACCOUNT, DataType.NOTES)+        assertTrue(NoteSink.listLocal(ctx, nMeta.vaultId).isEmpty())+        // Purge took a snapshot first: the way back exists+        assertTrue(SnapshotStore.listForVault(ctx, nMeta.vaultId).isNotEmpty())+        E2eeProvider.purgeType(ctx, ACCOUNT, DataType.PASSWORDS)+        assertTrue(PasswordSink.listLocal(ctx, pMeta.vaultId).isEmpty())+        E2eeProvider.purgeType(ctx, ACCOUNT, DataType.TODOS)+        E2eeProvider.purgeType(ctx, ACCOUNT, DataType.CONTACTS)+        E2eeProvider.purgeType(ctx, ACCOUNT, DataType.CALENDAR)+        // Relay type mapping is stable+        assertEquals("contacts", DataType.CONTACTS.let { with(E2eeProvider) { it.relayType() } })+        assertEquals("todos", DataType.TODOS.let { with(E2eeProvider) { it.relayType() } })+        assertNotNull(E2eeProvider.vaultIdFor(ctx, ACCOUNT, "notes"))+    } }++    @Test fun snapshotsForEveryTypeAndRestore() { runBlocking {+        assertTrue(RelaySync.init(ctx))+        val store = AccountStore.getInstance(ctx)+        store.upsert(AccountConfig(ACCOUNT, "e2ee", emptySet()))+        // passwords+        val (pMeta, _) = makeVault("passwords", "v-snap-pass2")+        PasswordSink.upsert(ctx, pMeta.vaultId, RemotePassword(uid = "sp1", name = "Mail", password = "pw", updatedAt = 3))+        assertTrue(SnapshotStore.snapshotVault(ctx, pMeta.vaultId, "passwords"))+        val pSnap = SnapshotStore.listForVault(ctx, pMeta.vaultId).single()+        PasswordSink.delete(ctx, pMeta.vaultId, "sp1")+        assertEquals(1, SnapshotStore.restore(ctx, pSnap))+        assertTrue(PasswordSink.listLocal(ctx, pMeta.vaultId).any { it.uid == "sp1" })+        // todos+        val (tMeta, _) = makeVault("todos", "v-snap-todo2")+        TodoIpcSink.upsert(ctx, tMeta.vaultId, com.vayunmathur.everysync.data.RemoteTodo(uid = "st1", title = "Task", updatedAt = 3))+        assertTrue(SnapshotStore.snapshotVault(ctx, tMeta.vaultId, "todos"))+        val tSnap = SnapshotStore.listForVault(ctx, tMeta.vaultId).single()+        TodoIpcSink.delete(ctx, tMeta.vaultId, "st1")+        assertEquals(1, SnapshotStore.restore(ctx, tSnap))+        // contacts (single account resolves the vault's account)+        val (cMeta, _) = makeVault("contacts", "v-snap-contacts2")+        seedContact()+        assertTrue(SnapshotStore.snapshotVault(ctx, cMeta.vaultId, "contacts"))+        val cSnap = SnapshotStore.listForVault(ctx, cMeta.vaultId).single()+        assertEquals(1, cSnap.recordCount)+        assertNotNull(SnapshotStore.restore(ctx, cSnap))+        // calendar (no events yet: empty snapshot is healthy when a calendar exists)+        val (eMeta, _) = makeVault("calendar", "v-snap-cal2")+        calendars.tables["calendars"] = mutableListOf(mutableMapOf("_id" to 5L))+        calendars.tables["events"] = mutableListOf(+            mutableMapOf("_id" to 11L, "_sync_id" to "sev1", "sync_data1" to "100", "deleted" to 0, "title" to "Meet", "description" to "", "eventLocation" to "", "dtstart" to 1000L, "dtend" to 2000L, "allDay" to 0, "eventTimezone" to "UTC", "rrule" to null),+        )+        assertTrue(SnapshotStore.snapshotVault(ctx, eMeta.vaultId, "calendar"))+        val eSnap = SnapshotStore.listForVault(ctx, eMeta.vaultId).single()+        assertEquals(1, eSnap.recordCount)+        assertNotNull(SnapshotStore.restore(ctx, eSnap))+        // notes with a blob file: blob is captured + restored+        val (nMeta, _) = makeVault("notes", "v-snap-notes2")+        NoteSink.upsert(ctx, nMeta.vaultId, com.vayunmathur.everysync.data.RemoteNote(uid = "snb1", title = "Pic", updatedAt = 3))+        val blobDir = java.io.File(ctx.filesDir, "relay_blobs/${nMeta.vaultId}").apply { mkdirs() }+        java.io.File(blobDir, "img1.png").writeBytes(byteArrayOf(9, 8, 7))+        assertTrue(SnapshotStore.snapshotVault(ctx, nMeta.vaultId, "notes"))+        val nSnap = SnapshotStore.listForVault(ctx, nMeta.vaultId).single()+        assertEquals(1, nSnap.blobCount)+        java.io.File(blobDir, "img1.png").delete()+        assertEquals(1, SnapshotStore.restore(ctx, nSnap))+        assertTrue(java.io.File(ctx.filesDir, "relay_blobs/${nMeta.vaultId}/img1.png").exists())+    } }++    private companion object { const val ACCOUNT = "alice" }+}
everysync/src/test/java/com/vayunmathur/everysync/VaultJoinTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/VaultJoinTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/VaultJoinTest.ktnew file mode 100644index 0000000000..02c26b18a8--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/VaultJoinTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.everysync++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelayRoles+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.platform.EverySyncViewModel+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Joining a shared vault: inbox invite adoption, signed title, verified roster. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class VaultJoinTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay+    private val json = Json { ignoreUnknownKeys = true }++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 19 + 2).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(app).secretKeyForTest = softwareKey+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); relay.uninstall() }++    private fun await(deadlineMs: Long = 20_000, condition: () -> Boolean): Boolean {+        val end = System.currentTimeMillis() + deadlineMs+        while (System.currentTimeMillis() < end) {+            if (condition()) return true+            Thread.sleep(25)+        }+        return condition()+    }++    @Test fun joinedVaultAdoptedWithSignedTitleAndRoster() { runBlocking {+        assertTrue(RelaySync.init(app))+        val device = RelaySync.deviceId+        val vaultId = "v-joined-1"+        val vaultKey = RelaySync.newVaultKey()+        // The owner (this same identity, acting as the sharing device) publishes+        // a signed title and roster, then seals us the invite.+        val titlePayload = json.encodeToString(mapOf("title" to "Shared Notes"))+        val titleEnv = json.encodeToString(RelaySync.SignedEnvelope(device, Base64.encode(RelaySync.sign(titlePayload.encodeToByteArray())), titlePayload))+        RelaySync.appendRaw("title:$vaultId", listOf(titleEnv))+        // A forged title (bad signature) must be ignored in favour of the signed one+        val forgedPayload = json.encodeToString(mapOf("title" to "Forged"))+        val forgedEnv = json.encodeToString(RelaySync.SignedEnvelope("mallory", Base64.encode(byteArrayOf(1, 1, 1)), forgedPayload))+        RelaySync.appendRaw("title:$vaultId", listOf(forgedEnv))+        assertTrue(RelaySync.sendInvite(device, vaultId, "notes", vaultKey, "Placeholder title", RelayRoles.EDITOR, Base64.encode(RelaySync.publicBundle), device, epoch = 1))++        val vm = EverySyncViewModel(app)+        vm.vaults.refreshInbox()+        assertTrue(await { VaultStore.get(app, vaultId) != null }, "vaults=${VaultStore.getAll(app)}")+        val joined = VaultStore.get(app, vaultId)!!+        assertEquals(false, joined.isOwner)+        assertEquals(1, joined.epoch)+        // The signed title wins over the invite's placeholder once the vault UI refreshes+        assertTrue(await { vm.vaults.vaultUi.value[vaultId]?.meta?.title == "Shared Notes" },+            "ui=${vm.vaults.vaultUi.value[vaultId]}")+        assertTrue(vm.vaults.vaultUi.value.getValue(vaultId).shareLink.contains(vaultId))+        // Inbox cursor advanced: a second refresh does not re-adopt or duplicate+        vm.vaults.refreshInbox()+        assertTrue(await { VaultStore.getAll(app).count { it.vaultId == vaultId } == 1 })+        Unit+    } }+}
everysync/src/test/java/com/vayunmathur/everysync/VaultsFlowTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/VaultsFlowTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/VaultsFlowTest.ktnew file mode 100644index 0000000000..4023e439ca--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/VaultsFlowTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.everysync++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelayRoles+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.platform.EverySyncViewModel+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import javax.crypto.spec.SecretKeySpec+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+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++/** Vault sharing flows (create/invite/join/approve/deny) over the fake relay. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class VaultsFlowTest {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 3 + 5).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(app).secretKeyForTest = softwareKey+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); relay.uninstall() }++    private fun await(deadlineMs: Long = 20_000, condition: () -> Boolean): Boolean {+        val end = System.currentTimeMillis() + deadlineMs+        while (System.currentTimeMillis() < end) {+            if (condition()) return true+            Thread.sleep(25)+        }+        return condition()+    }++    @Test fun createInviteJoinApproveAndSafetyCode() {+        val vm = EverySyncViewModel(app)+        vm.vaults.load()+        assertTrue(await { vm.vaults.deviceId.value == RelaySync.deviceId && RelaySync.deviceId.isNotBlank() }, "deviceId=${vm.vaults.deviceId.value}")+        assertTrue(vm.vaults.vaults.value.none { it.title == "My Notes" })++        var createResult: Boolean? = null+        vm.vaults.createVault("notes", "My Notes") { createResult = it }+        assertTrue(await { createResult != null }); assertEquals(true, createResult)+        val meta = vm.vaults.vaults.value.first { it.title == "My Notes" }+        assertTrue(meta.isOwner); assertEquals("notes", meta.dataType)+        // Owner roster + signed title landed on the relay+        assertTrue(relay.channel("members:${meta.vaultId}").isNotEmpty())+        assertTrue(relay.channel("title:${meta.vaultId}").isNotEmpty())+        // Vault UI state is computed with a share link and the owner member+        assertTrue(await { vm.vaults.vaultUi.value.containsKey(meta.vaultId) })+        val ui = vm.vaults.vaultUi.value.getValue(meta.vaultId)+        assertTrue(ui.shareLink.contains(meta.vaultId))+        assertTrue(ui.members.any { it.role == RelayRoles.OWNER })+        assertEquals(ui.shareLink, vm.vaults.shareLinkFor(meta))++        // Invite self (registered) works, unknown device does not+        var inviteResult: Boolean? = null+        vm.vaults.sendInvite(meta.vaultId, RelaySync.deviceId, RelayRoles.VIEWER) { inviteResult = it }+        assertTrue(await { inviteResult != null }); assertEquals(true, inviteResult)+        inviteResult = null+        vm.vaults.sendInvite(meta.vaultId, "ghost-device", RelayRoles.EDITOR) { inviteResult = it }+        assertTrue(await { inviteResult != null }); assertEquals(false, inviteResult)+        // Inviting for a missing vault fails closed+        inviteResult = null+        vm.vaults.sendInvite("no-such-vault", RelaySync.deviceId, RelayRoles.EDITOR) { inviteResult = it }+        assertTrue(await { inviteResult != null }); assertEquals(false, inviteResult)++        // Join request to self, pulled back as a pending request, then approved+        var joinResult: Boolean? = null+        vm.vaults.requestToJoin(meta.vaultId, RelaySync.deviceId, "notes") { joinResult = it }+        assertTrue(await { joinResult != null }); assertEquals(true, joinResult)+        vm.vaults.refreshInbox()+        assertTrue(await {+            vm.vaults.vaultUi.value[meta.vaultId]?.requests?.any { it.requesterId == RelaySync.deviceId } == true+        }, "ui=${vm.vaults.vaultUi.value}")+        vm.vaults.approveRequest(meta.vaultId, RelaySync.deviceId, "Self", RelayRoles.EDITOR)+        assertTrue(await {+            vm.vaults.vaultUi.value[meta.vaultId]?.requests?.none { it.requesterId == RelaySync.deviceId } == true+        })+        // The invite from the approval is in our own inbox channel+        assertTrue(relay.channel("inbox:${RelaySync.deviceId}").isNotEmpty())++        // A second request can be denied instead+        joinResult = null+        vm.vaults.requestToJoin(meta.vaultId, RelaySync.deviceId, "notes") { joinResult = it }+        assertTrue(await { joinResult != null }); assertEquals(true, joinResult)+        vm.vaults.refreshInbox()+        assertTrue(await {+            vm.vaults.vaultUi.value[meta.vaultId]?.requests?.any { it.requesterId == RelaySync.deviceId } == true+        })+        vm.vaults.denyRequest(meta.vaultId, RelaySync.deviceId)+        assertTrue(await {+            vm.vaults.vaultUi.value[meta.vaultId]?.requests?.isEmpty() == true+        })++        // Safety codes: self has one, unknown devices do not+        var code: String? = "unset"; var codeDone = false+        vm.vaults.safetyCode(RelaySync.deviceId) { code = it; codeDone = true }+        assertTrue(await { codeDone }); assertNotNull(code)+        // ViewModel-level safety code + offerable roles (passwords never viewer at VM level either)+        vm.computeSafetyCode(RelaySync.deviceId)+        assertTrue(await { !vm.computingCode.value && vm.safetyCode.value != null })+        assertEquals(listOf(RelayRoles.OWNER, RelayRoles.EDITOR), vm.offerableRoles("passwords"))+        assertEquals(listOf(RelayRoles.OWNER, RelayRoles.EDITOR, RelayRoles.VIEWER), vm.offerableRoles("notes"))+        var ghostCode: String? = "unset"; var ghostDone = false+        vm.vaults.safetyCode("ghost-device") { ghostCode = it; ghostDone = true }+        assertTrue(await { ghostDone }); assertNull(ghostCode)+        assertFalse(vm.vaults.vaultUi.value.isEmpty())+    }+}
everysync/src/test/java/com/vayunmathur/everysync/ViewModel2Test.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/ViewModel2Test.kt b/everysync/src/test/java/com/vayunmathur/everysync/ViewModel2Test.ktnew file mode 100644index 0000000000..89140357ae--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/ViewModel2Test.kt@@ -0,0 +1,132 @@+package com.vayunmathur.everysync++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.data.RemoteNote+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.data.VaultStore+import com.vayunmathur.everysync.data.sink.NoteSink+import com.vayunmathur.everysync.data.sink.PasswordSink+import com.vayunmathur.everysync.data.sink.TodoIpcSink+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.platform.EverySyncViewModel+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.sync.SnapshotKeyStore+import com.vayunmathur.everysync.sync.SnapshotStore+import javax.crypto.spec.SecretKeySpec+import kotlin.io.encoding.Base64+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** ViewModel behaviours needing the fake relay + providers: error mapping, purges, snapshot restore. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class ViewModel2Test {+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val relay get() = RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        relay.install()+        FakeIpcProvider.install(NoteSink.AUTHORITY, PasswordSink.AUTHORITY, TodoIpcSink.AUTHORITY)+        val softwareKey = SecretKeySpec(ByteArray(32) { (it * 11 + 3).toByte() }, "AES")+        com.vayunmathur.everysync.data.VaultKeyStore.secretKeyForTest = softwareKey+        SnapshotKeyStore.secretKeyForTest = softwareKey+        TokenStore.getInstance(app).secretKeyForTest = softwareKey+        try {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        } catch (_: IllegalStateException) { /* already initialised */ }+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); relay.uninstall() }++    private fun await(deadlineMs: Long = 20_000, condition: () -> Boolean): Boolean {+        val end = System.currentTimeMillis() + deadlineMs+        while (System.currentTimeMillis() < end) {+            if (condition()) return true+            Thread.sleep(25)+        }+        return condition()+    }++    @Test fun syncErrorTextMapsAbortCodes() { runBlocking {+        val store = AccountStore.getInstance(app)+        val vm = EverySyncViewModel(app)+        assertNull(vm.syncErrorText("ghost"))+        store.upsert(AccountConfig("err-acc", "e2ee", emptySet()))+        assertNull(vm.syncErrorText("err-acc"))+        for ((code, expectDistinct) in listOf(+            "pull_transport_failed" to true, "log_undecryptable" to true,+            "local_read_failed" to true, "relay_unavailable" to true, "some raw error" to false,+        )) {+            store.upsert(AccountConfig("err-acc", "e2ee", emptySet(), lastSyncError = "vault sync aborted: $code (notes)"))+            val text = vm.syncErrorText("err-acc")+            assertNotNull(text, code)+            if (!expectDistinct) assertEquals("vault sync aborted: some raw error (notes)", text)+        }+        // Distinct codes map to distinct user-facing strings+        store.upsert(AccountConfig("err-acc", "e2ee", emptySet(), lastSyncError = "pull_transport_failed"))+        val a = vm.syncErrorText("err-acc")+        store.upsert(AccountConfig("err-acc", "e2ee", emptySet(), lastSyncError = "log_undecryptable"))+        assertTrue(a != vm.syncErrorText("err-acc"))+        Unit+    } }++    @Test fun toggleTypesPurgesAndSnapshotRestore() { runBlocking {+        assertTrue(RelaySync.init(app))+        val store = AccountStore.getInstance(app)+        store.upsert(AccountConfig("vm-acc", "e2ee", setOf(DataType.CONTACTS, DataType.CALENDAR, DataType.PASSWORDS, DataType.NOTES, DataType.TODOS)))+        val key = RelaySync.newVaultKey()+        VaultStore.upsert(app, VaultMeta("v-vm-notes", "notes", "VM Notes", Base64.encode(key), RelaySync.deviceId, Base64.encode(RelaySync.publicBundle), isOwner = true))+        NoteSink.upsert(app, "v-vm-notes", RemoteNote(uid = "vm1", title = "Keep me", updatedAt = 5))+        val vm = EverySyncViewModel(app)+        // Disable notes: snapshot is taken first, local notes are purged, type removed+        vm.toggleType("vm-acc", DataType.NOTES, false)+        assertTrue(await { store.get("vm-acc")?.enabledTypes?.contains(DataType.NOTES) == false })+        assertTrue(await { NoteSink.listLocal(app, "v-vm-notes").isEmpty() })+        assertTrue(SnapshotStore.listForVault(app, "v-vm-notes").isNotEmpty())+        // Re-enable: type restored+        vm.toggleType("vm-acc", DataType.NOTES, true)+        assertTrue(await { store.get("vm-acc")?.enabledTypes?.contains(DataType.NOTES) == true })+        // Disable the IPC + system types too (purge paths for each), awaiting+        // each toggle so the read-modify-write cycles do not race each other+        for (type in listOf(DataType.PASSWORDS, DataType.TODOS, DataType.CONTACTS, DataType.CALENDAR)) {+            vm.toggleType("vm-acc", type, false)+            assertTrue(await { store.get("vm-acc")?.enabledTypes?.contains(type) == false }, "type $type still enabled: ${store.get("vm-acc")?.enabledTypes}")+        }+        assertEquals(setOf(DataType.NOTES), store.get("vm-acc")?.enabledTypes)+        vm.toggleType("ghost", DataType.NOTES, true) // unknown account: no-op, no crash++        // Snapshot restore through the ViewModel announces and clears the restoring flag+        vm.loadSnapshots()+        assertTrue(await { vm.snapshots.value.any { it.vaultId == "v-vm-notes" } })+        val snap = vm.snapshots.value.first { it.vaultId == "v-vm-notes" }+        vm.restoreSnapshot(snap)+        assertTrue(await { !vm.restoring.value && NoteSink.listLocal(app, "v-vm-notes").any { it.uid == "vm1" } })+        // snapshotNow is idempotent for the same day+        vm.snapshotNow()+        assertTrue(await { vm.snapshots.value.count { it.vaultId == "v-vm-notes" } >= 1 })+        // Settings actions persist+        vm.setInterval(30); vm.setWifiOnly(true); vm.setConflictPolicy("remote")+        assertTrue(await { com.vayunmathur.everysync.data.Settings.intervalMinutes(app) == 30L })+        vm.removeAccount("vm-acc")+        assertTrue(await { store.get("vm-acc") == null })+        Unit+    } }+}
everysync/src/test/java/com/vayunmathur/everysync/domain/format/Formats2Test.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/domain/format/Formats2Test.kt b/everysync/src/test/java/com/vayunmathur/everysync/domain/format/Formats2Test.ktnew file mode 100644index 0000000000..f57249a6b2--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/domain/format/Formats2Test.kt@@ -0,0 +1,107 @@+package com.vayunmathur.everysync.domain.format++import com.vayunmathur.everysync.data.RemoteEvent+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** ICalendar branches the first pass left: timezones, folding, defaults, escaping, malformed input. */+class Formats2Test {++    @Test fun parseZonedRecurringAndFolded() {+        val text = buildString {+            append("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n")+            append("BEGIN:VEVENT\r\n")+            append("UID:evt-1\r\n")+            append("DTSTART;TZID=America/New_York:20240115T090000\r\n")+            append("DTEND;TZID=America/New_York:20240115T100000\r\n")+            append("SUMMARY:Long title that was\r\n folded across lines\r\n")+            append("DESCRIPTION:Line1\\nLine2\\, with\\; escapes\\\\end\r\n")+            append("LOCATION:Room 5\r\n")+            append("RRULE:FREQ=WEEKLY;BYDAY=MO\r\n")+            append("RECURRENCE-ID:20240122T140000Z\r\n")+            append("END:VEVENT\r\n")+            append("BEGIN:VEVENT\r\n")+            append("DTSTART;VALUE=DATE:20240229\r\n")+            append("SUMMARY:Leap day all-day\r\n")+            append("END:VEVENT\r\n")+            append("END:VCALENDAR\r\n")+        }+        val events = ICalendar.parse(text, "cal-9")+        assertEquals(2, events.size)+        val zoned = events[0]+        assertEquals("evt-1", zoned.uid)+        assertEquals("America/New_York", zoned.timezone)+        assertEquals(3_600_000L, zoned.endMillis - zoned.startMillis)+        assertEquals("Long title that wasfolded across lines", zoned.summary)+        assertEquals("Line1\nLine2, with; escapes\\end", zoned.description)+        assertEquals("Room 5", zoned.location)+        assertEquals("FREQ=WEEKLY;BYDAY=MO", zoned.rrule)+        assertEquals("20240122T140000Z", zoned.recurrenceId)+        assertEquals(false, zoned.allDay)+        val allDay = events[1]+        assertEquals(true, allDay.allDay)+        // No DTEND on an all-day event defaults to a full day+        assertEquals(86_400_000L, allDay.endMillis - allDay.startMillis)+        assertEquals("cal-9", allDay.calendarId)+        // Missing UID falls back to the supplied fallback+        assertTrue(allDay.uid.isNotBlank())+    }++    @Test fun parseFallbackUidAndMalformed() {+        val noUid = "BEGIN:VEVENT\nDTSTART:20240101T000000Z\nSUMMARY:X\nEND:VEVENT\n"+        assertEquals("fallback-1", ICalendar.parse(noUid, "c", fallbackUid = "fallback-1").single().uid)+        // Garbage dates fall back to epoch + one hour rather than throwing+        val bad = "BEGIN:VEVENT\nUID:bad\nDTSTART:not-a-date\nEND:VEVENT\n"+        val ev = ICalendar.parse(bad, "c").single()+        assertEquals(0L, ev.startMillis); assertEquals(3_600_000L, ev.endMillis)+        // Lines outside events and properties without colons are ignored+        val messy = "BEGIN:VCALENDAR\nJUNKLINE\nBEGIN:VEVENT\nUID:ok\nDTSTART:20240101T120000Z\nEND:VEVENT\nEND:VCALENDAR\n"+        assertEquals(1, ICalendar.parse(messy, "c").size)+        assertTrue(ICalendar.parse("", "c").isEmpty())+        assertTrue(ICalendar.parse("no events here", "c").isEmpty())+        // Tab-folded continuation also unfolds+        val tabbed = "BEGIN:VEVENT\nUID:t\nSUMMARY:ab\n\tcd\nDTSTART:20240101T000000Z\nEND:VEVENT\n"+        assertEquals("abcd", ICalendar.parse(tabbed, "c").single().summary)+    }++    @Test fun serializeRoundTripsTimedAllDayAndRecurring() {+        val timed = RemoteEvent(+            uid = "rt-1", calendarId = "c", summary = "Meet; greet, then\nleave",+            description = "Bring \\ stuff", location = "Office",+            startMillis = 1_705_314_000_000L, endMillis = 1_705_317_600_000L,+            rrule = "RRULE:FREQ=DAILY", recurrenceId = "20240116T090000Z",+        )+        val parsed = ICalendar.parse(ICalendar.serialize(timed), "c").single()+        assertEquals(timed.uid, parsed.uid)+        assertEquals(timed.summary, parsed.summary)+        assertEquals(timed.description, parsed.description)+        assertEquals(timed.location, parsed.location)+        assertEquals(timed.startMillis, parsed.startMillis)+        assertEquals(timed.endMillis, parsed.endMillis)+        assertEquals("FREQ=DAILY", parsed.rrule)+        assertEquals(timed.recurrenceId, parsed.recurrenceId)+        assertTrue(ICalendar.serialize(timed).contains("RRULE:FREQ=DAILY"))++        val allDay = RemoteEvent(uid = "rt-2", calendarId = "c", summary = "Holiday", startMillis = 1_709_164_800_000L, endMillis = 1_709_251_200_000L, allDay = true)+        val parsedDay = ICalendar.parse(ICalendar.serialize(allDay), "c").single()+        assertEquals(true, parsedDay.allDay)+        assertEquals(allDay.startMillis, parsedDay.startMillis)+        assertEquals(allDay.endMillis, parsedDay.endMillis)+        // Blank optional fields are omitted from the wire form+        val bare = ICalendar.serialize(RemoteEvent(uid = "rt-3", calendarId = "c", startMillis = 0, endMillis = 1000))+        assertTrue(!bare.contains("SUMMARY")); assertTrue(!bare.contains("RRULE"))+    }++    @Test fun vCardExtraBranches() {+        // Escapes and structured name fields survive a round trip through VCard helpers+        val parsed = VCard.parse("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Doe\\, John\r\nN:Doe;John;;Dr.;Jr.\r\nORG:Acme Inc\r\nTITLE:Dev\r\nEND:VCARD\r\n")+        assertEquals("Doe, John", parsed.displayName)+        assertEquals("Doe", parsed.lastName); assertEquals("John", parsed.firstName)+        assertEquals("Dr.", parsed.prefix); assertEquals("Jr.", parsed.suffix)+        assertEquals("Acme Inc", parsed.organization)+        assertTrue(VCard.serialize(parsed).contains("FN:"))+        assertNull(VCard.parse("BEGIN:VCARD\nEND:VCARD\n").displayName.ifBlank { null })+    }+}
everysync/src/test/java/com/vayunmathur/everysync/ui/BinderScreensTest.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/ui/BinderScreensTest.kt b/everysync/src/test/java/com/vayunmathur/everysync/ui/BinderScreensTest.ktnew file mode 100644index 0000000000..b2eb32e96a--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/ui/BinderScreensTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.everysync.ui++import android.app.Application+import android.os.Looper+import androidx.compose.ui.test.ExperimentalTestApi+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.Route+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.data.Settings+import com.vayunmathur.everysync.network.remote.RelaySync+import com.vayunmathur.everysync.platform.EverySyncViewModel+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** The ViewModel-binding screen overloads (backStack + viewModel), driven end to end. */+@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = Application::class)+class BinderScreensTest {+    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val relay get() = com.vayunmathur.everysync.RelaySuccessTest.sharedRelay++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        relay.install()+        try {+            androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+        } catch (_: IllegalStateException) { /* already initialised */ }+        shadowOf(app).grantPermissions(+            android.Manifest.permission.READ_CONTACTS, android.Manifest.permission.WRITE_CONTACTS,+            android.Manifest.permission.READ_CALENDAR, android.Manifest.permission.WRITE_CALENDAR,+        )+    }+    @AfterTest fun tearDown() { Dispatchers.resetMain(); relay.uninstall() }++    private fun idle() { shadowOf(Looper.getMainLooper()).idle() }+    private fun await(deadlineMs: Long = 15_000, condition: () -> Boolean): Boolean {+        val end = System.currentTimeMillis() + deadlineMs+        while (System.currentTimeMillis() < end) {+            rule.waitForIdle(); idle()+            if (condition()) return true+            Thread.sleep(25)+        }+        return condition()+    }+    private fun str(id: Int) = app.getString(id)++    @Test fun settingsBinderPersistsChanges() {+        val vm = EverySyncViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.Settings))+        rule.setContent { SettingsScreen(stack, vm) }+        rule.onNodeWithText(str(R.string.wifi_only)).performClick()+        assertTrue(await { Settings.wifiOnly(app) }, "wifiOnly not persisted")+        rule.onNodeWithText(str(R.string.conflict_remote), substring = true).performClick()+        assertTrue(await { Settings.conflictPolicy(app) == Settings.CONFLICT_REMOTE })+        // Interval edit goes through the ViewModel (coerced to the 15-minute floor by Settings)+        rule.onNode(hasSetTextAction()).performTextReplacement("45")+        rule.waitForIdle(); idle()+        assertTrue(Settings.intervalMinutes(app) in listOf(45L, 60L) || Settings.intervalMinutes(app) >= 15L)+    }++    @Test fun accountsBinderNavigates() { runBlocking {+        AccountStore.getInstance(app).upsert(AccountConfig("bind-acc", "e2ee", setOf(DataType.NOTES)))+        RelaySync.init(app)+        val vm = EverySyncViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.Accounts))+        rule.setContent { AccountsScreen(stack, vm) }+        rule.waitUntil(timeoutMillis = 10_000) { stack.backStack.size == 1 }+        rule.onNodeWithText("bind-acc").assertExists()+        rule.onNodeWithText("bind-acc").performClick()+        assertEquals(Route.AccountDetail("bind-acc"), stack.last())+    } }++    @Test fun addAccountBinderCreatesAndPops() {+        val vm = EverySyncViewModel(app)+        val stack = NavBackStack<Route>(arrayOf(Route.Accounts, Route.AddAccount))+        rule.setContent { AddAccountScreen(stack, vm) }+        rule.onNodeWithText("Personal vaults").performClick()+        // Account created from the provider's display name and the chooser popped+        assertTrue(await { runBlocking { AccountStore.getInstance(app).get("Personal vaults") } != null }, "account not created")+        assertEquals("e2ee", runBlocking { AccountStore.getInstance(app).get("Personal vaults") }?.providerId)+        assertTrue(await { stack.last() == Route.Accounts })+    }++    @Test fun accountDetailBinderActions() { runBlocking {+        AccountStore.getInstance(app).upsert(AccountConfig("detail-acc", "e2ee", setOf(DataType.NOTES, DataType.CONTACTS)))+        RelaySync.init(app)+        val vm = EverySyncViewModel(app)+        vm.vaults.load()+        val stack = NavBackStack<Route>(arrayOf(Route.Accounts, Route.AccountDetail("detail-acc")))+        rule.setContent { AccountDetailScreen(stack, vm, "detail-acc") }+        rule.waitForIdle(); idle()+        rule.onNodeWithText("detail-acc").assertExists()+        // Toggle notes off through the binder (snapshots + purges via the ViewModel)+        rule.onNodeWithText(str(R.string.sync_notes)).performClick()+        assertTrue(await { runBlocking { AccountStore.getInstance(app).get("detail-acc") }?.enabledTypes?.contains(DataType.NOTES) == false }, "notes not toggled off")+        // Sync now enqueues work without crashing; remove pops the stack and deletes the account+        rule.onNodeWithText(str(R.string.sync_now)).performScrollTo().performClick()+        rule.onNodeWithText(str(R.string.remove_account)).performScrollTo().performClick()+        assertTrue(await { stack.last() == Route.Accounts })+        assertTrue(await { runBlocking { AccountStore.getInstance(app).get("detail-acc") } == null })+        Unit+    } }+}
everysync/src/test/java/com/vayunmathur/everysync/ui/UiScreens2Test.kt
diff --git a/everysync/src/test/java/com/vayunmathur/everysync/ui/UiScreens2Test.kt b/everysync/src/test/java/com/vayunmathur/everysync/ui/UiScreens2Test.ktnew file mode 100644index 0000000000..b870e3853a--- /dev/null+++ b/everysync/src/test/java/com/vayunmathur/everysync/ui/UiScreens2Test.kt@@ -0,0 +1,224 @@+package com.vayunmathur.everysync.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.ExperimentalTestApi+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.data.VaultMeta+import com.vayunmathur.everysync.platform.AccountDetailActions+import com.vayunmathur.everysync.platform.AccountDetailUiState+import com.vayunmathur.everysync.platform.AccountRow+import com.vayunmathur.everysync.platform.AccountsActions+import com.vayunmathur.everysync.platform.AccountsUiState+import com.vayunmathur.everysync.platform.AddAccountActions+import com.vayunmathur.everysync.platform.SettingsActions+import com.vayunmathur.everysync.platform.SettingsUiState+import com.vayunmathur.everysync.platform.VaultMemberUi+import com.vayunmathur.everysync.platform.VaultRequestUi+import com.vayunmathur.everysync.platform.VaultUiState+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.sync.SnapshotStore+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@OptIn(ExperimentalTestApi::class)+@RunWith(RobolectricTestRunner::class)+@Config(application = android.app.Application::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class UiScreens2Test {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private fun str(id: Int) = ctx.getString(id)++    private fun show(initial: @Composable () -> Unit): androidx.compose.runtime.MutableState<@Composable () -> Unit> {+        val state = mutableStateOf(initial)+        rule.setContent { state.value() }+        return state+    }++    private class DetailRecorder : AccountDetailActions {+        val toggles = mutableListOf<Triple<String, DataType, Boolean>>()+        var synced: String? = null; var removed: String? = null; var backs = 0+        var created: Pair<String, String>? = null; var refreshes = 0+        var restored: SnapshotStore.SnapshotMeta? = null; var snapshotNows = 0+        val invites = mutableListOf<Triple<String, String, String>>()+        val approvals = mutableListOf<Pair<String, String>>(); val denies = mutableListOf<Pair<String, String>>()+        val safetyFor = mutableListOf<String>()+        override fun toggleType(accountName: String, type: DataType, enabled: Boolean) { toggles += Triple(accountName, type, enabled) }+        override fun syncNow(accountName: String) { synced = accountName }+        override fun removeAccount(accountName: String) { removed = accountName }+        override fun back() { backs++ }+        override fun restoreSnapshot(snapshot: SnapshotStore.SnapshotMeta) { restored = snapshot }+        override fun snapshotNow() { snapshotNows++ }+        override fun createVault(dataType: String, title: String) { created = dataType to title }+        override fun refreshVaults() { refreshes++ }+        override fun sendInvite(vaultId: String, recipientId: String, role: String, onResult: (Boolean) -> Unit) { invites += Triple(vaultId, recipientId, role); onResult(true) }+        override fun approveRequest(vaultId: String, requesterId: String) { approvals += vaultId to requesterId }+        override fun denyRequest(vaultId: String, requesterId: String) { denies += vaultId to requesterId }+        override fun computeSafetyCode(recipientId: String) { safetyFor += recipientId }+        override fun offerableRoles(dataType: String) = if (dataType == "passwords") listOf("editor") else listOf("editor", "viewer")+    }++    private fun vaultState() = VaultUiState(+        meta = VaultMeta(vaultId = "v1", dataType = "notes", title = "Home Notes", keyB64 = "", ownerDeviceId = "ownerdev", isOwner = true),+        shareLink = "https://maproj.org/es/share#id=v1&owner=ownerdev&type=notes",+        members = listOf(VaultMemberUi("ownerdev", "Owner", "owner"), VaultMemberUi("peer1", "Peer", "editor")),+        requests = listOf(VaultRequestUi("req1", "Requester")),+    )++    @Test fun accountDetailFullInteractions() {+        val actions = DetailRecorder()+        val snapshot = SnapshotStore.SnapshotMeta("v1", "notes", 1_700_000_000_000L, recordCount = 4, blobCount = 1)+        show {+            AccountDetailScreen(+                AccountDetailUiState(+                    accountName = "alice", providerId = "e2ee",+                    enabledTypes = setOf(DataType.CONTACTS, DataType.NOTES),+                    vaults = listOf(vaultState()), deviceId = "mydev",+                    syncErrorText = "Pull failed", snapshots = listOf(snapshot),+                ),+                actions,+            )+        }+        rule.onNodeWithText("alice").assertIsDisplayed()+        rule.onNodeWithText("Pull failed").assertIsDisplayed()+        rule.onRoot().captureToImage()+        // Toggle an enabled type off and a disabled type on+        rule.onNodeWithText(str(R.string.sync_contacts)).performClick()+        rule.onNodeWithText(str(R.string.sync_passwords)).performClick()+        assertTrue(actions.toggles.contains(Triple("alice", DataType.CONTACTS, false)), actions.toggles.toString())+        assertTrue(actions.toggles.contains(Triple("alice", DataType.PASSWORDS, true)), actions.toggles.toString())+        rule.onNodeWithText(str(R.string.sync_now)).performScrollTo().performClick()+        assertEquals("alice", actions.synced)+        // Vault section renders the vault and its create-vault flow+        rule.onNodeWithText("Home Notes").assertExists()+        rule.onNode(androidx.compose.ui.test.hasSetTextAction()).performTextInput("Trip")+        rule.onNodeWithText(str(R.string.vault_create_calendar)).performScrollTo().performClick()+        assertEquals("calendar" to "Trip", actions.created)+        // Share opens the dialog (members + requests are inside)+        rule.onNodeWithText(str(R.string.vault_share)).performScrollTo().performClick()+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        // Snapshot section: snapshot-now button exists; restore asks then confirms+        rule.onAllNodesWithText("Restore", substring = true).fetchSemanticsNodes().let { assertTrue(it.isNotEmpty()) }+        assertEquals(null, actions.removed)+        rule.onNodeWithText(str(R.string.remove_account)).performScrollTo().performClick()+        assertEquals("alice", actions.removed)+    }++    @Test fun vaultSharingStatesAndCreateValidation() {+        val actions = DetailRecorder()+        val content = show {+            VaultSharingSection(vaults = emptyList(), deviceId = "dev", safetyCode = null, computingCode = false, actions = actions)+        }+        rule.onNodeWithText(str(R.string.vaults_empty), substring = true).assertIsDisplayed()+        // Create buttons stay disabled until a title is typed+        rule.onNodeWithText(str(R.string.vault_create_contacts)).performClick()+        assertEquals(null, actions.created)+        rule.onNode(androidx.compose.ui.test.hasSetTextAction()).performTextInput("  Keys  ")+        rule.onNodeWithText(str(R.string.vault_create_contacts)).performClick()+        assertEquals("contacts" to "Keys", actions.created)+        // With a vault + safety code, the section shows the member data in the dialog+        content.value = {+            VaultSharingSection(+                vaults = listOf(vaultState()), deviceId = "mydev",+                safetyCode = "123 456", computingCode = true, actions = actions,+            )+        }+        rule.onNodeWithText("Home Notes").assertIsDisplayed()+        rule.onNodeWithText("notes").assertIsDisplayed()+        assertEquals(0, actions.refreshes)+        // Icon-only refresh button: second clickable in the vault row area+        rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().let { assertTrue(it.size >= 3) }+    }++    @Test fun settingsInteractions() {+        var interval: Long? = null; var wifi: Boolean? = null; var policy: String? = null; var backs = 0+        val actions = object : SettingsActions {+            override fun setInterval(minutes: Long) { interval = minutes }+            override fun setWifiOnly(value: Boolean) { wifi = value }+            override fun setConflictPolicy(p: String) { policy = p }+            override fun back() { backs++ }+        }+        show { SettingsScreen(SettingsUiState(intervalMinutes = 60, wifiOnly = false, conflictPolicy = "lww"), actions) }+        rule.onNodeWithText(str(R.string.global_interval), substring = true).assertIsDisplayed()+        rule.onNodeWithText(str(R.string.wifi_only)).performClick()+        assertEquals(true, wifi)+        rule.onNodeWithText(str(R.string.conflict_remote), substring = true).performClick()+        assertEquals("remote", policy)+        rule.onNodeWithText(str(R.string.conflict_lww), substring = true).performClick()+        assertEquals("lww", policy)+        // Interval field accepts a new value+        rule.onAllNodesWithText("60").fetchSemanticsNodes().let { assertTrue(it.isNotEmpty()) }+        assertEquals(0, backs); assertEquals(null, interval)+    }++    @Test fun accountsAndAddAccountInteractions() {+        var opened: String? = null; var synced: String? = null; var added: String? = null; var settings = 0; var addAccount = 0; var backs = 0+        val actions = object : AccountsActions {+            override fun openAccount(accountName: String) { opened = accountName }+            override fun syncNow(accountName: String) { synced = accountName }+            override fun openSettings() { settings++ }+            override fun openAddAccount() { addAccount++ }+        }+        val content = show {+            AccountsScreen(+                AccountsUiState(listOf(+                    AccountRow("alice", "e2ee", syncing = false, lastSyncedAt = "today"),+                    AccountRow("bob", "e2ee", syncing = true),+                    AccountRow("carol", "e2ee", lastSyncError = "boom"),+                )),+                actions,+            )+        }+        rule.onNodeWithText("alice").assertIsDisplayed()+        assertTrue(rule.onAllNodesWithText("Personal vaults").fetchSemanticsNodes().isNotEmpty())+        rule.onNodeWithText("boom").assertIsDisplayed()+        rule.onRoot().captureToImage()+        rule.onNodeWithText("alice").performClick()+        assertEquals("alice", opened)+        assertEquals(0, settings); assertEquals(0, addAccount); assertEquals(null, added); assertEquals(0, backs)+        // Sync button for a non-syncing row is an icon button beside the row+        rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().let { assertTrue(it.size >= 4) }++        val addActions = object : AddAccountActions {+            override fun addRelayAccount(providerId: String) { added = providerId }+            override fun back() { backs++ }+        }+        content.value = { AddAccountScreen(addActions) }+        rule.onNodeWithText("Personal vaults").performClick()+        assertEquals("e2ee", added)+    }++    @Test fun syncHealthSections() {+        var restored: SnapshotStore.SnapshotMeta? = null; var now = 0+        val meta = SnapshotStore.SnapshotMeta("v1", "notes", 1_700_000_000_000L, recordCount = 2, takenAtMs = 1_700_000_100_000L)+        show {+            androidx.compose.foundation.layout.Column {+                SyncErrorBanner("Relay unreachable")+                SnapshotSection(listOf(meta), restoring = true, onRestore = { restored = it }, onSnapshotNow = { now++ })+            }+        }+        rule.onNodeWithText("Relay unreachable").assertIsDisplayed()+        rule.onRoot().captureToImage()+        assertEquals(null, restored); assertEquals(0, now)+    }+}