Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault sync run logs to mobile app (#2159)
Leendert de Borst0ab45a41e600
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.ktindex 98127ed67..5e1dd5226 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt@@ -25,6 +25,7 @@ import kotlinx.coroutines.withContextimport net.aliasvault.app.qrscanner.QRScannerActivityimport net.aliasvault.app.vaultstore.AppErrorimport net.aliasvault.app.vaultstore.VaultStore+import net.aliasvault.app.vaultstore.VaultSyncRunLogimport net.aliasvault.app.vaultstore.interfaces.CryptoOperationCallbackimport net.aliasvault.app.vaultstore.keystoreprovider.AndroidKeystoreProviderimport net.aliasvault.app.vaultstore.storageprovider.AndroidStorageProvider@@ -1166,6 +1167,7 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :* @param promise The promise to resolve.*/@ReactMethod+ @Suppress("LongParameterList") // Signature is dictated by the TurboModule specoverride fun executeWebApiRequest(method: String,endpoint: String,@@ -1476,6 +1478,15 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :}}+ /**+ * The logs of the recent sync engine runs as JSON text, newest first (developer tools).+ * @param promise The promise to resolve+ */+ @ReactMethod+ override fun getVaultSyncLogs(promise: Promise) {+ promise.resolve(vaultStore.getVaultSyncLogs())+ }+/*** Classify the pending manifest migration (see VaultStore.getVaultMigrationStatus). Rejects with the native error code.* @param promise The promise to resolve with the migration kind.diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex 0b0d030b1..7d514f70b 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -811,6 +811,13 @@ class VaultStore(return sync.syncVaultWithServer(webApiService)}+ /**+ * The logs of the recent sync engine runs as JSON text, newest first (developer tools).+ */+ fun getVaultSyncLogs(): String {+ return VaultSyncRunLog.persisted(storageProvider)+ }+/*** Classify the pending manifest migration (see VaultSync.getVaultMigrationStatus).*/diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.ktindex 6b881ecf2..4bfb1e818 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt@@ -23,6 +23,7 @@ class VaultSync(*/@Suppress("TooGenericExceptionCaught")suspend fun syncVaultWithServer(webApiService: WebApiService): VaultSyncResult {+ val startNanos = System.nanoTime()val metadata = vaultStore.metadatametadata.setIsSyncing(true)try {@@ -61,6 +62,7 @@ class VaultSync()} finally {metadata.setIsSyncing(false)+ Log.d(TAG, "Sync finished in ${VaultSyncRunLog.elapsedMsSince(startNanos)}ms")}}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.ktindex ad02886c2..047110faa 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt@@ -42,6 +42,7 @@ class VaultSyncEngine(private var staging: SQLiteDatabase? = nullprivate var stagingFile: File? = null+ private var runLog = VaultSyncRunLog("")/*** Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`) and@@ -49,20 +50,30 @@ class VaultSyncEngine(*/suspend fun run(operation: String, forcePull: Boolean = false, encryptionKey: String? = null): JSONObject {JnaInitializer.ensureInitialized()+ val log = VaultSyncRunLog(operation)+ runLog = log+ var success: Boolean? = nullval session = VaultSyncSession(buildRequest(operation, forcePull, encryptionKey))try {while (true) {- val command = JSONObject(session.nextCommand())+ val commandJson = log.engine { session.nextCommand() }+ val command = log.json { JSONObject(commandJson) }val kind = command.optString("kind")if (kind == "done") {- return command.optJSONObject("result") ?: JSONObject()+ val result = command.optJSONObject("result") ?: JSONObject()+ success = if (result.has("success")) result.optBoolean("success") else null+ return result}+ val startNanos = System.nanoTime()val response = handle(kind, command)- session.resume(response.toString())+ log.recordCommand(kind, command, response, System.nanoTime() - startNanos)+ val responseJson = log.json { response.toString() }+ log.engine { session.resume(responseJson) }}} finally {closeStaging()session.destroy()+ log.finish(success, storageProvider)}}@@ -127,7 +138,7 @@ class VaultSyncEngine(JSONObject().put("cleared", cleared)}"log" -> {- Log.d(TAG, command.optString("message"))+ runLog.engineLine(command.optString("level", "log"), command.optString("message"))JSONObject()}else -> JSONObject().put("error", "Unknown engine command $kind")@@ -146,9 +157,9 @@ class VaultSyncEngine(headers["Content-Type"] = "application/json"}try {- val response = webApiService.executeVersionedRequest(+ val response = webApiService.executeRequest(method = command.optString("method", "GET"),- path = command.optString("path"),+ endpoint = command.optString("path"),body = body,headers = headers,requiresAuth = command.optBoolean("auth", true),@@ -221,7 +232,9 @@ class VaultSyncEngine()if (result.success && vaultStore.isVaultUnlocked()) {// The contract: after a store, the live database is the vault just stored.+ val reloadStartNanos = System.nanoTime()vaultStore.unlockVault()+ runLog.note("Live vault reloaded (decrypt and open) in ${VaultSyncRunLog.elapsedMsSince(reloadStartNanos)}ms")}return JSONObject().put("success", result.success).put("mutationSequence", result.mutationSequence)}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncRunLog.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncRunLog.ktnew file mode 100644index 000000000..60e1aa00c--- /dev/null+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncRunLog.kt@@ -0,0 +1,190 @@+package net.aliasvault.app.vaultstore++import android.util.Log+import net.aliasvault.app.vaultstore.storageprovider.StorageProvider+import org.json.JSONArray+import org.json.JSONObject+import java.util.Locale++/**+ * The log of one sync engine run for local performance analysis.+ */+class VaultSyncRunLog(private val operation: String) {+ companion object {+ const val TAG = "VaultSync"+ private const val ENGINE_TAG = "VaultSyncEngine"+ private const val SLOW_COMMAND_MS = 50L+ private const val KEPT_SYNCS = 5+ private const val MAX_ENTRIES = 20+ private val AUXILIARY_OPERATIONS = setOf("statusCheck", "migrationStatus", "resolveVaultKey")+ private const val NANOS_PER_MS = 1_000_000L+ private const val BYTES_PER_KB = 1024.0+ private val persistLock = Any()++ /**+ * Milliseconds since a [System.nanoTime] reading.+ */+ fun elapsedMsSince(startNanos: Long): Long = (System.nanoTime() - startNanos) / NANOS_PER_MS++ /**+ * The persisted run logs as JSON text, newest first.+ */+ fun persisted(storageProvider: StorageProvider): String = storageProvider.getSyncLogs() ?: "[]"++ /**+ * The size of a text payload (JSON or base64) for the logs, by character count.+ */+ private fun formatSize(value: Any?): String {+ val size = (value as? String)?.length ?: 0+ return when {+ size < BYTES_PER_KB -> "$size B"+ size < BYTES_PER_KB * BYTES_PER_KB -> String.format(Locale.US, "%.1f KB", size / BYTES_PER_KB)+ else -> String.format(Locale.US, "%.1f MB", size / (BYTES_PER_KB * BYTES_PER_KB))+ }+ }+ }++ private val startedAtMillis = System.currentTimeMillis()+ private val startedAtNanos = System.nanoTime()+ private val lines = mutableListOf<String>()+ private val commandNanos = mutableMapOf<String, Long>()+ private val commandCounts = mutableMapOf<String, Int>()+ private var engineNanos = 0L+ private var jsonNanos = 0L+ private var lastLineMs = 0L++ /**+ * Log a driver line and keep it.+ */+ fun note(message: String) {+ Log.d(TAG, keep(message))+ }++ /**+ * Log a line the Rust engine emitted and keep it; `phase` and `warn` lines keep their level in the text.+ */+ fun engineLine(level: String, message: String) {+ Log.d(ENGINE_TAG, keep(if (level == "log") message else "[$level] $message"))+ }++ /**+ * Keep a line, prefixed with its offset from the run start and the time since the previous line. The engine logs+ * before and after each heavy step (decrypt, canonicalize, merge, materialize, compress), so that gap is the step's time.+ */+ private fun keep(text: String): String {+ val offsetMs = elapsedMsSince(startedAtNanos)+ val line = "+${offsetMs}ms (Δ${offsetMs - lastLineMs}ms) $text"+ lastLineMs = offsetMs+ lines.add(line)+ return line+ }++ /**+ * Run [block], counting its time as time inside the Rust engine.+ */+ fun <T> engine(block: () -> T): T {+ val startNanos = System.nanoTime()+ try {+ return block()+ } finally {+ engineNanos += System.nanoTime() - startNanos+ }+ }++ /**+ * Run [block], counting its time as native JSON parsing and serialization.+ */+ fun <T> json(block: () -> T): T {+ val startNanos = System.nanoTime()+ try {+ return block()+ } finally {+ jsonNanos += System.nanoTime() - startNanos+ }+ }++ /**+ * Count one handled command, and log it on its own when it is a transfer or slow.+ */+ fun recordCommand(kind: String, command: JSONObject, response: JSONObject, nanos: Long) {+ commandNanos[kind] = (commandNanos[kind] ?: 0L) + nanos+ commandCounts[kind] = (commandCounts[kind] ?: 0) + 1+ describe(kind, command, response, nanos / NANOS_PER_MS)?.let { note(it) }+ }++ /**+ * Log where the run's time went and persist the run.+ */+ fun finish(success: Boolean?, storageProvider: StorageProvider) {+ val totalMs = elapsedMsSince(startedAtNanos)+ val hostMs = commandNanos.values.sum() / NANOS_PER_MS+ val parts = commandNanos.entries.sortedByDescending { it.value }+ .joinToString(", ") { "${it.key} ${commandCounts[it.key]}x ${it.value / NANOS_PER_MS}ms" }+ note("$operation took ${totalMs}ms: engine ${engineNanos / NANOS_PER_MS}ms, host ${hostMs}ms ($parts), json ${jsonNanos / NANOS_PER_MS}ms")++ val entry = JSONObject()+ .put("operation", operation)+ .put("startedAt", startedAtMillis)+ .put("durationMs", totalMs)+ .put("success", success ?: JSONObject.NULL)+ .put("lines", JSONArray(lines))+ persist(entry, storageProvider)+ }++ /**+ * One line for a command relevant for performance analysis, or null for unrelated calls.+ */+ private fun describe(kind: String, command: JSONObject, response: JSONObject, ms: Long): String? {+ val took = "$kind took ${ms}ms"+ if (response.has("error")) {+ return "$took: failed (${response.optString("error")})"+ }+ val slow = ms >= SLOW_COMMAND_MS+ val db = command.optString("db")+ return when (kind) {+ "http" -> {+ val request = "${command.optString("method", "GET")} ${command.optString("path")}"+ val status = response.optInt("status")+ if (status == 0) {+ "$took: $request failed (${response.optString("transportError", "no response")})"+ } else {+ "$took: $request $status, sent ${formatSize(command.opt("body"))}, received ${formatSize(response.opt("body"))}"+ }+ }+ "vaultStore" -> "$took: ${formatSize(command.opt("encryptedBlob"))}"+ "vaultLoad" -> "$took: ${formatSize(response.opt("encryptedBlob"))}"+ "dbOpen" -> "$took: ${if (command.isNull("bytes")) "fresh schema" else formatSize(command.opt("bytes"))}"+ "dbExport" -> "$took: $db ${formatSize(response.opt("bytes"))}"+ "dbExec" -> if (slow) "$took: ${command.optJSONArray("statements")?.length() ?: 0} statement(s) on $db" else null+ "dbQuery" -> if (slow) "$took: ${response.optJSONArray("rows")?.length() ?: 0} row(s) from $db" else null+ else -> if (slow) took else null+ }+ }++ /**+ * Prepend the run to the persisted log, keeping the last [KEPT_SYNCS] syncs.+ */+ @Suppress("TooGenericExceptionCaught")+ private fun persist(entry: JSONObject, storageProvider: StorageProvider) {+ try {+ synchronized(persistLock) {+ val existing = storageProvider.getSyncLogs()?.let { JSONArray(it) } ?: JSONArray()+ val kept = JSONArray().put(entry)+ var syncs = if (operation in AUXILIARY_OPERATIONS) 0 else 1+ for (index in 0 until existing.length()) {+ if (syncs >= KEPT_SYNCS || kept.length() >= MAX_ENTRIES) {+ break+ }+ val previous = existing.getJSONObject(index)+ kept.put(previous)+ if (previous.optString("operation") !in AUXILIARY_OPERATIONS) {+ syncs+++ }+ }+ storageProvider.setSyncLogs(kept.toString())+ }+ } catch (e: Exception) {+ Log.w(TAG, "Failed to persist the sync log", e)+ }+ }+}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.ktindex 188634ab0..dc921282c 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/AndroidStorageProvider.kt@@ -240,4 +240,16 @@ class AndroidStorageProvider(private val context: Context) : StorageProvider {}// endregion++ // region Sync logs++ override fun getSyncLogs(): String? {+ return context.getSharedPreferences("aliasvault_sync_logs", Context.MODE_PRIVATE).getString("logs", null)+ }++ override fun setSyncLogs(json: String) {+ context.getSharedPreferences("aliasvault_sync_logs", Context.MODE_PRIVATE).edit { putString("logs", json) }+ }++ // endregion}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.ktindex bf5bec3a6..6f9faa83d 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/StorageProvider.kt@@ -209,4 +209,20 @@ interface StorageProvider {fun clearSyncEngineState()// endregion++ // region Sync logs++ /**+ * Get the persisted logs of the recent sync engine runs.+ * @return The JSON array text, newest first, or null when none were recorded+ */+ fun getSyncLogs(): String?++ /**+ * Set the persisted logs of the recent sync engine runs.+ * @param json The JSON array text, newest first+ */+ fun setSyncLogs(json: String)++ // endregion}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.ktindex 5d39f85c5..ac4b28b0f 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/storageprovider/TestStorageProvider.kt@@ -169,4 +169,16 @@ class TestStorageProvider : StorageProvider {}// endregion++ // region Sync logs++ private var syncLogs: String? = null++ override fun getSyncLogs(): String? = syncLogs++ override fun setSyncLogs(json: String) {+ syncLogs = json+ }++ // endregion}diff --git a/apps/mobile-app/app/(tabs)/settings/_layout.tsx b/apps/mobile-app/app/(tabs)/settings/_layout.tsxindex d2f1e918a..9637d48c5 100644--- a/apps/mobile-app/app/(tabs)/settings/_layout.tsx+++ b/apps/mobile-app/app/(tabs)/settings/_layout.tsx@@ -135,15 +135,29 @@ export default function SettingsLayout(): React.ReactNode {...defaultHeaderOptions,}}/>- {/* Developer only screen. Note: not required to be translated. */}+ {/* Developer only screens. Note: not required to be translated. */}<Stack.Screen- name="developer-tools"+ name="developer-tools/index"options={{title: 'Developer tools',headerBackTitle: t('settings.title'),...defaultHeaderOptions,}}/>+ <Stack.Screen+ name="developer-tools/app-review"+ options={{+ title: 'App review',+ ...defaultHeaderOptions,+ }}+ />+ <Stack.Screen+ name="developer-tools/sync-logs"+ options={{+ title: 'Sync logs',+ ...defaultHeaderOptions,+ }}+ /><Stack.Screenname="qr-scanner"options={{diff --git a/apps/mobile-app/app/(tabs)/settings/developer-tools.tsx b/apps/mobile-app/app/(tabs)/settings/developer-tools/app-review.tsxsimilarity index 79%rename from apps/mobile-app/app/(tabs)/settings/developer-tools.tsxrename to apps/mobile-app/app/(tabs)/settings/developer-tools/app-review.tsxindex a3090b02f..18a22c256 100644--- a/apps/mobile-app/app/(tabs)/settings/developer-tools.tsx+++ b/apps/mobile-app/app/(tabs)/settings/developer-tools/app-review.tsx@@ -1,12 +1,10 @@import { Ionicons } from '@expo/vector-icons';-import { router } from 'expo-router';import { useCallback } from 'react';import { StyleSheet, View } from 'react-native';import Toast from 'react-native-toast-message';import { useAppReviewDebug } from '@/hooks/useAppReviewPrompt';import { useColors } from '@/hooks/useColorScheme';-import { useDeveloperToolsUnlock } from '@/hooks/useDeveloperToolsUnlock';import { ThemedButton } from '@/components/themed/ThemedButton';import { ThemedContainer } from '@/components/themed/ThemedContainer';@@ -14,7 +12,7 @@ import { ThemedScrollView } from '@/components/themed/ThemedScrollView';import { ThemedText } from '@/components/themed/ThemedText';/**- * Row in one of the state readouts below.+ * Row in the review state readout below.*/type StateRow = {label: string;@@ -23,12 +21,11 @@ type StateRow = {};/**- * Developer tools screen. Note: not required to be translated.+ * Developer tools: the app store review prompt state. Note: not required to be translated.*/-export default function DeveloperToolsScreen(): React.ReactNode {+export default function AppReviewDebugScreen(): React.ReactNode {const colors = useColors();const { state: reviewState, reset: resetReviewState, requestNow: requestReviewNow } = useAppReviewDebug();- const { hide: hideDeveloperTools } = useDeveloperToolsUnlock();/*** Ask the OS for its review prompt right now, skipping every condition.@@ -51,15 +48,6 @@ export default function DeveloperToolsScreen(): React.ReactNode {});}, [resetReviewState]);- /**- * Hide the developer tools again, which also puts the unlock gesture back at the start. Useful- * to get the app into a clean state for app store screenshots.- */- const handleHideDeveloperTools = useCallback(async (): Promise<void> => {- await hideDeveloperTools();- router.back();- }, [hideDeveloperTools]);-const reviewRows: StateRow[] = reviewState ? [{label: 'Review prompt available',@@ -138,26 +126,18 @@ export default function DeveloperToolsScreen(): React.ReactNode {section: {backgroundColor: colors.accentBackground,borderRadius: 10,- marginTop: 8,+ marginTop: 16,overflow: 'hidden',},- sectionTitle: {- color: colors.textMuted,- fontSize: 13,- fontWeight: '600',- marginTop: 24,- textTransform: 'uppercase',- },});return (<ThemedContainer><ThemedScrollView><ThemedText style={styles.headerText}>- These tools are for development and manual testing purposes.+ The conditions that decide when the app store review prompt is shown.</ThemedText>- <ThemedText style={styles.sectionTitle}>App store review</ThemedText>{reviewRows.length > 0 && (<View style={styles.section}>{reviewRows.map((row, index) => (@@ -188,13 +168,6 @@ export default function DeveloperToolsScreen(): React.ReactNode {title="Reset app review state"onPress={handleResetReviewState}/>-- <ThemedText style={styles.sectionTitle}>Developer tools</ThemedText>- <ThemedButton- style={styles.buttonSecondary}- title="Hide developer tools"- onPress={handleHideDeveloperTools}- /></ThemedScrollView></ThemedContainer>);diff --git a/apps/mobile-app/app/(tabs)/settings/developer-tools/index.tsx b/apps/mobile-app/app/(tabs)/settings/developer-tools/index.tsxnew file mode 100644index 000000000..27b2c4be6--- /dev/null+++ b/apps/mobile-app/app/(tabs)/settings/developer-tools/index.tsx@@ -0,0 +1,128 @@+import { Ionicons } from '@expo/vector-icons';+import { Href, router } from 'expo-router';+import { useCallback } from 'react';+import { StyleSheet, TouchableOpacity, View } from 'react-native';++import { useColors } from '@/hooks/useColorScheme';+import { useDeveloperToolsUnlock } from '@/hooks/useDeveloperToolsUnlock';+import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';++import { ThemedButton } from '@/components/themed/ThemedButton';+import { ThemedContainer } from '@/components/themed/ThemedContainer';+import { ThemedScrollView } from '@/components/themed/ThemedScrollView';+import { ThemedText } from '@/components/themed/ThemedText';++/**+ * A debug page listed in the developer tools menu.+ */+type DeveloperToolsPage = {+ title: string;+ icon: keyof typeof Ionicons.glyphMap;+ route: Href;+};++const developerToolsPages: DeveloperToolsPage[] = [+ { title: 'Sync logs', icon: 'pulse-outline', route: '/(tabs)/settings/developer-tools/sync-logs' },+ { title: 'App review prompt', icon: 'star-outline', route: '/(tabs)/settings/developer-tools/app-review' },+];++/**+ * Developer tools menu: every debug page, and the switch to hide the tools again. Note: not required to be translated.+ */+export default function DeveloperToolsScreen(): React.ReactNode {+ const colors = useColors();+ const navigate = useNavigationDebounce();+ const { hide: hideDeveloperTools } = useDeveloperToolsUnlock();++ /**+ * Hide the developer tools again.+ */+ const handleHideDeveloperTools = useCallback(async (): Promise<void> => {+ await hideDeveloperTools();+ router.back();+ }, [hideDeveloperTools]);++ const styles = StyleSheet.create({+ buttonSecondary: {+ marginTop: 24,+ backgroundColor: colors.accentBackground,+ },+ headerText: {+ color: colors.textMuted,+ fontSize: 13,+ lineHeight: 20,+ },+ section: {+ backgroundColor: colors.accentBackground,+ borderRadius: 10,+ marginTop: 16,+ overflow: 'hidden',+ },+ separator: {+ backgroundColor: colors.accentBorder,+ height: StyleSheet.hairlineWidth,+ marginLeft: 52,+ },+ settingItem: {+ alignItems: 'center',+ backgroundColor: colors.accentBackground,+ flexDirection: 'row',+ paddingHorizontal: 16,+ paddingVertical: 6,+ },+ settingItemContent: {+ alignItems: 'center',+ flex: 1,+ flexDirection: 'row',+ paddingVertical: 10,+ },+ settingItemIcon: {+ alignItems: 'center',+ height: 24,+ justifyContent: 'center',+ marginRight: 12,+ width: 24,+ },+ settingItemText: {+ color: colors.text,+ flex: 1,+ fontSize: 16,+ },+ });++ return (+ <ThemedContainer>+ <ThemedScrollView>+ <ThemedText style={styles.headerText}>+ These tools are for development and manual testing purposes.+ </ThemedText>++ <View style={styles.section}>+ {developerToolsPages.map((page, index) => (+ <View key={page.title}>+ {index > 0 && <View style={styles.separator} />}+ <TouchableOpacity+ style={styles.settingItem}+ onPress={() => navigate(() => router.push(page.route))}+ >+ <View style={styles.settingItemIcon}>+ <Ionicons name={page.icon} size={20} color={colors.text} />+ </View>+ <View style={styles.settingItemContent}>+ <ThemedText style={styles.settingItemText}>{page.title}</ThemedText>+ <Ionicons name="chevron-forward" size={20} color={colors.textMuted} />+ </View>+ </TouchableOpacity>+ </View>+ ))}+ </View>++ <ThemedButton+ style={styles.buttonSecondary}+ title="Hide developer tools"+ onPress={handleHideDeveloperTools}+ />+ </ThemedScrollView>+ </ThemedContainer>+ );+}diff --git a/apps/mobile-app/app/(tabs)/settings/developer-tools/sync-logs.tsx b/apps/mobile-app/app/(tabs)/settings/developer-tools/sync-logs.tsxnew file mode 100644index 000000000..d628b45d3--- /dev/null+++ b/apps/mobile-app/app/(tabs)/settings/developer-tools/sync-logs.tsx@@ -0,0 +1,152 @@+import { useFocusEffect } from 'expo-router';+import { useCallback, useState } from 'react';+import { Platform, StyleSheet, View } from 'react-native';+import Toast from 'react-native-toast-message';++import { copyToClipboard } from '@/utils/ClipboardUtility';++import { useColors } from '@/hooks/useColorScheme';++import { ThemedButton } from '@/components/themed/ThemedButton';+import { ThemedContainer } from '@/components/themed/ThemedContainer';+import { ThemedScrollView } from '@/components/themed/ThemedScrollView';+import { ThemedText } from '@/components/themed/ThemedText';+import NativeVaultManager from '@/specs/NativeVaultManager';++/**+ * A persisted sync engine run (recorded by the native layer).+ */+type VaultSyncLogEntry = {+ operation: string;+ startedAt: number;+ durationMs: number;+ success: boolean | null;+ lines: string[];+};++/**+ * The outcome of a run.+ */+function formatOutcome(success: boolean | null): string {+ if (success === null) {+ return 'no result';+ }+ return success ? 'success' : 'failed';+}++/**+ * Header of a run.+ */+function formatHeader(entry: VaultSyncLogEntry): string {+ return `${entry.operation} at ${new Date(entry.startedAt).toLocaleString()}: ${entry.durationMs}ms, ${formatOutcome(entry.success)}`;+}++/**+ * Developer tools: the logs of the recent vault syncs. Note: not required to be translated.+ */+export default function SyncLogsScreen(): React.ReactNode {+ const colors = useColors();+ const [entries, setEntries] = useState<VaultSyncLogEntry[]>([]);++ /**+ * Load the persisted run logs.+ */+ const loadLogs = useCallback(async (): Promise<void> => {+ const json = await NativeVaultManager.getVaultSyncLogs();+ setEntries(JSON.parse(json) as VaultSyncLogEntry[]);+ }, []);++ useFocusEffect(+ useCallback(() => {+ loadLogs();+ }, [loadLogs])+ );++ /**+ * Copy every run's log to the clipboard.+ */+ const handleCopyLogs = useCallback(async (): Promise<void> => {+ if (entries.length === 0) {+ return;+ }+ await copyToClipboard(entries.map((entry) => `${formatHeader(entry)}\n${entry.lines.join('\n')}`).join('\n\n'));++ Toast.show({+ type: 'success',+ text1: 'Sync logs copied',+ position: 'bottom',+ visibilityTime: 2000,+ });+ }, [entries]);++ const styles = StyleSheet.create({+ button: {+ marginTop: 12,+ backgroundColor: colors.primary,+ },+ buttonSecondary: {+ marginTop: 12,+ backgroundColor: colors.accentBackground,+ },+ emptyText: {+ color: colors.textMuted,+ fontSize: 15,+ marginTop: 24,+ textAlign: 'center',+ },+ entryHeader: {+ color: colors.text,+ fontSize: 13,+ fontWeight: '600',+ marginBottom: 8,+ },+ headerText: {+ color: colors.textMuted,+ fontSize: 13,+ lineHeight: 20,+ },+ logText: {+ color: colors.text,+ fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',+ fontSize: 11,+ lineHeight: 16,+ },+ section: {+ backgroundColor: colors.accentBackground,+ borderRadius: 10,+ marginTop: 16,+ padding: 12,+ },+ });++ return (+ <ThemedContainer>+ <ThemedScrollView>+ <ThemedText style={styles.headerText}>+ The last 5 vault syncs on this device, newest first, with the status checks in between.+ </ThemedText>++ <ThemedButton+ style={styles.button}+ title="Copy logs"+ onPress={handleCopyLogs}+ />+ <ThemedButton+ style={styles.buttonSecondary}+ title="Refresh"+ onPress={loadLogs}+ />++ {entries.length === 0 && (+ <ThemedText style={styles.emptyText}>No sync logs recorded yet.</ThemedText>+ )}+ {entries.map((entry) => (+ <View key={`${entry.startedAt}-${entry.operation}`} style={styles.section}>+ <ThemedText style={styles.entryHeader}>{formatHeader(entry)}</ThemedText>+ <ThemedText selectable style={styles.logText}>{entry.lines.join('\n')}</ThemedText>+ </View>+ ))}+ </ThemedScrollView>+ </ThemedContainer>+ );+}diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swiftindex c8c80de02..d2c371aac 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift@@ -26,6 +26,7 @@ public final class VaultSyncEngine {private let vaultStore: VaultStoreprivate let webApiService: WebApiServiceprivate var staging: OpaquePointer?+ private var runLog = VaultSyncRunLog(operation: "")public init(vaultStore: VaultStore, webApiService: WebApiService) {self.vaultStore = vaultStore@@ -39,17 +40,29 @@ public final class VaultSyncEngine {/// Run one engine operation (`fullSync`, `statusCheck`, `migrationStatus`, `migrateManifest`, `resolveVaultKey`) and/// return its result. `encryptionKey` overrides the store's key for the one operation that runs before it is known.public func run(operation: String, forcePull: Bool = false, encryptionKey: String? = nil) async throws -> [String: Any] {+ let log = VaultSyncRunLog(operation: operation)+ runLog = log+ var finalResult: [String: Any]?let session = try VaultSyncSession(requestJson: try buildRequest(operation: operation, forcePull: forcePull, encryptionKey: encryptionKey))- defer { closeStaging() }+ defer {+ closeStaging()+ log.finish(result: finalResult, userDefaults: vaultStore.userDefaults)+ }while true {- let command = try Self.parseJson(try session.nextCommand())+ let commandJson = try log.engine { try session.nextCommand() }+ let command = try log.json { try Self.parseJson(commandJson) }let kind = command["kind"] as? String ?? ""if kind == "done" {- return command["result"] as? [String: Any] ?? [:]+ let result = command["result"] as? [String: Any] ?? [:]+ finalResult = result+ return result}+ let commandStartedAt = Date()let response = await handle(kind: kind, command: command)- try session.resume(responseJson: try Self.serializeJson(response))+ log.recordCommand(kind, command: command, response: response, since: commandStartedAt)+ let responseJson = try log.json { try Self.serializeJson(response) }+ try log.engine { try session.resume(responseJson: responseJson) }}}@@ -118,7 +131,7 @@ public final class VaultSyncEngine {let cleared = vaultStore.markVaultClean(mutationSeqAtStart: command["mutationSeqAtStart"] as? Int ?? 0, newServerRevision: vaultStore.getCurrentVaultRevisionNumber())return ["cleared": cleared]case "log":- print("[VaultSyncEngine] [\(command["level"] as? String ?? "log")] \(command["message"] as? String ?? "")")+ runLog.engineLine(level: command["level"] as? String ?? "log", message: command["message"] as? String ?? "")return [:]default:return ["error": "Unknown engine command \(kind)"]@@ -140,7 +153,7 @@ public final class VaultSyncEngine {headers["Content-Type"] = "application/json"}do {- let response = try await webApiService.executeVersionedRequest(method: method, path: path, body: body, headers: headers, requiresAuth: auth)+ let response = try await webApiService.executeRequest(method: method, endpoint: path, body: body, headers: headers, requiresAuth: auth)return ["status": response.statusCode, "body": response.body]} catch {let timedOut = (error as? URLError)?.code == .timedOut@@ -218,7 +231,9 @@ public final class VaultSyncEngine {)if result.success && vaultStore.isVaultUnlocked {// The contract: after a store, the live database is the vault just stored.+ let reloadStartedAt = Date()try vaultStore.unlockVault()+ runLog.note("Live vault reloaded (decrypt and open) in \(VaultSyncRunLog.elapsedMs(since: reloadStartedAt))ms")}return ["success": result.success, "mutationSequence": result.mutationSequence]}diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncRunLog.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncRunLog.swiftnew file mode 100644index 000000000..159a7b261--- /dev/null+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncRunLog.swift@@ -0,0 +1,167 @@+import Foundation+import VaultUtils++/// The log of one sync engine run for local performance analysis.+internal final class VaultSyncRunLog {+ private static let slowCommandMs = 50.0+ private static let keptSyncs = 5+ private static let maxEntries = 20+ private static let auxiliaryOperations: Set<String> = ["statusCheck", "migrationStatus", "resolveVaultKey"]+ private static let persistLock = NSLock()++ /// Milliseconds since `date`.+ static func elapsedMs(since date: Date) -> Int {+ return Int(Date().timeIntervalSince(date) * 1000)+ }++ /// The persisted run logs as JSON text, newest first.+ static func persistedLogs(in userDefaults: UserDefaults) -> String {+ return userDefaults.string(forKey: VaultConstants.syncLogsKey) ?? "[]"+ }++ /// The size of a text payload (JSON or base64) for the logs, by UTF-8 byte count.+ private static func formatSize(_ value: Any?) -> String {+ let size = (value as? String)?.utf8.count ?? 0+ if size < 1024 {+ return "\(size) B"+ }+ if size < 1024 * 1024 {+ return String(format: "%.1f KB", Double(size) / 1024)+ }+ return String(format: "%.1f MB", Double(size) / (1024 * 1024))+ }++ private let operation: String+ private let startedAt = Date()+ private var lines: [String] = []+ private var commandTimings: [String: (count: Int, totalMs: Double)] = [:]+ private var engineMs = 0.0+ private var jsonMs = 0.0+ private var lastLineMs = 0++ init(operation: String) {+ self.operation = operation+ }++ /// Print a driver line and keep it.+ func note(_ message: String) {+ print("[VaultSync] \(keep(message))")+ }++ /// Print a line the Rust engine emitted and keep it; `phase` and `warn` lines keep their level in the text.+ func engineLine(level: String, message: String) {+ print("[VaultSyncEngine] \(keep(level == "log" ? message : "[\(level)] \(message)"))")+ }++ /// Keep a line, prefixed with its offset from the run start and the time since the previous line. The engine logs+ /// before and after each heavy step (decrypt, canonicalize, merge, materialize, compress), so that gap is the step's time.+ private func keep(_ text: String) -> String {+ let offsetMs = Self.elapsedMs(since: startedAt)+ let line = "+\(offsetMs)ms (Δ\(offsetMs - lastLineMs)ms) \(text)"+ lastLineMs = offsetMs+ lines.append(line)+ return line+ }++ /// Run `body`, counting its time as time inside the Rust engine.+ func engine<T>(_ body: () throws -> T) rethrows -> T {+ let bodyStartedAt = Date()+ defer { engineMs += Date().timeIntervalSince(bodyStartedAt) * 1000 }+ return try body()+ }++ /// Run `body`, counting its time as native JSON parsing and serialization.+ func json<T>(_ body: () throws -> T) rethrows -> T {+ let bodyStartedAt = Date()+ defer { jsonMs += Date().timeIntervalSince(bodyStartedAt) * 1000 }+ return try body()+ }++ /// Count one handled command, and log it on its own when it is a transfer or slow.+ func recordCommand(_ kind: String, command: [String: Any], response: [String: Any], since commandStartedAt: Date) {+ let durationMs = Date().timeIntervalSince(commandStartedAt) * 1000+ let timing = commandTimings[kind] ?? (count: 0, totalMs: 0)+ commandTimings[kind] = (count: timing.count + 1, totalMs: timing.totalMs + durationMs)+ if let line = describe(kind: kind, command: command, response: response, durationMs: durationMs) {+ note(line)+ }+ }++ /// Log where the run's time went and persist the run.+ func finish(result: [String: Any]?, userDefaults: UserDefaults) {+ let totalMs = Self.elapsedMs(since: startedAt)+ let hostMs = commandTimings.values.reduce(0) { $0 + $1.totalMs }+ let parts = commandTimings.sorted { $0.value.totalMs > $1.value.totalMs }.map { "\($0.key) \($0.value.count)x \(Int($0.value.totalMs))ms" }+ note("\(operation) took \(totalMs)ms: engine \(Int(engineMs))ms, host \(Int(hostMs))ms (\(parts.joined(separator: ", "))), json \(Int(jsonMs))ms")++ let entry: [String: Any] = [+ "operation": operation,+ "startedAt": Int(startedAt.timeIntervalSince1970 * 1000),+ "durationMs": totalMs,+ "success": result?["success"] ?? NSNull(),+ "lines": lines+ ]+ persist(entry, in: userDefaults)+ }++ /// One line for a command relevant for performance analysis, or nil for unrelated calls.+ private func describe(kind: String, command: [String: Any], response: [String: Any], durationMs: Double) -> String? {+ let took = "\(kind) took \(Int(durationMs))ms"+ if let error = response["error"] as? String {+ return "\(took): failed (\(error))"+ }+ let slow = durationMs >= Self.slowCommandMs+ let database = command["db"] as? String ?? ""+ switch kind {+ case "http":+ let request = "\(command["method"] as? String ?? "GET") \(command["path"] as? String ?? "")"+ guard let status = response["status"] as? Int, status != 0 else {+ return "\(took): \(request) failed (\(response["transportError"] as? String ?? "no response"))"+ }+ return "\(took): \(request) \(status), sent \(Self.formatSize(command["body"])), received \(Self.formatSize(response["body"]))"+ case "vaultStore":+ return "\(took): \(Self.formatSize(command["encryptedBlob"]))"+ case "vaultLoad":+ return "\(took): \(Self.formatSize(response["encryptedBlob"]))"+ case "dbOpen":+ return "\(took): \(command["bytes"] is String ? Self.formatSize(command["bytes"]) : "fresh schema")"+ case "dbExport":+ return "\(took): \(database) \(Self.formatSize(response["bytes"]))"+ case "dbExec":+ return slow ? "\(took): \((command["statements"] as? [Any])?.count ?? 0) statement(s) on \(database)" : nil+ case "dbQuery":+ return slow ? "\(took): \((response["rows"] as? [Any])?.count ?? 0) row(s) from \(database)" : nil+ default:+ return slow ? took : nil+ }+ }++ /// Prepend the run to the persisted log, keeping the last `keptSyncs` syncs.+ private func persist(_ entry: [String: Any], in userDefaults: UserDefaults) {+ Self.persistLock.lock()+ defer { Self.persistLock.unlock() }++ var existing: [[String: Any]] = []+ if let json = userDefaults.string(forKey: VaultConstants.syncLogsKey), let data = json.data(using: .utf8) {+ existing = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] ?? []+ }++ var kept = [entry]+ var syncs = Self.auxiliaryOperations.contains(operation) ? 0 : 1+ for previous in existing {+ if syncs >= Self.keptSyncs || kept.count >= Self.maxEntries {+ break+ }+ kept.append(previous)+ if !Self.auxiliaryOperations.contains(previous["operation"] as? String ?? "") {+ syncs += 1+ }+ }++ guard JSONSerialization.isValidJSONObject(kept), let data = try? JSONSerialization.data(withJSONObject: kept), let json = String(data: data, encoding: .utf8) else {+ print("[VaultSync] Failed to persist the sync log")+ return+ }+ userDefaults.set(json, forKey: VaultConstants.syncLogsKey)+ }+}