💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Merge llmchat-common-rust and migrate ensu bindings
Prateek Sunal3c91b2802c71
diff --cc mobile/native/android/apps/ensu/README.mdindex d4d4bb5b49,0000000000..d65c1c0fecmode 100644,000000..100644--- a/mobile/native/android/apps/ensu/README.md+++ b/mobile/native/android/apps/ensu/README.md@@@ -1,96 -1,0 +1,98 @@@+# Ensu Android++## Prerequisites++- Android Studio or command-line tools+- JDK 17+- Android SDK with API level 35 (install in a default location or set `ANDROID_HOME`/`ANDROID_SDK_ROOT`)+- Android NDK (install via `sdkmanager "ndk;<version>"`; optionally set `NDK_VERSION` to select a specific version)+- Rust toolchain and `cargo-ndk` (`cargo install cargo-ndk`)+- Python 3 (used to patch llama.cpp mtmd sources)++## Building++### 1. Build Rust Libraries++Before building the Android app, compile the Rust native libraries. Ensure the SDK is installed in a default location or set `ANDROID_HOME`/`ANDROID_SDK_ROOT` to the SDK containing an NDK. Optionally set `NDK_VERSION` to select a specific version. The build script applies the llama.cpp mtmd patch; set `APPLY_LLAMA_MTMD_PATCH=0` to skip it.++```bash+cd mobile/native/android/packages/rust/tool+./build_android.sh+```+- This script produces the JNI `.so` artifacts in `android/packages/rust/src/main/jniLibs/` (including `libcore_uniffi.so`, `libinference_rs_uniffi.so`, `libllmchat_db_uniffi.so`, and `libllmchat_sync_uniffi.so`).++This script produces the JNI `.so` artifacts in `android/packages/rust/src/main/jniLibs/` (including `libcore.so`, `libinference.so`, `libdb.so`, and `libsync.so`).+The UniFFI Kotlin bindings are generated separately into:- - `android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/core_uniffi.kt`- - `android/packages/rust/src/main/kotlin/io/ente/labs/*/*_uniffi.kt`++- `android/apps/ensu/crypto-auth-core/src/main/java/io/ente/ensu/crypto/core.kt`++- `android/packages/rust/src/main/kotlin/io/ente/labs/ensu_db/db.kt`++- `android/packages/rust/src/main/kotlin/io/ente/labs/ensu_sync/sync.kt`++- `android/packages/rust/src/main/kotlin/io/ente/labs/inference_rs/inference.kt`++These generated files are gitignored. If bindings are missing, rebuild the corresponding- `rust/uniffi/*` and `rust/llmchat/uniffi/*` crates and run `uniffi-bindgen generate` for Kotlin (see each crate’s++`rust/uniffi/core` and `rust/uniffi/ensu/*` crates and run `uniffi-bindgen generate` for Kotlin (see each crate’s+`uniffi.toml` for package names).++### 2. Build Debug APK++```bash+cd mobile/native/android/apps/ensu+./gradlew :app-ui:assembleDebug+```++Output: `app-ui/build/outputs/apk/debug/app-ui-debug.apk`++### 3. Build Release APK++```bash+./gradlew :app-ui:assembleRelease+```++Output: `app-ui/build/outputs/apk/release/app-ui-release.apk`++Note: Release builds use a debug keystore located at `debug.keystore`. For production releases, configure your own signing keys in `app-ui/build.gradle.kts`.++## Installation++### Install Debug Build++```bash+./gradlew :app-ui:installDebug+```++Or via adb:++```bash+adb install -r app-ui/build/outputs/apk/debug/app-ui-debug.apk+```++### Install Release Build++```bash+adb install -r app-ui/build/outputs/apk/release/app-ui-release.apk+```++Note: If upgrading from a differently signed build, uninstall first:++```bash+adb uninstall io.ente.ensu+```++## Custom API Endpoint++Set `ENTE_API_ENDPOINT` to override the default (`https://api.ente.io`).++```bash+ENTE_API_ENDPOINT=https://your-endpoint ./gradlew :app-ui:installDebug+```++Or via Gradle property:++```bash+./gradlew :app-ui:installDebug -PENTE_API_ENDPOINT=https://your-endpoint+```++## Project Structure++- `app-ui/` - Main application module (Compose UI)+- `domain/` - Domain layer (business logic, state management)+- `data/` - Data layer (repositories, network, storage)+- `crypto-auth-core/` - Cryptographic authentication utilitiesdiff --cc mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.ktindex 8b5b9a2727,0000000000..78b85a1769mode 100644,000000..100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt@@@ -1,239 -1,0 +1,239 @@@+package io.ente.ensu.data.chat++import android.content.Context+import io.ente.ensu.data.storage.CredentialStore+import io.ente.ensu.data.storage.FilePathManager+import io.ente.ensu.domain.chat.ChatRepository+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.AttachmentType+import io.ente.ensu.domain.model.ChatMessage+import io.ente.ensu.domain.model.ChatSession+import io.ente.ensu.domain.model.MessageAuthor+import io.ente.ensu.domain.model.sessionTitleFromText- import io.ente.labs.llmchat_db.AttachmentKind- import io.ente.labs.llmchat_db.AttachmentMeta- import io.ente.labs.llmchat_db.DbException- import io.ente.labs.llmchat_db.LlmChatDb++import io.ente.labs.ensu_db.AttachmentKind++import io.ente.labs.ensu_db.AttachmentMeta++import io.ente.labs.ensu_db.DbException++import io.ente.labs.ensu_db.EnsuDb+import java.io.File++class RustChatRepository(+ context: Context,+ private val credentialStore: CredentialStore+) : ChatRepository {++ private val filePaths = FilePathManager(context)+ private val attachmentsDir = filePaths.attachmentsDir+ private val offlineDbFile = filePaths.mainDbFile+ private val onlineDbFile = filePaths.onlineDbFile+ private val syncDbFile = filePaths.syncDbFile+ private var offlineDbKey = credentialStore.getOrCreateChatDbKey()+ private var onlineDbKey: ByteArray? = null+ private var usingOnlineDb = false- private var db: LlmChatDb = openDb(offlineDbFile, offlineDbKey)++ private var db: EnsuDb = openDb(offlineDbFile, offlineDbKey)++ override fun listSessions(): List<ChatSession> = withDbRecovery {+ val sessions = db.listSessions()+ sessions.map { session ->+ val messages = runCatching { db.getMessages(session.uuid) }.getOrNull().orEmpty()+ val firstMessage = messages.firstOrNull()?.text.orEmpty()+ val lastMessage = messages.lastOrNull()?.text+ val isPlaceholder = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)+ val seedTitle = if (isPlaceholder) firstMessage else session.title+ ChatSession(+ id = session.uuid,+ title = sessionTitleFromText(seedTitle, fallback = session.title),+ lastMessagePreview = lastMessage,+ updatedAtMillis = session.updatedAtUs / 1000+ )+ }+ }++ override fun createSession(title: String): ChatSession = withDbRecovery {+ val session = db.createSession(title)+ ChatSession(+ id = session.uuid,+ title = session.title,+ lastMessagePreview = null,+ updatedAtMillis = session.updatedAtUs / 1000+ )+ }++ override fun deleteSession(sessionId: String) = withDbRecovery {+ db.deleteSession(sessionId)+ }++ override fun getMessages(sessionId: String): List<ChatMessage> = withDbRecovery {+ db.getMessages(sessionId).map { message ->+ ChatMessage(+ id = message.uuid,+ sessionId = message.sessionUuid,+ parentId = message.parentMessageUuid,+ author = when (message.sender) {- io.ente.labs.llmchat_db.Sender.SELF_USER -> MessageAuthor.User- io.ente.labs.llmchat_db.Sender.OTHER -> MessageAuthor.Assistant++ io.ente.labs.ensu_db.Sender.SELF_USER -> MessageAuthor.User++ io.ente.labs.ensu_db.Sender.OTHER -> MessageAuthor.Assistant+ },+ text = message.text,+ timestampMillis = message.createdAtUs / 1000,+ attachments = message.attachments.map { meta ->+ Attachment(+ id = meta.id,+ name = meta.name,+ sizeBytes = meta.size,+ type = when (meta.kind) {+ AttachmentKind.IMAGE -> AttachmentType.Image+ AttachmentKind.DOCUMENT -> AttachmentType.Document+ },+ localPath = File(attachmentsDir, meta.id).absolutePath,+ isUploading = false+ )+ }+ )+ }+ }++ override fun insertMessage(+ sessionId: String,+ parentId: String?,+ author: MessageAuthor,+ text: String,+ attachments: List<Attachment>+ ): ChatMessage = withDbRecovery {+ val meta = attachments.map { att ->+ AttachmentMeta(+ id = att.id,+ kind = when (att.type) {+ AttachmentType.Image -> AttachmentKind.IMAGE+ AttachmentType.Document -> AttachmentKind.DOCUMENT+ },+ size = att.sizeBytes,+ name = att.name+ )+ }++ val message = db.insertMessage(+ sessionUuid = sessionId,- sender = if (author == MessageAuthor.User) io.ente.labs.llmchat_db.Sender.SELF_USER else io.ente.labs.llmchat_db.Sender.OTHER,++ sender = if (author == MessageAuthor.User) io.ente.labs.ensu_db.Sender.SELF_USER else io.ente.labs.ensu_db.Sender.OTHER,+ text = text,+ parentMessageUuid = parentId,+ attachments = meta+ )++ ChatMessage(+ id = message.uuid,+ sessionId = message.sessionUuid,+ parentId = message.parentMessageUuid,+ author = author,+ text = message.text,+ timestampMillis = message.createdAtUs / 1000,+ attachments = attachments+ )+ }++ override fun updateMessageText(messageId: String, text: String) = withDbRecovery {+ db.updateMessageText(messageId, text)+ }++ override fun updateSessionTitle(sessionId: String, title: String) = withDbRecovery {+ db.updateSessionTitle(sessionId, title)+ }++ override fun enterOnlineMode(chatKey: ByteArray) {+ onlineDbKey = chatKey+ usingOnlineDb = true+ db = openDb(onlineDbFile, chatKey)+ }++ override fun exitOnlineMode() {+ usingOnlineDb = false+ onlineDbKey = null+ offlineDbKey = credentialStore.getOrCreateChatDbKey()+ db = openDb(offlineDbFile, offlineDbKey)+ }++ override fun deleteAllData() {+ offlineDbFile.delete()+ onlineDbFile.delete()+ syncDbFile.delete()+ filePaths.encryptedAttachmentsDir.deleteRecursively()+ filePaths.syncMetaDir.deleteRecursively()+ filePaths.attachmentsDir.deleteRecursively()+ filePaths.plaintextAttachmentsDir.deleteRecursively()++ filePaths.encryptedAttachmentsDir.mkdirs()+ filePaths.syncMetaDir.mkdirs()+ filePaths.attachmentsDir.mkdirs()+ filePaths.plaintextAttachmentsDir.mkdirs()++ usingOnlineDb = false+ onlineDbKey = null+ offlineDbKey = credentialStore.getOrCreateChatDbKey()+ db = openDb(offlineDbFile, offlineDbKey)+ }+- private fun openDb(dbFile: File, key: ByteArray): LlmChatDb {- return LlmChatDb.open(++ private fun openDb(dbFile: File, key: ByteArray): EnsuDb {++ return EnsuDb.open(+ dbFile.absolutePath,+ syncDbFile.absolutePath,+ key+ )+ }++ private fun <T> withDbRecovery(block: () -> T): T {+ val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile+ if (!syncDbFile.exists() || !targetDbFile.exists()) {+ reopenDb(targetDbFile)+ }+ return try {+ block()+ } catch (error: DbException) {+ if (isReadonlyDbError(error)) {+ reopenDb(targetDbFile)+ return block()+ }+ if (shouldResetDb(error)) {+ resetDb()+ return block()+ }+ throw error+ }+ }++ private fun reopenDb(targetDbFile: File) {+ targetDbFile.parentFile?.mkdirs()+ syncDbFile.parentFile?.mkdirs()+ targetDbFile.setWritable(true)+ syncDbFile.setWritable(true)+ db = openDb(targetDbFile, currentDbKey())+ }++ private fun shouldResetDb(error: DbException): Boolean {+ val message = when (error) {+ is DbException.Message -> error.v1+ else -> error.message.orEmpty()+ }+ return ChatRecovery.shouldResetFromMessage(message)+ }++ private fun isReadonlyDbError(error: DbException): Boolean {+ val message = when (error) {+ is DbException.Message -> error.v1+ else -> error.message.orEmpty()+ }+ return message.contains("readonly database", ignoreCase = true)+ }++ private fun currentDbKey(): ByteArray {+ return if (usingOnlineDb) {+ onlineDbKey ?: throw IllegalStateException("Missing online DB key")+ } else {+ offlineDbKey+ }+ }++ private fun resetDb() {+ val targetDbFile = if (usingOnlineDb) onlineDbFile else offlineDbFile+ targetDbFile.delete()+ syncDbFile.delete()+ db = openDb(targetDbFile, currentDbKey())+ }+}diff --cc mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.ktindex a7ae73616d,0000000000..d3cead25bamode 100644,000000..100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt@@@ -1,215 -1,0 +1,215 @@@+package io.ente.ensu.data.chat++import android.content.Context+import io.ente.ensu.data.EndpointPreferencesDataStore+import io.ente.ensu.data.network.NetworkConfiguration+import io.ente.ensu.data.storage.CredentialStore+import io.ente.ensu.data.storage.FilePathManager+import io.ente.ensu.domain.chat.ChatSyncRepository+import io.ente.ensu.domain.model.MigrationConfig as DomainMigrationConfig+import io.ente.ensu.domain.model.MigrationPriority as DomainMigrationPriority+import io.ente.ensu.domain.model.MigrationProgress as DomainMigrationProgress+import io.ente.ensu.domain.model.MigrationState as DomainMigrationState- import io.ente.labs.llmchat_sync.LlmChatSync- import io.ente.labs.llmchat_sync.MigrationConfig as RustMigrationConfig- import io.ente.labs.llmchat_sync.MigrationPriority as RustMigrationPriority- import io.ente.labs.llmchat_sync.MigrationProgress as RustMigrationProgress- import io.ente.labs.llmchat_sync.MigrationProgressCallback- import io.ente.labs.llmchat_sync.MigrationState as RustMigrationState- import io.ente.labs.llmchat_sync.SyncAuth- import io.ente.labs.llmchat_sync.SyncException++import io.ente.labs.ensu_sync.EnsuSync++import io.ente.labs.ensu_sync.MigrationConfig as RustMigrationConfig++import io.ente.labs.ensu_sync.MigrationPriority as RustMigrationPriority++import io.ente.labs.ensu_sync.MigrationProgress as RustMigrationProgress++import io.ente.labs.ensu_sync.MigrationProgressCallback++import io.ente.labs.ensu_sync.MigrationState as RustMigrationState++import io.ente.labs.ensu_sync.SyncAuth++import io.ente.labs.ensu_sync.SyncException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContext++class RustChatSyncRepository(+ private val context: Context,+ private val credentialStore: CredentialStore,+ private val endpointPreferences: EndpointPreferencesDataStore+) : ChatSyncRepository {++ private val filePaths = FilePathManager(context)- private var syncEngine: LlmChatSync? = null++ private var syncEngine: EnsuSync? = null+ private var chatKey: ByteArray? = null++ override suspend fun sync() {+ withContext(Dispatchers.IO) {+ try {+ ensureSyncEngine().sync(buildAuth())+ } catch (err: Throwable) {+ if (shouldResetSync(err)) {+ resetSyncStateInternal()+ try {+ ensureSyncEngine().sync(buildAuth())+ return@withContext+ } catch (retryErr: Throwable) {+ throw IllegalStateException(syncErrorMessage(retryErr), retryErr)+ }+ }+ throw IllegalStateException(syncErrorMessage(err), err)+ }+ }+ }++ override suspend fun syncWithProgress(+ config: DomainMigrationConfig,+ onProgress: (DomainMigrationProgress) -> Unit+ ) {+ withContext(Dispatchers.IO) {+ val callback = object : MigrationProgressCallback {+ override fun onProgress(progress: RustMigrationProgress) {+ onProgress(progress.toDomain())+ }+ }+ ensureSyncEngine().syncWithProgress(buildAuth(), config.toRust(), callback)+ }+ }++ override suspend fun checkMigrationStatusLocal(): DomainMigrationState? {+ return withContext(Dispatchers.IO) {+ runCatching { syncEngine?.checkMigrationStatusLocal() }+ .getOrNull()+ ?.toDomain()+ }+ }++ override suspend fun checkMigrationStatus(): DomainMigrationState {+ return withContext(Dispatchers.IO) {+ ensureSyncEngine().checkMigrationStatus(buildAuth()).toDomain()+ }+ }++ override suspend fun downloadAttachment(attachmentId: String, sessionId: String): Boolean {+ return withContext(Dispatchers.IO) {+ ensureSyncEngine().downloadAttachment(attachmentId, sessionId, buildAuth())+ }+ }++ override suspend fun prepareOnlineDb(): ByteArray {+ return withContext(Dispatchers.IO) {+ resetSyncStateInternal()+ val auth = buildAuth()- val key = io.ente.labs.llmchat_sync.fetchChatKey(auth, filePaths.syncDbFile.absolutePath)++ val key = io.ente.labs.ensu_sync.fetchChatKey(auth, filePaths.syncDbFile.absolutePath)+ chatKey = key+ val engine = buildSyncEngine(key).also { syncEngine = it }+ val offlineKey = credentialStore.getOrCreateChatDbKey()+ engine.seedFromOffline(filePaths.mainDbFile.absolutePath, offlineKey)+ key+ }+ }++ override suspend fun resetSyncState() {+ withContext(Dispatchers.IO) {+ resetSyncStateInternal()+ }+ }+- private suspend fun ensureSyncEngine(): LlmChatSync {++ private suspend fun ensureSyncEngine(): EnsuSync {+ return syncEngine ?: run {+ val key = chatKey ?: prepareOnlineDb()+ buildSyncEngine(key).also { syncEngine = it }+ }+ }+- private fun buildSyncEngine(dbKey: ByteArray): LlmChatSync {- return LlmChatSync.open(++ private fun buildSyncEngine(dbKey: ByteArray): EnsuSync {++ return EnsuSync.open(+ mainDbPath = filePaths.onlineDbFile.absolutePath,+ attachmentsDbPath = filePaths.syncDbFile.absolutePath,+ dbKey = dbKey,+ attachmentsDir = filePaths.encryptedAttachmentsDir.absolutePath,+ metaDir = filePaths.syncMetaDir.absolutePath,+ plaintextDir = filePaths.plaintextAttachmentsDir.absolutePath+ )+ }++ private suspend fun buildAuth(): SyncAuth {+ val endpoint = endpointPreferences.endpointFlow.first()+ val baseUrl = endpoint ?: NetworkConfiguration.default.apiEndpoint.toString()+ val token = credentialStore.getToken()?.let(::normalizeToken)+ ?: throw IllegalStateException("Missing auth token")+ val masterKey = credentialStore.getMasterKey()+ ?: throw IllegalStateException("Missing master key")++ val clientVersion = runCatching {+ context.packageManager.getPackageInfo(context.packageName, 0).versionName+ }.getOrNull()++ return SyncAuth(+ baseUrl = baseUrl,+ authToken = token,+ masterKey = masterKey,+ userAgent = "EnteNative-Android",+ clientPackage = context.packageName,+ clientVersion = clientVersion+ )+ }++ private fun normalizeToken(token: String): String {+ val remainder = token.length % 4+ return if (remainder == 0) token else token + "=".repeat(4 - remainder)+ }++ private fun shouldResetSync(error: Throwable): Boolean {+ val message = syncErrorMessage(error)+ return ChatRecovery.shouldResetFromMessage(message)+ }++ private fun resetSyncStateInternal() {+ runCatching { syncEngine?.resetSyncState() }+ syncEngine = null+ chatKey = null+ filePaths.onlineDbFile.delete()+ filePaths.syncDbFile.delete()+ filePaths.syncMetaDir.deleteRecursively()+ filePaths.encryptedAttachmentsDir.deleteRecursively()+ filePaths.encryptedAttachmentsDir.mkdirs()+ filePaths.syncMetaDir.mkdirs()+ }++ private fun syncErrorMessage(error: Throwable): String {+ val syncMessage = generateSequence(error) { it.cause }+ .filterIsInstance<SyncException.Message>()+ .firstOrNull()+ if (syncMessage != null) {+ return syncMessage.v1+ }++ val inProgress = generateSequence(error) { it.cause }+ .filterIsInstance<SyncException.SyncInProgress>()+ .firstOrNull()+ if (inProgress != null) {+ return "Sync already in progress"+ }++ val rootCause = generateSequence(error) { it.cause }.lastOrNull() ?: error+ return rootCause.message ?: error.message ?: rootCause.toString()+ }++ private fun DomainMigrationConfig.toRust(): RustMigrationConfig {+ return RustMigrationConfig(+ batchSize = batchSize,+ priority = when (priority) {+ DomainMigrationPriority.RECENT_FIRST -> RustMigrationPriority.RECENT_FIRST+ DomainMigrationPriority.OLDEST_FIRST -> RustMigrationPriority.OLDEST_FIRST+ }+ )+ }++ private fun RustMigrationState.toDomain(): DomainMigrationState {+ return when (this) {+ RustMigrationState.NOT_NEEDED -> DomainMigrationState.NOT_NEEDED+ RustMigrationState.IN_PROGRESS -> DomainMigrationState.IN_PROGRESS+ RustMigrationState.COMPLETE -> DomainMigrationState.COMPLETE+ RustMigrationState.FAILED -> DomainMigrationState.FAILED+ }+ }++ private fun RustMigrationProgress.toDomain(): DomainMigrationProgress {+ return DomainMigrationProgress(+ state = state.toDomain(),+ processed = processed,+ remaining = remaining,+ total = total+ )+ }+}diff --cc mobile/native/android/packages/rust/tool/build_android.shindex 5c80d5b601,0000000000..0023cd87bemode 100755,000000..100755--- a/mobile/native/android/packages/rust/tool/build_android.sh+++ b/mobile/native/android/packages/rust/tool/build_android.sh@@@ -1,76 -1,0 +1,76 @@@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"- CORE_UNIFFI_RUST_DIR="$REPO_ROOT/rust/uniffi/core_uniffi"- INFERENCE_UNIFFI_RUST_DIR="$REPO_ROOT/rust/llmchat/uniffi/inference_rs_uniffi"- CHATDB_UNIFFI_RUST_DIR="$REPO_ROOT/rust/llmchat/uniffi/llmchat_db_uniffi"- CHAT_SYNC_UNIFFI_RUST_DIR="$REPO_ROOT/rust/llmchat/uniffi/llmchat_sync_uniffi"++CORE_UNIFFI_RUST_DIR="$REPO_ROOT/rust/uniffi/core"++INFERENCE_UNIFFI_RUST_DIR="$REPO_ROOT/rust/uniffi/ensu/inference"++CHATDB_UNIFFI_RUST_DIR="$REPO_ROOT/rust/uniffi/ensu/db"++CHAT_SYNC_UNIFFI_RUST_DIR="$REPO_ROOT/rust/uniffi/ensu/sync"+# Patch llama.cpp mtmd sources so mmproj models load correctly.- PATCH_SCRIPT="$REPO_ROOT/rust/llmchat/inference/tool/patch_llama_mtmd.sh"++PATCH_SCRIPT="$REPO_ROOT/rust/ensu/inference/tool/patch_llama_mtmd.sh"+APPLY_LLAMA_MTMD_PATCH="${APPLY_LLAMA_MTMD_PATCH:-1}"+OUT_DIR="$ROOT/src/main/jniLibs"+SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"+NDK_VERSION="${NDK_VERSION:-}"+NDK_ROOT_PATH=""++if [[ -z "$SDK_ROOT" ]]; then+ for candidate in "$HOME/Library/Android/sdk" "$HOME/Android/Sdk" "$HOME/Android/sdk"; do+ if [[ -d "$candidate" ]]; then+ SDK_ROOT="$candidate"+ break+ fi+ done+fi++if [[ -z "$SDK_ROOT" ]]; then+ echo "Android SDK not found. Set ANDROID_HOME or ANDROID_SDK_ROOT to your SDK path." >&2+ exit 1+fi++if [[ -n "$NDK_VERSION" ]]; then+ NDK_ROOT_PATH="$SDK_ROOT/ndk/$NDK_VERSION"+elif [[ -d "$SDK_ROOT/ndk" ]]; then+ # Prefer numeric version folders (ignore legacy rXX folders).- NDK_ROOT_PATH="$(ls -1d "$SDK_ROOT/ndk/"[0-9]* 2>/dev/null | sort -V | tail -n 1)"++ NDK_ROOT_PATH="$(find "$SDK_ROOT/ndk" -mindepth 1 -maxdepth 1 -name '[0-9]*' 2>/dev/null | sort -V | tail -n 1 || true)"+ if [[ -z "$NDK_ROOT_PATH" ]]; then- NDK_ROOT_PATH="$(ls -1d "$SDK_ROOT/ndk/"* 2>/dev/null | sort -V | tail -n 1)"++ NDK_ROOT_PATH="$(find "$SDK_ROOT/ndk" -mindepth 1 -maxdepth 1 2>/dev/null | sort -V | tail -n 1 || true)"+ fi+elif [[ -d "$SDK_ROOT/ndk-bundle" ]]; then+ NDK_ROOT_PATH="$SDK_ROOT/ndk-bundle"+fi++if [[ -z "$NDK_ROOT_PATH" || ! -d "$NDK_ROOT_PATH" ]]; then+ echo "Android NDK not found. Install an NDK under $SDK_ROOT/ndk or set NDK_VERSION to a specific version." >&2+ exit 1+fi++if [[ "$APPLY_LLAMA_MTMD_PATCH" != "0" && -f "$PATCH_SCRIPT" ]]; then+ if ! command -v python3 >/dev/null 2>&1; then+ echo "python3 is required to apply the llama mtmd patch." >&2+ exit 1+ fi+ echo "Applying llama mtmd patch..."+ bash "$PATCH_SCRIPT"+fi++export ANDROID_NDK="$NDK_ROOT_PATH"+export ANDROID_NDK_ROOT="$NDK_ROOT_PATH"+export NDK_ROOT="$NDK_ROOT_PATH"+export CARGO_CFG_TARGET_FEATURE="${CARGO_CFG_TARGET_FEATURE:-}"++mkdir -p "$OUT_DIR"++for CRATE_DIR in "$CORE_UNIFFI_RUST_DIR" "$INFERENCE_UNIFFI_RUST_DIR" "$CHATDB_UNIFFI_RUST_DIR" "$CHAT_SYNC_UNIFFI_RUST_DIR"; do+ pushd "$CRATE_DIR" >/dev/null+ cargo ndk \+ --platform 23 \+ --link-libcxx-shared \+ -t arm64-v8a \+ -t armeabi-v7a \+ -t x86_64 \+ -o "$OUT_DIR" \+ build --release+ popd >/dev/null+donediff --cc mobile/native/darwin/Apps/ensu/README.mdindex e6b183a665,0000000000..b27e9619f2mode 100644,000000..100644--- a/mobile/native/darwin/Apps/ensu/README.md+++ b/mobile/native/darwin/Apps/ensu/README.md@@@ -1,106 -1,0 +1,106 @@@+# Ensu Apple Platforms++## Build (Terminal)++All commands below assume you run them from `darwin/Apps/ensu`.++## Generated bindings & dependencies++- SwiftMath is fetched via SwiftPM (`https://github.com/mgriebling/SwiftMath.git`).+- UniFFI Swift bindings are generated locally and gitignored:- - `ensu/Generated/*_uniffi*`++ - `ensu/Generated/core*`, `ensu/Generated/db*`, `ensu/Generated/sync*`+ - `../Packages/Rust/Sources/InferenceRS/inference_rs_uniffi*`+ - `../Packages/Rust/InferenceRSFFI.xcframework`++The Xcode build script (`scripts/build-rust.sh`) builds Rust static libs, but it does+not regenerate the Swift bindings. If bindings are missing, build the corresponding- `rust/uniffi/*` or `rust/llmchat/uniffi/*` crate and run `uniffi-bindgen generate` to output into the paths above.++`rust/uniffi/core` or `rust/uniffi/ensu/*` crate and run `uniffi-bindgen generate` to output into the paths above.+`../Packages/Rust/tool/generate_bindings.sh` and `../Packages/Rust/tool/build_xcframework.sh`+handle the InferenceRS bindings and xcframework.++### Debug Build (Simulator)+```bash+cd darwin/Apps/ensu+xcodebuild \+ -project ensu.xcodeproj \+ -scheme ensu \+ -configuration Debug \+ -sdk iphonesimulator \+ -destination 'platform=iOS Simulator,name=iPhone 15' \+ -derivedDataPath build+```++### Debug Build (Device)+```bash+cd darwin/Apps/ensu+xcodebuild \+ -project ensu.xcodeproj \+ -scheme ensu \+ -configuration Debug \+ -sdk iphoneos \+ -destination 'generic/platform=iOS' \+ -derivedDataPath build+```++### Release Build (Archive)+```bash+cd darwin/Apps/ensu+xcodebuild \+ -project ensu.xcodeproj \+ -scheme ensu \+ -configuration Release \+ -sdk iphoneos \+ -destination 'generic/platform=iOS' \+ -archivePath build/Archive/ensu.xcarchive \+ archive+```++### Release IPA (App Store)+```bash+cd darwin/Apps/ensu+xcodebuild \+ -exportArchive \+ -archivePath build/Archive/ensu.xcarchive \+ -exportPath build/Export \+ -exportOptionsPlist ExportOptions-AppStore.plist+```++## Installation (Terminal)++### Debug (Simulator)+```bash+cd darwin/Apps/ensu+xcrun simctl boot "iPhone 15" || true+xcrun simctl install booted build/Build/Products/Debug-iphonesimulator/ensu.app+xcrun simctl launch booted io.ente.ensu+```++### Debug (Physical Device)+```bash+cd darwin/Apps/ensu+xcrun devicectl device list+xcrun devicectl device install app \+ --device <DEVICE_UDID> \+ build/Build/Products/Debug-iphoneos/ensu.app+```++### Release (IPA)+Install the exported IPA via Apple Configurator or TestFlight after `xcodebuild -exportArchive`.++## Custom API Endpoint++Set the endpoint at build time using `ENTE_API_ENDPOINT`. If it is not set, the app defaults to `https://api.ente.io`.++```bash+cd darwin/Apps/ensu+ENTE_API_ENDPOINT="https://your-endpoint.example" \+ xcodebuild \+ -project ensu.xcodeproj \+ -scheme ensu \+ -configuration Debug \+ -sdk iphonesimulator \+ -destination 'platform=iOS Simulator,name=iPhone 15' \+ -derivedDataPath build+```++diff --cc mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxprojindex b1fcd1cd7f,0000000000..c4caaf9d8dmode 100644,000000..100644--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj@@@ -1,934 -1,0 +1,934 @@@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 77;+ objects = {++/* Begin PBXBuildFile section */+ DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };+ 21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };+ DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };+ DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };+ DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };+ DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };+ DBA3E91C2F7A6B9000AA11BB /* SwiftMath in Frameworks */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* SwiftMath */; };+ DBA3E91D2F7A6B9000AA11BB /* SwiftMath in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* SwiftMath */; };+ DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */ = {isa = PBXBuildFile; productRef = DB9F1C3B2F9D123400ABCD02 /* Markdown */; };+ DB9F1C3D2F9D123400ABCD02 /* Markdown in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DB9F1C3B2F9D123400ABCD02 /* Markdown */; };+/* End PBXBuildFile section */+++/* Begin PBXFileReference section */+ DA72BC612E5F87A000D128FF /* ensu.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ensu.app; sourceTree = BUILT_PRODUCTS_DIR; };+ 77E1DDDF900AB047CB554122 /* Ensu.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Ensu.app; sourceTree = BUILT_PRODUCTS_DIR; };+ DA72BC732E5F87A100D128FF /* castTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = castTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ DA72BC7D2E5F87A100D128FF /* castUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = castUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+/* End PBXFileReference section */++/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */+ DA01087C2E682336006E79AE /* Exceptions for "ensu" folder in "ensu" target */ = {+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;+ membershipExceptions = (+ Info-macOS.plist,+ Info.plist,+ );+ target = DA72BC602E5F87A000D128FF /* ensu */;+ };+ 8E70A4C58F3DCEC48083BAFB /* Exceptions for "ensu" folder in "ensu-macos" target */ = {+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;+ membershipExceptions = (+ Info-macOS.plist,+ Info.plist,+ LaunchScreen.storyboard,+ );+ target = EC53501B1BEF7BA36025B216 /* ensu-macos */;+ };+/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */++/* Begin PBXFileSystemSynchronizedRootGroup section */+ DA72BC632E5F87A000D128FF /* ensu */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ exceptions = (+ DA01087C2E682336006E79AE /* Exceptions for "ensu" folder in "ensu" target */,+ 8E70A4C58F3DCEC48083BAFB /* Exceptions for "ensu" folder in "ensu-macos" target */,+ );+ path = ensu;+ sourceTree = "<group>";+ };+/* End PBXFileSystemSynchronizedRootGroup section */++/* Begin PBXFrameworksBuildPhase section */+ DA72BC5E2E5F87A000D128FF /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */,+ DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */,+ DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */,+ DBA3E91C2F7A6B9000AA11BB /* SwiftMath in Frameworks */,+ DB9F1C3C2F9D123400ABCD02 /* Markdown in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 0BCBB02794980AFFDC386B69 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */,+ DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */,+ DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */,+ DBA3E91D2F7A6B9000AA11BB /* SwiftMath in Frameworks (macOS) */,+ DB9F1C3D2F9D123400ABCD02 /* Markdown in Frameworks (macOS) */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC702E5F87A100D128FF /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC7A2E5F87A100D128FF /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ DA72BC582E5F87A000D128FF = {+ isa = PBXGroup;+ children = (+ DA72BC632E5F87A000D128FF /* ensu */,+ DACC3DC72E618D6A00DAF993 /* Frameworks */,+ DA72BC622E5F87A000D128FF /* Products */,+ );+ sourceTree = "<group>";+ };+ DA72BC622E5F87A000D128FF /* Products */ = {+ isa = PBXGroup;+ children = (+ DA72BC612E5F87A000D128FF /* ensu.app */,+ 77E1DDDF900AB047CB554122 /* Ensu.app */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ DACC3DC72E618D6A00DAF993 /* Frameworks */ = {+ isa = PBXGroup;+ children = (+ );+ name = Frameworks;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ DA72BC602E5F87A000D128FF /* ensu */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = DA72BC872E5F87A100D128FF /* Build configuration list for PBXNativeTarget "ensu" */;+ buildPhases = (- CC142736A470612F436ECF8E /* Build Rust (core_uniffi) */,++ CC142736A470612F436ECF8E /* Build Rust (core/db/sync) */,+ DA72BC5D2E5F87A000D128FF /* Sources */,+ DA72BC5E2E5F87A000D128FF /* Frameworks */,+ DA72BC5F2E5F87A000D128FF /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ DA72BC632E5F87A000D128FF /* ensu */,+ );+ name = ensu;+ packageProductDependencies = (+ DACC3DC82E618D6A00DAF993 /* EnteNetwork */,+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */,+ DAF584662E61BB8300F8A08F /* ZIPFoundation */,+ DBA3E91B2F7A6B9000AA11BB /* SwiftMath */,+ DB9F1C3B2F9D123400ABCD02 /* Markdown */,+ );+ productName = ensu;+ productReference = DA72BC612E5F87A000D128FF /* ensu.app */;+ productType = "com.apple.product-type.application";+ };+ EC53501B1BEF7BA36025B216 /* ensu-macos */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 9C5C5C140967470293DCAAF2 /* Build configuration list for PBXNativeTarget "ensu-macos" */;+ buildPhases = (- 25484CE4873ED7217FB27990 /* Build Rust (core_uniffi) */,++ 25484CE4873ED7217FB27990 /* Build Rust (core/db/sync) */,+ BB83D829CC14232E7E8BDD51 /* Sources */,+ 0BCBB02794980AFFDC386B69 /* Frameworks */,+ 1FDE2B245F9DADEF5E026D0B /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ fileSystemSynchronizedGroups = (+ DA72BC632E5F87A000D128FF /* ensu */,+ );+ name = "ensu-macos";+ packageProductDependencies = (+ DACC3DC82E618D6A00DAF993 /* EnteNetwork */,+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */,+ DAF584662E61BB8300F8A08F /* ZIPFoundation */,+ DBA3E91B2F7A6B9000AA11BB /* SwiftMath */,+ DB9F1C3B2F9D123400ABCD02 /* Markdown */,+ );+ productName = Ensu;+ productReference = 77E1DDDF900AB047CB554122 /* Ensu.app */;+ productType = "com.apple.product-type.application";+ };+ DA72BC722E5F87A100D128FF /* castTests */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = DA72BC8A2E5F87A100D128FF /* Build configuration list for PBXNativeTarget "castTests" */;+ buildPhases = (+ DA72BC6F2E5F87A100D128FF /* Sources */,+ DA72BC702E5F87A100D128FF /* Frameworks */,+ DA72BC712E5F87A100D128FF /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ DA72BC752E5F87A100D128FF /* PBXTargetDependency */,+ );+ name = castTests;+ packageProductDependencies = (+ );+ productName = tvTests;+ productReference = DA72BC732E5F87A100D128FF /* castTests.xctest */;+ productType = "com.apple.product-type.bundle.unit-test";+ };+ DA72BC7C2E5F87A100D128FF /* castUITests */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = DA72BC8D2E5F87A100D128FF /* Build configuration list for PBXNativeTarget "castUITests" */;+ buildPhases = (+ DA72BC792E5F87A100D128FF /* Sources */,+ DA72BC7A2E5F87A100D128FF /* Frameworks */,+ DA72BC7B2E5F87A100D128FF /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ DA72BC7F2E5F87A100D128FF /* PBXTargetDependency */,+ );+ name = castUITests;+ packageProductDependencies = (+ );+ productName = tvUITests;+ productReference = DA72BC7D2E5F87A100D128FF /* castUITests.xctest */;+ productType = "com.apple.product-type.bundle.ui-testing";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ DA72BC592E5F87A000D128FF /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = 1;+ LastSwiftUpdateCheck = 1630;+ LastUpgradeCheck = 1630;+ TargetAttributes = {+ DA72BC602E5F87A000D128FF = {+ CreatedOnToolsVersion = 16.3;+ };+ EC53501B1BEF7BA36025B216 = {+ CreatedOnToolsVersion = 16.3;+ };+ DA72BC722E5F87A100D128FF = {+ CreatedOnToolsVersion = 16.3;+ TestTargetID = DA72BC602E5F87A000D128FF;+ };+ DA72BC7C2E5F87A100D128FF = {+ CreatedOnToolsVersion = 16.3;+ TestTargetID = DA72BC602E5F87A000D128FF;+ };+ };+ };+ buildConfigurationList = DA72BC5C2E5F87A000D128FF /* Build configuration list for PBXProject "ensu" */;+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ );+ mainGroup = DA72BC582E5F87A000D128FF;+ minimizedProjectReferenceProxies = 1;+ packageReferences = (+ DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */,+ DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */,+ DBA3E91A2F7A6B9000AA11BB /* XCRemoteSwiftPackageReference "SwiftMath" */,+ DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */,+ DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */,+ );+ preferredProjectObjectVersion = 77;+ productRefGroup = DA72BC622E5F87A000D128FF /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ DA72BC602E5F87A000D128FF /* ensu */,+ EC53501B1BEF7BA36025B216 /* ensu-macos */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ DA72BC5F2E5F87A000D128FF /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 1FDE2B245F9DADEF5E026D0B /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC712E5F87A100D128FF /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC7B2E5F87A100D128FF /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXShellScriptBuildPhase section */- CC142736A470612F436ECF8E /* Build Rust (core_uniffi) */ = {++ CC142736A470612F436ECF8E /* Build Rust (core/db/sync) */ = {+ isa = PBXShellScriptBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ inputPaths = (+ );- name = "Build Rust (core_uniffi)";++ name = "Build Rust (core/db/sync)";+ outputPaths = (- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "ENTE_API_ENDPOINT=\"${ENTE_API_ENDPOINT}\" \"${SRCROOT}/scripts/build-rust.sh\"\n";+ };- 25484CE4873ED7217FB27990 /* Build Rust (core_uniffi) */ = {++ 25484CE4873ED7217FB27990 /* Build Rust (core/db/sync) */ = {+ isa = PBXShellScriptBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ inputPaths = (+ );- name = "Build Rust (core_uniffi)";++ name = "Build Rust (core/db/sync)";+ outputPaths = (- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "ENTE_API_ENDPOINT=\"${ENTE_API_ENDPOINT}\" \"${SRCROOT}/scripts/build-rust.sh\"\n";+ };+/* End PBXShellScriptBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ DA72BC5D2E5F87A000D128FF /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ BB83D829CC14232E7E8BDD51 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC6F2E5F87A100D128FF /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ DA72BC792E5F87A100D128FF /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */+++/* Begin XCBuildConfiguration section */+ DA72BC852E5F87A100D128FF /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ INFOPLIST_KEY_UIRequiresFullScreen = YES;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = iphoneos;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ IPHONEOS_DEPLOYMENT_TARGET = 16.0;+ };+ name = Debug;+ };+ DA72BC862E5F87A100D128FF /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = YES;+ GCC_C_LANGUAGE_STANDARD = gnu17;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ INFOPLIST_KEY_UIRequiresFullScreen = YES;+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ SDKROOT = iphoneos;+ SWIFT_COMPILATION_MODE = wholemodule;+ IPHONEOS_DEPLOYMENT_TARGET = 16.0;+ VALIDATE_PRODUCT = YES;+ };+ name = Release;+ };+ DA72BC882E5F87A100D128FF /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 20;+ DEVELOPMENT_TEAM = 6Z68YJY9Q2;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = ensu/Info.plist;+ ENTE_API_ENDPOINT = "";+ INFOPLIST_KEY_CFBundleDisplayName = "Ensu";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.photography";+ INFOPLIST_KEY_UILaunchScreen_Generation = YES;+ INFOPLIST_KEY_UIRequiresFullScreen = YES;+ INFOPLIST_KEY_UIUserInterfaceStyle = Automatic;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 0.1.2;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;+ PRODUCT_NAME = "$(TARGET_NAME)";+ PROVISIONING_PROFILE_SPECIFIER = "";+ HEADER_SEARCH_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ SWIFT_INCLUDE_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ LIBRARY_SEARCH_PATHS = (+ "$(inherited)",+ "$(TARGET_TEMP_DIR)/ensu_rust",+ );+ OTHER_LDFLAGS = (+ "$(inherited)",+ "-force_load",- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ OTHER_SWIFT_FLAGS = (+ "$(inherited)",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/core_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/coreFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_db_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/dbFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_sync_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/syncFFI.modulemap",+ );+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ DA72BC892E5F87A100D128FF /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 20;+ DEVELOPMENT_TEAM = 6Z68YJY9Q2;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = ensu/Info.plist;+ ENTE_API_ENDPOINT = "";+ INFOPLIST_KEY_CFBundleDisplayName = "Ensu";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.photography";+ INFOPLIST_KEY_UILaunchScreen_Generation = YES;+ INFOPLIST_KEY_UIRequiresFullScreen = YES;+ INFOPLIST_KEY_UIUserInterfaceStyle = Automatic;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ MARKETING_VERSION = 0.1.2;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;+ PRODUCT_NAME = "$(TARGET_NAME)";+ PROVISIONING_PROFILE_SPECIFIER = "";+ HEADER_SEARCH_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ SWIFT_INCLUDE_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ LIBRARY_SEARCH_PATHS = (+ "$(inherited)",+ "$(TARGET_TEMP_DIR)/ensu_rust",+ );+ OTHER_LDFLAGS = (+ "$(inherited)",+ "-force_load",- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ OTHER_SWIFT_FLAGS = (+ "$(inherited)",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/core_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/coreFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_db_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/dbFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_sync_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/syncFFI.modulemap",+ );+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+ 951526E3C06548C816E1D750 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIconMac;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 5;+ DEVELOPMENT_TEAM = 6Z68YJY9Q2;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = ensu/Info-macOS.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "Ensu";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.photography";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ MACOSX_DEPLOYMENT_TARGET = 13.0;+ MARKETING_VERSION = 0.1.2;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;+ PRODUCT_NAME = Ensu;+ HEADER_SEARCH_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ SWIFT_INCLUDE_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ LIBRARY_SEARCH_PATHS = (+ "$(inherited)",+ "$(TARGET_TEMP_DIR)/ensu_rust",+ );+ OTHER_LDFLAGS = (+ "$(inherited)",+ "-framework",+ "SystemConfiguration",+ "-force_load",- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ OTHER_SWIFT_FLAGS = (+ "$(inherited)",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/core_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/coreFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_db_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/dbFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_sync_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/syncFFI.modulemap",+ );+ SDKROOT = macosx;+ SUPPORTED_PLATFORMS = macosx;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 5.0;+ };+ name = Debug;+ };+ 903C407D9F16DA01750450CF /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIconMac;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_IDENTITY = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 5;+ DEVELOPMENT_TEAM = 6Z68YJY9Q2;+ ENABLE_PREVIEWS = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = ensu/Info-macOS.plist;+ INFOPLIST_KEY_CFBundleDisplayName = "Ensu";+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.photography";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/../Frameworks",+ );+ MACOSX_DEPLOYMENT_TARGET = 13.0;+ MARKETING_VERSION = 0.1.2;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.ensu;+ PRODUCT_NAME = Ensu;+ HEADER_SEARCH_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ SWIFT_INCLUDE_PATHS = (+ "$(inherited)",+ "$(SRCROOT)/ensu/Generated",+ );+ LIBRARY_SEARCH_PATHS = (+ "$(inherited)",+ "$(TARGET_TEMP_DIR)/ensu_rust",+ );+ OTHER_LDFLAGS = (+ "$(inherited)",+ "-framework",+ "SystemConfiguration",+ "-force_load",- "$(TARGET_TEMP_DIR)/ensu_rust/libcore_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_db_uniffi.a",- "$(TARGET_TEMP_DIR)/ensu_rust/libllmchat_sync_uniffi.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libcore.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libdb.a",++ "$(TARGET_TEMP_DIR)/ensu_rust/libsync.a",+ );+ OTHER_SWIFT_FLAGS = (+ "$(inherited)",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/core_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/coreFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_db_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/dbFFI.modulemap",+ "-Xcc",- "-fmodule-map-file=$(SRCROOT)/ensu/Generated/llmchat_sync_uniffiFFI.modulemap",++ "-fmodule-map-file=$(SRCROOT)/ensu/Generated/syncFFI.modulemap",+ );+ SDKROOT = macosx;+ SUPPORTED_PLATFORMS = macosx;+ SWIFT_EMIT_LOC_STRINGS = YES;+ SWIFT_VERSION = 5.0;+ };+ name = Release;+ };+ DA72BC8B2E5F87A100D128FF /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 3;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/tv.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/tv";+ TVOS_DEPLOYMENT_TARGET = 18.4;+ };+ name = Debug;+ };+ DA72BC8C2E5F87A100D128FF /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tvTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 3;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/tv.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/tv";+ TVOS_DEPLOYMENT_TARGET = 18.4;+ };+ name = Release;+ };+ DA72BC8E2E5F87A100D128FF /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tv.castUITests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 3;+ TEST_TARGET_NAME = tv;+ };+ name = Debug;+ };+ DA72BC8F2E5F87A100D128FF /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ DEVELOPMENT_TEAM = SN6GQPQWGV;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 0.1.0;+ PRODUCT_BUNDLE_IDENTIFIER = io.ente.photos.tvUITests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_EMIT_LOC_STRINGS = NO;+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 3;+ TEST_TARGET_NAME = tv;+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ DA72BC5C2E5F87A000D128FF /* Build configuration list for PBXProject "ensu" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DA72BC852E5F87A100D128FF /* Debug */,+ DA72BC862E5F87A100D128FF /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ DA72BC872E5F87A100D128FF /* Build configuration list for PBXNativeTarget "ensu" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DA72BC882E5F87A100D128FF /* Debug */,+ DA72BC892E5F87A100D128FF /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 9C5C5C140967470293DCAAF2 /* Build configuration list for PBXNativeTarget "ensu-macos" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 951526E3C06548C816E1D750 /* Debug */,+ 903C407D9F16DA01750450CF /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ DA72BC8A2E5F87A100D128FF /* Build configuration list for PBXNativeTarget "castTests" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DA72BC8B2E5F87A100D128FF /* Debug */,+ DA72BC8C2E5F87A100D128FF /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ DA72BC8D2E5F87A100D128FF /* Build configuration list for PBXNativeTarget "castUITests" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ DA72BC8E2E5F87A100D128FF /* Debug */,+ DA72BC8F2E5F87A100D128FF /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCLocalSwiftPackageReference section */+ DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = ../../Packages/EnteNetwork;+ };+ DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = ../../Packages/Rust;+ };+/* End XCLocalSwiftPackageReference section */++/* Begin XCRemoteSwiftPackageReference section */+ DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/weichsel/ZIPFoundation.git";+ requirement = {+ kind = upToNextMajorVersion;+ minimumVersion = 0.9.19;+ };+ };+ DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/apple/swift-markdown.git";+ requirement = {+ kind = upToNextMajorVersion;+ minimumVersion = 0.3.0;+ };+ };+ DBA3E91A2F7A6B9000AA11BB /* XCRemoteSwiftPackageReference "SwiftMath" */ = {+ isa = XCRemoteSwiftPackageReference;+ repositoryURL = "https://github.com/mgriebling/SwiftMath.git";+ requirement = {+ kind = upToNextMajorVersion;+ minimumVersion = 1.7.3;+ };+ };+/* End XCRemoteSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ DACC3DC82E618D6A00DAF993 /* EnteNetwork */ = {+ isa = XCSwiftPackageProductDependency;+ productName = EnteNetwork;+ };+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */ = {+ isa = XCSwiftPackageProductDependency;+ productName = InferenceRS;+ };+ DBA3E91B2F7A6B9000AA11BB /* SwiftMath */ = {+ isa = XCSwiftPackageProductDependency;+ package = DBA3E91A2F7A6B9000AA11BB /* XCRemoteSwiftPackageReference "SwiftMath" */;+ productName = SwiftMath;+ };+ DAF584662E61BB8300F8A08F /* ZIPFoundation */ = {+ isa = XCSwiftPackageProductDependency;+ package = DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */;+ productName = ZIPFoundation;+ };+ DB9F1C3B2F9D123400ABCD02 /* Markdown */ = {+ isa = XCSwiftPackageProductDependency;+ package = DB9F1C3A2F9D123400ABCD02 /* XCRemoteSwiftPackageReference "swift-markdown" */;+ productName = Markdown;+ };+/* End XCSwiftPackageProductDependency section */+ };+ rootObject = DA72BC592E5F87A000D128FF /* Project object */;+}diff --cc mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 6b8dd27661,0000000000..82e296a612mode 100644,000000..100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@@ -1,2419 -1,0 +1,2419 @@@+import Foundation+import SwiftUI+#if canImport(EnteCore)+import EnteCore+#else+struct SyncAuth {+ let baseUrl: String+ let authToken: String+ let masterKey: Data+ let userAgent: String+ let clientPackage: String+ let clientVersion: String?+}++enum SyncError: Error {+ case Message(String)+ case SyncInProgress+}++struct MigrationConfig {+ let batchSize: Int64+ let priority: MigrationPriority+}++enum MigrationPriority {+ case recentFirst+ case oldestFirst+}++enum MigrationState {+ case notNeeded+ case inProgress+ case complete+ case failed+}++struct MigrationProgress {+ let state: MigrationState+ let processed: Int64+ let remaining: Int64+ let total: Int64+}++protocol MigrationProgressCallback {+ func onProgress(progress: MigrationProgress)+}++final class CredentialStore {+ static let shared = CredentialStore()+ var hasConfiguredAccount: Bool { false }+ var token: String? { nil }+ var masterKey: Data? { nil }++ func getOrCreateChatDbKey() -> Data {+ Data()+ }+}++struct EntePlatform {+ static let current = EntePlatform()+ var userAgent: String { "ensu" }+}++enum EnteApp {+ case ensu++ var packageIdentifier: String {+ "ensu"+ }+}++enum EnsuLogLevel: String {+ case info+ case warning+ case error+}++struct EnsuLogger {+ let tag: String++ func info(_ message: String, details: String? = nil) {}+ func warning(_ message: String, details: String? = nil) {}+ func error(_ message: String, _ error: Error? = nil, details: String? = nil) {}+}++final class EnsuLogging {+ static let shared = EnsuLogging()++ func start() {}++ func logger(_ tag: String) -> EnsuLogger {+ EnsuLogger(tag: tag)+ }++ func log(level: EnsuLogLevel, tag: String, message: String, details: String? = nil, error: Error? = nil) {}++ func todayLogFileURL() -> URL { URL(fileURLWithPath: "") }+ func listLogFiles() -> [URL] { [] }+ func readLogText(fileURL: URL) -> String { "" }+ func createLogsArchive() throws -> URL { URL(fileURLWithPath: "") }+}++struct NetworkConfiguration {+ let apiEndpoint: URL++ static var `default`: NetworkConfiguration {+ NetworkConfiguration(apiEndpoint: URL(string: "https://api.ente.io")!)+ }+}++enum EnsuDeveloperSettings {+ static var networkConfiguration: NetworkConfiguration {+ .default+ }+}++struct InferenceModelTarget: Equatable {+ let id: String+ let url: String+ let mmprojUrl: String?+ let contextLength: Int?+ let maxTokens: Int?+}++struct InferenceDownloadProgress: Equatable {+ let percent: Int+ let status: String+}++enum InferenceMessageRole {+ case user+ case assistant+ case system++ var roleString: String {+ switch self {+ case .user:+ return "user"+ case .assistant:+ return "assistant"+ case .system:+ return "system"+ }+ }+}++struct InferenceMessage {+ let text: String+ let role: InferenceMessageRole+ let hasAttachments: Bool+}++struct InferenceGenerationSummary {+ let jobId: Int64+ let generatedTokens: Int+ let totalTimeMs: Int64?+}++final class InferenceRsProvider {+ init(modelDir: URL) {+ _ = modelDir+ }++ func ensureModelReady(+ target: InferenceModelTarget,+ onProgress: @escaping (InferenceDownloadProgress) -> Void+ ) async throws {+ _ = (target, onProgress)+ }++ func generateChat(+ target: InferenceModelTarget,+ messages: [InferenceMessage],+ imageFiles: [URL],+ temperature: Float,+ maxTokens: Int,+ onToken: @escaping (String) -> Void+ ) async throws -> InferenceGenerationSummary {+ _ = (target, messages, imageFiles, temperature, maxTokens, onToken)+ return InferenceGenerationSummary(jobId: 0, generatedTokens: 0, totalTimeMs: nil)+ }++ func isModelDownloaded(target: InferenceModelTarget) -> Bool {+ _ = target+ return true+ }++ func estimatedDownloadSize(target: InferenceModelTarget) async -> Int64? {+ _ = target+ return nil+ }++ func stopGeneration() {}++ func resetContext() {}++ func cancelDownload() {}+}++@MainActor+final class ModelSettingsStore: ObservableObject {+ static let shared = ModelSettingsStore()++ var temperature: String = ""+ var contextLength: String = ""+ var maxTokens: String = ""+ var useCustomModel: Bool = false+ var modelUrl: String = ""+ var mmprojUrl: String = ""++ func currentTarget() -> InferenceModelTarget {+ let context = Int(contextLength)+ let maxOutput = Int(maxTokens)+ return InferenceModelTarget(+ id: "default",+ url: "",+ mmprojUrl: nil,+ contextLength: context,+ maxTokens: maxOutput+ )+ }+}++enum MessageSender {+ case selfUser+ case other+}++enum AttachmentKind {+ case image+ case document+}++struct AttachmentMeta {+ let id: String+ let kind: AttachmentKind+ let size: Int64+ let name: String+}++struct LlmChatSession {+ let uuid: String+ let title: String+ let updatedAtUs: Int64+}++struct LlmChatMessage {+ let uuid: String+ let sender: MessageSender+ let createdAtUs: Int64+ let text: String+ let parentMessageUuid: String?+ let attachments: [AttachmentMeta]+}+- final class LlmChatDb {- static func open(mainDbPath: String, attachmentsDbPath: String, key: Data) throws -> LlmChatDb {++final class EnsuDb {++ static func open(mainDbPath: String, attachmentsDbPath: String, key: Data) throws -> EnsuDb {+ _ = (mainDbPath, attachmentsDbPath, key)- return LlmChatDb()++ return EnsuDb()+ }++ func listSessions() throws -> [LlmChatSession] { [] }++ func getMessages(sessionUuid: String) throws -> [LlmChatMessage] {+ _ = sessionUuid+ return []+ }++ func deleteSession(uuid: String) throws {+ _ = uuid+ }++ func insertMessage(+ sessionUuid: String,+ sender: MessageSender,+ text: String,+ parentMessageUuid: String?,+ attachments: [AttachmentMeta]+ ) throws -> LlmChatMessage {+ _ = (sessionUuid, sender, text, parentMessageUuid, attachments)+ return LlmChatMessage(+ uuid: UUID().uuidString,+ sender: sender,+ createdAtUs: Int64(Date().timeIntervalSince1970 * 1_000_000),+ text: text,+ parentMessageUuid: parentMessageUuid,+ attachments: attachments+ )+ }++ func createSession(title: String) throws -> LlmChatSession {+ LlmChatSession(uuid: UUID().uuidString, title: title, updatedAtUs: Int64(Date().timeIntervalSince1970 * 1_000_000))+ }++ func updateSessionTitle(uuid: String, title: String) throws {+ _ = (uuid, title)+ }+}+- final class LlmChatSync {++final class EnsuSync {+ static func open(+ mainDbPath: String,+ attachmentsDbPath: String,+ dbKey: Data,+ attachmentsDir: String,+ metaDir: String,+ plaintextDir: String- ) throws -> LlmChatSync {++ ) throws -> EnsuSync {+ _ = (mainDbPath, attachmentsDbPath, dbKey, attachmentsDir, metaDir, plaintextDir)- return LlmChatSync()++ return EnsuSync()+ }++ func sync(auth: SyncAuth) throws -> Bool {+ _ = auth+ return true+ }++ func checkMigrationStatusLocal() -> MigrationState? {+ nil+ }++ func checkMigrationStatus(auth: SyncAuth) throws -> MigrationState {+ _ = auth+ return .inProgress+ }++ func syncWithProgress(+ auth: SyncAuth,+ config: MigrationConfig,+ callback: MigrationProgressCallback+ ) throws -> Bool {+ _ = (auth, config, callback)+ return true+ }++ func resetSyncState() throws {+ }++ func seedFromOffline(offlineDbPath: String, offlineDbKey: Data) throws {+ _ = (offlineDbPath, offlineDbKey)+ }++ func downloadAttachment(attachmentId: String, sessionUuid: String, auth: SyncAuth) throws -> Bool {+ _ = (attachmentId, sessionUuid, auth)+ return true+ }+}++func fetchChatKey(auth: SyncAuth, syncDbPath: String) throws -> Data {+ _ = (auth, syncDbPath)+ return Data()+}+#endif++#if canImport(EnteCore)++typealias LlmChatSession = Session++enum SyncState: Equatable {+ case idle+ case syncing+ case migrating(processed: Int64, total: Int64)+ case error(String)+}++final class MigrationProgressHandler: MigrationProgressCallback {+ private let handler: @Sendable (MigrationProgress) -> Void++ init(_ handler: @escaping @Sendable (MigrationProgress) -> Void) {+ self.handler = handler+ }++ func onProgress(progress: MigrationProgress) {+ handler(progress)+ }+}++private struct OnlineStorePreparation {+ let chatKey: Data- let chatDb: LlmChatDb- let syncEngine: LlmChatSync++ let chatDb: EnsuDb++ let syncEngine: EnsuSync+}++@MainActor+final class ChatViewModel: ObservableObject {+ private static let defaultTemperature: Float = 0.5+ private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$"+ private static let overflowSafetyTokens = 128+ private static let imageTokenEstimate = 768+ private nonisolated static let sessionTitleMaxLength = 40+ private static let sessionSummaryMaxWords = 7+ private static let sessionSummaryStoreKey = "ensu.session_summaries"+ private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title."++ private let logger = EnsuLogging.shared.logger("ChatViewModel")++ @Published var sessions: [ChatSession]+ @Published var currentSessionId: UUID?+ @Published var messages: [ChatMessage]+ @Published var streamingResponse: String = ""+ @Published var streamingParentId: UUID? = nil+ @Published var overflowAlert: OverflowAlertState? = nil++ var displayedStreamingResponse: String {+ guard let activeSession = activeGenerationSessionId,+ activeSession == currentSessionId,+ activeGenerationId != nil else {+ return ""+ }+ return streamingResponse+ }++ var displayedStreamingParentId: UUID? {+ guard let activeSession = activeGenerationSessionId,+ activeSession == currentSessionId,+ activeGenerationId != nil else {+ return nil+ }+ return streamingParentId+ }+ @Published var isGenerating: Bool = false+ @Published var isDownloading: Bool = false+ @Published var isProcessingAttachments: Bool = false+ @Published var draftText: String = ""+ @Published var draftAttachments: [ChatAttachment] = []+ @Published var editingMessageId: UUID?+ @Published var downloadToast: DownloadToastState?+ @Published var isModelDownloaded: Bool = false+ @Published var modelDownloadSizeBytes: Int64?+ @Published var hasRequestedModelDownload: Bool = false+ @Published var attachmentDownloads: [AttachmentDownloadItem] = []+ @Published var currentSessionMissingAttachments: [AttachmentDownloadItem] = []+ @Published var syncState: SyncState = .idle+ @Published var syncErrorMessage: String?+ @Published var syncSuccessMessage: String?+ @Published var generationErrorMessage: String?++ private let provider: InferenceRsProvider- private var chatDb: LlmChatDb- private var syncEngine: LlmChatSync++ private var chatDb: EnsuDb++ private var syncEngine: EnsuSync+ private let attachmentsDir: URL+ private let offlineDbPath: String+ private let onlineDbPath: String+ private let syncDbPath: String+ private let syncMetaDir: URL+ private let encryptedAttachmentsDir: URL+ private let offlineDbKey: Data+ private var onlineDbKey: Data?+ private var isOnlineMode = false+ private let modelSettings = ModelSettingsStore.shared++ private var activeDbPath: String {+ isOnlineMode ? onlineDbPath : offlineDbPath+ }++ private var activeDbKey: Data? {+ isOnlineMode ? onlineDbKey : offlineDbKey+ }++ private var messageStore: [UUID: [MessageNode]] = [:]+ private var branchSelections: [UUID: [String: UUID]] = [:]+ private var childrenByParentCache: [UUID: [UUID: [MessageNode]]] = [:]+ private var sessionSummaries: [String: String] = [:]+ private var sessionSummaryTask: Task<Void, Never>?+ private var reloadTask: Task<Void, Never>?+ private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!+ private var generationTask: Task<Void, Never>?+ private var modelDownloadTask: Task<Void, Never>?+ private var stopRequested = false+ private var activeGenerationId: UUID?+ private var activeGenerationSessionId: UUID?+ private var pendingSyncRequested = false+ private var pendingSyncShowErrors = false+ private var pendingSyncShowSuccess = false+ private var modelDownloadLoggedStart = false+ private var pendingOverflow: PendingOverflow?+ private var overflowBypassMessageId: UUID?++ private var attachmentDownloadQueue: [String] = []+ private var attachmentDownloadTasks: [String: Task<Void, Never>] = [:]+ private let maxAttachmentDownloads = 2++ init() {+ logger.info("Initializing")+ let summaries = Self.loadSessionSummaries().reduce(into: [String: String]()) { result, item in+ result[item.key.lowercased()] = item.value+ }+ let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? FileManager.default.temporaryDirectory++ // LLM model files.+ let llmDir = baseDir.appendingPathComponent("llm", isDirectory: true)+ let provider = InferenceRsProvider(modelDir: llmDir)++ // Chat DB + attachments.+ let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)+ try? FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true, attributes: nil)+ let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)+ try? FileManager.default.createDirectory(at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)++ let offlineKey = CredentialStore.shared.getOrCreateChatDbKey()+ let offlineDbPath = dbDir.appendingPathComponent("llmchat.db").path+ let onlineDbPath = dbDir.appendingPathComponent("llmchat_online.db").path+ let syncDbPath = dbDir.appendingPathComponent("llmchat_sync.db").path+- let chatDb: LlmChatDb++ let chatDb: EnsuDb+ do {- chatDb = try LlmChatDb.open(mainDbPath: offlineDbPath, attachmentsDbPath: syncDbPath, key: offlineKey)++ chatDb = try EnsuDb.open(mainDbPath: offlineDbPath, attachmentsDbPath: syncDbPath, key: offlineKey)+ } catch {+ fatalError("Failed to open chat DB: \(error)")+ }++ let syncMetaDir = dbDir.appendingPathComponent("sync_meta", isDirectory: true)+ try? FileManager.default.createDirectory(at: syncMetaDir, withIntermediateDirectories: true, attributes: nil)+ let encryptedAttachmentsDir = dbDir.appendingPathComponent("chat_attachments_encrypted", isDirectory: true)+ try? FileManager.default.createDirectory(at: encryptedAttachmentsDir, withIntermediateDirectories: true, attributes: nil)+- let syncEngine: LlmChatSync++ let syncEngine: EnsuSync+ do {- syncEngine = try LlmChatSync.open(++ syncEngine = try EnsuSync.open(+ mainDbPath: offlineDbPath,+ attachmentsDbPath: syncDbPath,+ dbKey: offlineKey,+ attachmentsDir: encryptedAttachmentsDir.path,+ metaDir: syncMetaDir.path,+ plaintextDir: attachmentsDir.path+ )+ } catch {+ fatalError("Failed to open chat sync: \(error)")+ }++ // Load sessions/messages.+ let loaded = (try? chatDb.listSessions()) ?? []+ let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)++ // Stored properties.+ self.provider = provider+ self.chatDb = chatDb+ self.syncEngine = syncEngine+ self.attachmentsDir = attachmentsDir+ self.offlineDbPath = offlineDbPath+ self.onlineDbPath = onlineDbPath+ self.syncDbPath = syncDbPath+ self.syncMetaDir = syncMetaDir+ self.encryptedAttachmentsDir = encryptedAttachmentsDir+ self.offlineDbKey = offlineKey+ self.sessionSummaries = summaries++ self.sessions = sessions+ self.currentSessionId = nil+ self.messages = []++ for session in sessions {+ self.messageStore[session.id] = []+ self.branchSelections[session.id] = [:]+ }++ if let current = self.currentSessionId {+ loadMessagesFromDb(for: current)+ } else {+ refreshAttachmentDownloadState()+ }++ refreshModelDownloadInfo()+ }++ private func reopenSyncStoresIfNeeded(force: Bool = false) {+ let hasSyncDb = FileManager.default.fileExists(atPath: syncDbPath)+ let hasActiveDb = FileManager.default.fileExists(atPath: activeDbPath)+ if !force && hasSyncDb && hasActiveDb {+ return+ }++ guard let key = activeDbKey else {+ logger.error("Missing active DB key")+ return+ }++ do {+ try? FileManager.default.createDirectory(+ at: syncMetaDir,+ withIntermediateDirectories: true,+ attributes: nil+ )+ try? FileManager.default.createDirectory(+ at: encryptedAttachmentsDir,+ withIntermediateDirectories: true,+ attributes: nil+ )+ try? FileManager.default.createDirectory(+ at: attachmentsDir,+ withIntermediateDirectories: true,+ attributes: nil+ )+- chatDb = try LlmChatDb.open(++ chatDb = try EnsuDb.open(+ mainDbPath: activeDbPath,+ attachmentsDbPath: syncDbPath,+ key: key+ )- syncEngine = try LlmChatSync.open(++ syncEngine = try EnsuSync.open(+ mainDbPath: activeDbPath,+ attachmentsDbPath: syncDbPath,+ dbKey: key,+ attachmentsDir: encryptedAttachmentsDir.path,+ metaDir: syncMetaDir.path,+ plaintextDir: attachmentsDir.path+ )+ } catch {+ logger.error("Failed to reopen sync stores: \(error)")+ }+ }++ private func prepareOnlineStores(auth: SyncAuth) async throws {+ let syncDbPath = syncDbPath+ let onlineDbPath = onlineDbPath+ let offlineDbPath = offlineDbPath+ let offlineDbKey = offlineDbKey+ let syncMetaDir = syncMetaDir+ let encryptedAttachmentsDir = encryptedAttachmentsDir+ let attachmentsDir = attachmentsDir+ let existingSyncEngine = syncEngine++ let preparation = try await Task.detached {+ if FileManager.default.fileExists(atPath: syncDbPath) {+ try? existingSyncEngine.resetSyncState()+ }+ try? FileManager.default.removeItem(atPath: onlineDbPath)+ ChatDataCleaner.deleteSyncState()+ try? FileManager.default.createDirectory(+ at: syncMetaDir,+ withIntermediateDirectories: true,+ attributes: nil+ )+ try? FileManager.default.createDirectory(+ at: encryptedAttachmentsDir,+ withIntermediateDirectories: true,+ attributes: nil+ )+ try? FileManager.default.createDirectory(+ at: attachmentsDir,+ withIntermediateDirectories: true,+ attributes: nil+ )++ let chatKey = try fetchChatKey(auth: auth, syncDbPath: syncDbPath)+- let chatDb = try LlmChatDb.open(++ let chatDb = try EnsuDb.open(+ mainDbPath: onlineDbPath,+ attachmentsDbPath: syncDbPath,+ key: chatKey+ )- let newSyncEngine = try LlmChatSync.open(++ let newSyncEngine = try EnsuSync.open(+ mainDbPath: onlineDbPath,+ attachmentsDbPath: syncDbPath,+ dbKey: chatKey,+ attachmentsDir: encryptedAttachmentsDir.path,+ metaDir: syncMetaDir.path,+ plaintextDir: attachmentsDir.path+ )+ try newSyncEngine.seedFromOffline(offlineDbPath: offlineDbPath, offlineDbKey: offlineDbKey)+ return OnlineStorePreparation(chatKey: chatKey, chatDb: chatDb, syncEngine: newSyncEngine)+ }.value++ onlineDbKey = preparation.chatKey+ isOnlineMode = true+ chatDb = preparation.chatDb+ syncEngine = preparation.syncEngine+ }++ func handleLogout() {+ if FileManager.default.fileExists(atPath: syncDbPath) {+ do {+ try syncEngine.resetSyncState()+ } catch {+ logger.warning("Failed to reset sync state: \(error)")+ }+ }+ ChatDataCleaner.deleteSyncState()+ try? FileManager.default.removeItem(atPath: onlineDbPath)+ onlineDbKey = nil+ isOnlineMode = false+ reopenSyncStoresIfNeeded(force: true)+ reloadFromDb()+ }++ var currentSession: ChatSession? {+ guard let currentSessionId else { return nil }+ return sessions.first { $0.id == currentSessionId }+ }++ var isAttachmentDownloadBlocked: Bool {+ !currentSessionMissingAttachments.isEmpty+ }++ var attachmentDownloadProgress: Double? {+ let active = attachmentDownloads.filter { $0.status != AttachmentDownloadItem.Status.canceled }+ let total = active.count+ guard total > 0 else { return nil }++ let hasPending = active.contains { item in+ item.status == AttachmentDownloadItem.Status.queued ||+ item.status == AttachmentDownloadItem.Status.downloading ||+ item.status == AttachmentDownloadItem.Status.failed+ }+ guard hasPending else { return nil }++ let completed = active.filter { $0.status == AttachmentDownloadItem.Status.completed }.count+ return Double(completed) / Double(total)+ }++ var attachmentDownloadSummary: (completed: Int, total: Int)? {+ let active = attachmentDownloads.filter { $0.status != AttachmentDownloadItem.Status.canceled }+ let total = active.count+ guard total > 0 else { return nil }++ let hasPending = active.contains { item in+ item.status == AttachmentDownloadItem.Status.queued ||+ item.status == AttachmentDownloadItem.Status.downloading ||+ item.status == AttachmentDownloadItem.Status.failed+ }+ guard hasPending else { return nil }++ let completed = active.filter { $0.status == AttachmentDownloadItem.Status.completed }.count+ return (completed, total)+ }++ var modelDownloadSizeText: String {+ guard let bytes = modelDownloadSizeBytes else { return "Approx. size varies by model" }+ return "Approx. \(bytes.formattedFileSize)"+ }++ private func resetGenerationState(stopRequested: Bool = false) {+ generationTask?.cancel()+ provider.stopGeneration()+ self.stopRequested = stopRequested+ activeGenerationId = nil+ activeGenerationSessionId = nil+ isGenerating = false+ isDownloading = false+ streamingResponse = ""+ streamingParentId = nil+ downloadToast = nil+ }++ func sessionTitle(for sessionId: UUID) -> String {+ guard let title = sessions.first(where: { $0.id == sessionId })?.title else { return "Chat" }+ return Self.sessionTitle(from: title, fallback: "Chat")+ }++ func startNewSession() {+ resetGenerationState()+ draftText = ""+ draftAttachments = []+ editingMessageId = nil++ currentSessionId = nil+ messages = []+ refreshAttachmentDownloadState()+ }++ func selectSession(_ session: ChatSession) {+ resetGenerationState()+ currentSessionId = session.id+ messages = []+ loadMessagesFromDb(for: session.id)+ }++ func deleteSession(_ session: ChatSession) {+ if currentSessionId == session.id {+ resetGenerationState()+ }++ if let nodes = messageStore[session.id] {+ for node in nodes {+ logger.info("Message deleted", details: "id=\(node.id.uuidString) session=\(session.id.uuidString) role=\(node.role.rawValue)")+ }+ }+ logger.info("Session deleted", details: "id=\(session.id.uuidString)")+ try? chatDb.deleteSession(uuid: session.id.uuidString)+ deleteOfflineSessionIfNeeded(session.id)+ sessionSummaries.removeValue(forKey: sessionSummaryKey(session.id))+ persistSessionSummaries()++ sessions.removeAll { $0.id == session.id }+ messageStore[session.id] = nil+ branchSelections[session.id] = nil+ childrenByParentCache[session.id] = nil+ purgeAttachmentDownloads(for: session.id)+ if currentSessionId == session.id {+ currentSessionId = sessions.first?.id+ if let next = currentSessionId {+ messages = []+ loadMessagesFromDb(for: next)+ } else {+ messages = []+ refreshAttachmentDownloadState()+ }+ }+ syncNow()+ }++ private func deleteOfflineSessionIfNeeded(_ sessionId: UUID) {+ guard isOnlineMode else { return }+ do {- let offlineDb = try LlmChatDb.open(++ let offlineDb = try EnsuDb.open(+ mainDbPath: offlineDbPath,+ attachmentsDbPath: syncDbPath,+ key: offlineDbKey+ )+ try offlineDb.deleteSession(uuid: sessionId.uuidString)+ } catch {+ logger.warning("Failed to delete offline session", details: "id=\(sessionId.uuidString) error=\(error)")+ }+ }++ func syncNow(showErrors: Bool = true, showSuccess: Bool = false) {+ if isGenerating {+ pendingSyncRequested = true+ pendingSyncShowErrors = pendingSyncShowErrors || showErrors+ pendingSyncShowSuccess = pendingSyncShowSuccess || showSuccess+ return+ }++ let shouldSync = pendingSyncRequested || showErrors || showSuccess+ let shouldShowErrors = pendingSyncShowErrors || showErrors+ let shouldShowSuccess = pendingSyncShowSuccess || showSuccess+ pendingSyncRequested = false+ pendingSyncShowErrors = false+ pendingSyncShowSuccess = false+ guard shouldSync else { return }+ performSync(showErrors: shouldShowErrors, showSuccess: shouldShowSuccess)+ }++ func syncAfterLogin() {+ guard let auth = buildSyncAuth() else {+ syncState = .error("Sign in to sync")+ return+ }++ Task.detached { [weak self] in+ guard let self else { return }+ do {+ try await self.prepareOnlineStores(auth: auth)+ } catch {+ await MainActor.run {+ self.syncState = .error("Failed to prepare online chats")+ }+ return+ }++ await MainActor.run {+ self.reloadFromDb()+ }++ let syncEngine = await self.syncEngine+ if let localStatus = syncEngine.checkMigrationStatusLocal() {+ await self.handleMigrationStatus(localStatus, auth: auth)+ return+ }++ do {+ let status = try syncEngine.checkMigrationStatus(auth: auth)+ await self.handleMigrationStatus(status, auth: auth)+ } catch {+ await MainActor.run {+ self.syncState = .error("Offline")+ }+ }+ }+ }++ private func handleMigrationStatus(_ status: MigrationState, auth: SyncAuth) async {+ switch status {+ case .inProgress:+ await performBatchedSync(auth: auth)+ case .notNeeded, .complete:+ performSyncWithAuth(auth: auth, showErrors: false, showSuccess: false)+ case .failed:+ await MainActor.run {+ self.syncState = .error("Migration failed")+ }+ }+ }++ private func performSync(showErrors: Bool, showSuccess: Bool) {+ reopenSyncStoresIfNeeded()+ guard let auth = buildSyncAuth() else {+ if showErrors {+ syncErrorMessage = "Sync failed: Sign in to sync"+ }+ return+ }+ performSyncWithAuth(auth: auth, showErrors: showErrors, showSuccess: showSuccess)+ }++ private func performSyncWithAuth(auth: SyncAuth, showErrors: Bool, showSuccess: Bool) {+ let log = logger+ syncState = .syncing+ log.info("Sync started")++ let syncEngine = self.syncEngine+ Task.detached { [weak self, log] in+ guard let self else { return }+ do {+ _ = try syncEngine.sync(auth: auth)+ log.info("Sync success")+ await MainActor.run {+ self.syncState = .idle+ self.reloadFromDb()+ if showSuccess {+ self.syncSuccessMessage = "Sync complete"+ }+ }+ } catch {+ let message = syncErrorMessage(from: error)+ let needsReset = ChatRecovery.shouldResetFromMessage(message)+ let userMessage = needsReset+ ? "\(message). Reset chat data to recover."+ : message+ log.error("Sync failed", error, details: message)+ await MainActor.run {+ self.syncState = .error(userMessage)+ if showErrors {+ self.syncErrorMessage = self.formatSyncErrorMessage(userMessage)+ }+ }+ }+ }+ }++ private func performBatchedSync(auth: SyncAuth) async {+ let config = MigrationConfig(batchSize: 25, priority: .recentFirst)+ syncState = .migrating(processed: 0, total: 0)++ let syncEngine = syncEngine+ do {+ let handler = MigrationProgressHandler { [weak self] progress in+ Task { @MainActor in+ self?.syncState = .migrating(processed: progress.processed, total: progress.total)+ }+ }+ try await Task.detached {+ _ = try syncEngine.syncWithProgress(auth: auth, config: config, callback: handler)+ }.value+ syncState = .idle+ reloadFromDb()+ } catch {+ let message = syncErrorMessage(from: error)+ syncState = .error(message)+ syncErrorMessage = formatSyncErrorMessage(message)+ }+ }++ func deleteAllData() async {+ await Task.detached { ChatDataCleaner.deleteAllData() }.value+ sessions = []+ messages = []+ currentSessionId = nil+ messageStore.removeAll()+ branchSelections.removeAll()+ childrenByParentCache.removeAll()+ attachmentDownloads = []+ currentSessionMissingAttachments = []+ syncState = .idle+ refreshAttachmentDownloadState()+ }++ func beginEditing(message: ChatMessage) {+ guard message.role == .user else { return }+ editingMessageId = message.id+ draftText = message.text+ draftAttachments = message.attachments+ }++ func cancelEditing() {+ editingMessageId = nil+ draftText = ""+ draftAttachments = []+ }++ func addImageAttachment(data: Data, fileName: String?) {+ guard !isGenerating && !isDownloading && !isAttachmentDownloadBlocked else { return }+ isProcessingAttachments = true++ Task.detached { [weak self] in+ guard let self else { return }+ do {+ let id = UUID()+ let url = try self.writeAttachment(data: data, attachmentId: id)+ let attachment = ChatAttachment(+ id: id,+ name: fileName ?? "photo.jpg",+ size: Int64(data.count),+ kind: .image,+ url: url,+ isUploading: false+ )+ await MainActor.run {+ self.draftAttachments.append(attachment)+ self.isProcessingAttachments = false+ }+ } catch {+ await MainActor.run { self.isProcessingAttachments = false }+ }+ }+ }++ func addDocumentAttachment(url: URL) {+ guard !isGenerating && !isDownloading && !isAttachmentDownloadBlocked else { return }+ isProcessingAttachments = true++ Task.detached { [weak self] in+ guard let self else { return }+ do {+ let id = UUID()+ let storedUrl = try self.copyAttachment(from: url, attachmentId: id)+ let size = (try? FileManager.default.attributesOfItem(atPath: storedUrl.path)[.size] as? NSNumber)?.int64Value ?? 0+ let attachment = ChatAttachment(+ id: id,+ name: url.lastPathComponent,+ size: size,+ kind: .document,+ url: storedUrl,+ isUploading: false+ )+ await MainActor.run {+ self.draftAttachments.append(attachment)+ self.isProcessingAttachments = false+ }+ } catch {+ await MainActor.run { self.isProcessingAttachments = false }+ }+ }+ }++ func removeAttachment(_ attachment: ChatAttachment) {+ draftAttachments.removeAll { $0.id == attachment.id }+ }++ func sendDraft() {+ let trimmed = draftText.trimmingCharacters(in: .whitespacesAndNewlines)+ let attachments = draftAttachments+ guard !trimmed.isEmpty || !attachments.isEmpty else { return }++ let sessionId = currentSessionId ?? createSessionForDraft()++ Task { @MainActor in+ let missing = await self.missingAttachments(for: sessionId)+ if !missing.isEmpty {+ self.queueMissingAttachments(for: sessionId, missing: missing)+ return+ }+ self.sendDraftMessage(trimmed: trimmed, attachments: attachments, sessionId: sessionId)+ }+ }++ private func sendDraftMessage(trimmed: String, attachments: [ChatAttachment], sessionId: UUID) {+ let parentId: UUID? = {+ if let editingId = editingMessageId {+ let existing = messageStore[sessionId]?.first { $0.id == editingId }+ return existing?.parentId+ }+ let childrenMap = childrenByParent(sessionId: sessionId)+ return buildSelectedPath(for: sessionId, childrenMap: childrenMap).last?.id+ }()++ let meta: [AttachmentMeta] = attachments.map { attachment in+ AttachmentMeta(+ id: attachment.id.uuidString.lowercased(),+ kind: attachment.kind == .image ? .image : .document,+ size: attachment.size,+ name: attachment.name+ )+ }++ guard let inserted = try? chatDb.insertMessage(+ sessionUuid: sessionId.uuidString,+ sender: .selfUser,+ text: trimmed,+ parentMessageUuid: parentId?.uuidString,+ attachments: meta+ ), let messageId = UUID(uuidString: inserted.uuid) else {+ return+ }++ logger.info(+ "Sent message",+ details: "id=\(messageId.uuidString) session=\(sessionId.uuidString) len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)"+ )++ let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)++ let userNode = MessageNode(+ id: messageId,+ sessionId: sessionId,+ parentId: parentId,+ role: .user,+ text: trimmed,+ timestamp: timestamp,+ attachments: attachments,+ isInterrupted: false,+ tokensPerSecond: nil+ )++ messageStore[sessionId, default: []].append(userNode)+ invalidateChildrenCache(for: sessionId)+ updateSelection(for: sessionId, parentId: parentId, childId: userNode.id)++ draftText = ""+ draftAttachments = []+ editingMessageId = nil++ updateSessionPreview(sessionId: sessionId, preview: trimmed, date: timestamp)+ rebuildMessages(for: sessionId)+ startGeneration(for: userNode)+ syncNow(showErrors: false)+ }++ func stopGenerating() {+ stopRequested = true+ provider.stopGeneration()+ }++ func confirmOverflowTrim() {+ guard let pendingOverflow else { return }+ guard let node = messageStore[pendingOverflow.sessionId]?.first(where: { $0.id == pendingOverflow.messageId }) else {+ cancelOverflowDialog()+ return+ }+ overflowBypassMessageId = pendingOverflow.messageId+ self.pendingOverflow = nil+ overflowAlert = nil+ startGeneration(for: node)+ }++ func cancelOverflowDialog() {+ pendingOverflow = nil+ overflowBypassMessageId = nil+ overflowAlert = nil+ }++ func refreshModelDownloadInfo() {+ let target = modelSettings.currentTarget()+ isModelDownloaded = provider.isModelDownloaded(target: target)+ if isModelDownloaded {+ modelDownloadSizeBytes = nil+ return+ }++ Task { [weak self] in+ guard let self else { return }+ let size = await provider.estimatedDownloadSize(target: target)+ await MainActor.run {+ self.modelDownloadSizeBytes = size+ }+ }+ }++ func startModelDownload(userInitiated: Bool = true) {+ guard !isDownloading && !isGenerating else { return }+ if userInitiated {+ hasRequestedModelDownload = true+ }++ let target = modelSettings.currentTarget()+ let isDownloaded = provider.isModelDownloaded(target: target)+ if isDownloaded {+ isModelDownloaded = true+ modelDownloadSizeBytes = nil+ return+ }++ isDownloading = true+ modelDownloadLoggedStart = true+ logger.info("Model download started", details: "model=\(target.id)")++ modelDownloadTask?.cancel()+ modelDownloadTask = Task {+ do {+ try await provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ self.handleProgress(progress)+ }+ }+ } catch {+ if isCancellation(error) {+ return+ }+ if self.modelDownloadLoggedStart {+ self.logger.error("Model download failed", error)+ self.modelDownloadLoggedStart = false+ } else {+ self.logger.error("Model load failed", error)+ }+ await MainActor.run {+ self.downloadToast = DownloadToastState(+ phase: .errorDownload,+ percent: -1,+ status: error.localizedDescription,+ offerRetryDownload: true+ )+ self.isDownloading = false+ }+ }+ }+ }++ func autoStartModelDownloadIfNeeded() {+ guard !isDownloading && !isGenerating else { return }+ let target = modelSettings.currentTarget()+ let isDownloaded = provider.isModelDownloaded(target: target)+ isModelDownloaded = isDownloaded+ if !isDownloaded {+ return+ }+ modelDownloadSizeBytes = nil+ modelDownloadTask?.cancel()+ modelDownloadTask = Task { [weak self] in+ guard let self else { return }+ do {+ try await self.provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ self.handleProgress(progress)+ }+ }+ } catch {+ if self.isCancellation(error) {+ return+ }+ await MainActor.run {+ self.downloadToast = DownloadToastState(+ phase: .errorLoad,+ percent: -1,+ status: error.localizedDescription,+ offerRetryDownload: true+ )+ self.isDownloading = false+ }+ }+ }+ }++ func cancelDownload() {+ resetGenerationState(stopRequested: true)+ modelDownloadTask?.cancel()+ modelDownloadTask = nil+ provider.cancelDownload()+ if modelDownloadLoggedStart {+ logger.info("Model download cancelled")+ modelDownloadLoggedStart = false+ }+ hasRequestedModelDownload = false+ refreshModelDownloadInfo()+ }++ func retryDownload() {+ startModelDownload(userInitiated: true)+ }++ func retryAssistantResponse(_ message: ChatMessage) {+ guard message.role == .assistant else { return }+ if isGenerating {+ stopGenerating()+ }+ guard let sessionId = currentSessionId else { return }+ guard let parent = messageStore[sessionId]?.first(where: { $0.id == message.id })?.parentId,+ let userNode = messageStore[sessionId]?.first(where: { $0.id == parent }) else {+ return+ }+ Task { @MainActor in+ let missing = await self.missingAttachments(for: sessionId)+ if !missing.isEmpty {+ self.queueMissingAttachments(for: sessionId, missing: missing)+ return+ }+ self.provider.resetContext()+ self.startGeneration(for: userNode)+ self.syncNow(showErrors: false)+ }+ }++ func changeBranch(for message: ChatMessage, delta: Int) {+ if isGenerating {+ stopGenerating()+ }+ guard let sessionId = currentSessionId else { return }+ guard let node = messageStore[sessionId]?.first(where: { $0.id == message.id }) else { return }+ let parentKey = node.parentId?.uuidString ?? "__root__"+ let parentId = node.parentId ?? rootId+ let siblings = dedupeSiblings(childrenFor(sessionId: sessionId, parentId: parentId))+ guard !siblings.isEmpty else { return }+ let selectionMap = branchSelections[sessionId] ?? [:]+ let currentId = selectionMap[parentKey] ?? siblings.last?.id+ let currentIndex = siblings.firstIndex { $0.id == currentId } ?? (siblings.count - 1)+ let nextIndex = max(0, min(siblings.count - 1, currentIndex + delta))+ branchSelections[sessionId, default: [:]][parentKey] = siblings[nextIndex].id+ rebuildMessages(for: sessionId)+ }++ private func createSessionForDraft() -> UUID {+ let created = (try? chatDb.createSession(title: "New chat"))+ let sessionId = created.flatMap { UUID(uuidString: $0.uuid) } ?? UUID()+ let updatedAt = created.map { Date(timeIntervalSince1970: Double($0.updatedAtUs) / 1_000_000.0) } ?? Date()++ logger.info("Session created", details: "id=\(sessionId.uuidString)")+ let session = ChatSession(id: sessionId, title: created?.title ?? "New chat", lastMessage: "", updatedAt: updatedAt)+ sessions.insert(session, at: 0)+ currentSessionId = session.id+ messageStore[session.id] = []+ branchSelections[session.id] = [:]+ invalidateChildrenCache(for: session.id)+ refreshAttachmentDownloadState()+ return session.id+ }++ private func startGeneration(for userNode: MessageNode) {+ generationTask?.cancel()+ sessionSummaryTask?.cancel()+ stopRequested = false++ let target = modelSettings.currentTarget()+ let prompt = buildPrompt(text: userNode.text, attachments: userNode.attachments)+ let historySelection = buildHistorySelection(+ sessionId: userNode.sessionId,+ promptText: prompt.text,+ promptImageCount: prompt.imageFiles.count,+ currentMessageId: userNode.id,+ target: target+ )++ if historySelection.wasTrimmed && overflowBypassMessageId != userNode.id {+ pendingOverflow = PendingOverflow(sessionId: userNode.sessionId, messageId: userNode.id)+ overflowAlert = OverflowAlertState(+ inputTokens: historySelection.inputTokens,+ inputBudget: historySelection.inputBudget,+ contextLength: target.contextLength ?? 4096,+ maxOutput: target.maxTokens ?? 1024+ )+ return+ }++ overflowBypassMessageId = nil+ pendingOverflow = nil+ overflowAlert = nil++ let generationId = UUID()+ activeGenerationId = generationId+ activeGenerationSessionId = userNode.sessionId+ isGenerating = true+ isDownloading = false+ hasRequestedModelDownload = true+ streamingResponse = ""+ streamingParentId = userNode.id+ downloadToast = nil+ rebuildMessages(for: userNode.sessionId)++ generationTask = Task {+ do {+ try await provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.handleProgress(progress)+ }+ }+ } catch {+ if isCancellation(error) {+ if self.activeGenerationId == generationId {+ isGenerating = false+ isDownloading = false+ streamingParentId = nil+ downloadToast = nil+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }+ syncNow(showErrors: false)+ return+ }+ if self.activeGenerationId == generationId {+ isGenerating = false+ isDownloading = false+ streamingParentId = nil+ downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: error.localizedDescription, offerRetryDownload: true)+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }+ syncNow(showErrors: false)+ return+ }++ let history = historySelection.messages+ let systemMessage = InferenceMessage(text: Self.systemPrompt, role: .system, hasAttachments: false)+ let messages = [systemMessage] + history + [InferenceMessage(text: prompt.text, role: .user, hasAttachments: !userNode.attachments.isEmpty)]++ let bufferLock = NSLock()+ var buffer = ""+ var tokenCount = 0+ let uiUpdateInterval: TimeInterval = 0.05+ var lastUiUpdate = Date.distantPast+ var pendingSnapshot: String?+ var updateWorkItem: DispatchWorkItem?++ let scheduleStreamingUpdate = {+ bufferLock.lock()+ if updateWorkItem != nil {+ bufferLock.unlock()+ return+ }+ let workItem = DispatchWorkItem { [weak self] in+ guard let self else { return }+ bufferLock.lock()+ let snapshot = pendingSnapshot+ pendingSnapshot = nil+ updateWorkItem = nil+ lastUiUpdate = Date()+ bufferLock.unlock()+ guard let snapshot else { return }+ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.streamingResponse = snapshot+ }+ }+ updateWorkItem = workItem+ bufferLock.unlock()+ DispatchQueue.main.asyncAfter(deadline: .now() + uiUpdateInterval, execute: workItem)+ }++ do {+ let summary = try await provider.generateChat(+ target: target,+ messages: messages,+ imageFiles: prompt.imageFiles,+ temperature: resolveTemperature(),+ maxTokens: target.maxTokens ?? 1024,+ onToken: { token in+ let tokenEstimate = max(1, token.count / 4)+ var snapshot = ""+ var shouldUpdateNow = false++ bufferLock.lock()+ buffer.append(token)+ tokenCount += tokenEstimate+ snapshot = buffer+ pendingSnapshot = snapshot+ let now = Date()+ shouldUpdateNow = now.timeIntervalSince(lastUiUpdate) >= uiUpdateInterval+ if shouldUpdateNow {+ lastUiUpdate = now+ pendingSnapshot = nil+ updateWorkItem?.cancel()+ updateWorkItem = nil+ }+ bufferLock.unlock()++ if shouldUpdateNow {+ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.streamingResponse = snapshot+ }+ } else {+ scheduleStreamingUpdate()+ }+ }+ )++ finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: summary.totalTimeMs, interrupted: false, generationId: generationId)+ } catch {+ let wasCancelled = stopRequested || isCancellation(error)+ if activeGenerationId == generationId && !wasCancelled {+ let details = "session=\(userNode.sessionId.uuidString) promptLen=\(prompt.text.count) responseLen=\(buffer.count) tokens=\(tokenCount)"+ logger.error("Generation failed", error, details: details)+ generationErrorMessage = "Response failed. Try again."+ }+ finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: nil, interrupted: true, generationId: generationId)+ }+ }+ }++ private func finishGeneration(parent: MessageNode, response: String, tokenCount: Int, totalTimeMs: Int64?, interrupted: Bool, generationId: UUID) {+ let trimmed = response.trimmingCharacters(in: .whitespacesAndNewlines)+ let isActiveGeneration = activeGenerationId == generationId+ if trimmed.isEmpty {+ if isActiveGeneration && !interrupted && generationErrorMessage == nil {+ let details = "session=\(parent.sessionId.uuidString) promptLen=\(parent.text.count)"+ logger.warning("Generation returned empty response", details: details)+ generationErrorMessage = "No response from model. Try again."+ }+ } else {+ let tokensPerSecond: Double? = {+ guard let totalTimeMs, totalTimeMs > 0 else { return nil }+ return Double(tokenCount) / (Double(totalTimeMs) / 1000.0)+ }()++ let meta: [AttachmentMeta] = []+ if let inserted = try? chatDb.insertMessage(+ sessionUuid: parent.sessionId.uuidString,+ sender: .other,+ text: trimmed,+ parentMessageUuid: parent.id.uuidString,+ attachments: meta+ ), let assistantId = UUID(uuidString: inserted.uuid) {+ logger.info("Message created", details: "id=\(assistantId.uuidString) session=\(parent.sessionId.uuidString) role=assistant")+ let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)+ let assistant = MessageNode(+ id: assistantId,+ sessionId: parent.sessionId,+ parentId: parent.id,+ role: .assistant,+ text: trimmed,+ timestamp: timestamp,+ attachments: [],+ isInterrupted: interrupted,+ tokensPerSecond: tokensPerSecond+ )++ messageStore[parent.sessionId, default: []].append(assistant)+ invalidateChildrenCache(for: parent.sessionId)+ updateSelection(for: parent.sessionId, parentId: parent.id, childId: assistant.id)+ updateSessionPreview(sessionId: parent.sessionId, preview: trimmed, date: assistant.timestamp)+ }+ }++ if isActiveGeneration {+ isGenerating = false+ isDownloading = false+ streamingResponse = ""+ streamingParentId = nil+ downloadToast = nil+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }++ if currentSessionId == parent.sessionId {+ rebuildMessages(for: parent.sessionId)+ }+ syncNow(showErrors: false)+ scheduleSessionSummary(for: parent.sessionId)+ }++ private func handleProgress(_ progress: InferenceDownloadProgress) {+ if progress.percent == -1 {+ if modelDownloadLoggedStart {+ logger.error("Model download failed", details: progress.status)+ modelDownloadLoggedStart = false+ }+ downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: progress.status, offerRetryDownload: true)+ isDownloading = false+ return+ }++ let isLoading = progress.status.localizedCaseInsensitiveContains("Loading")+ let isReady = progress.status.localizedCaseInsensitiveContains("Ready")++ if isLoading {+ downloadToast = DownloadToastState(phase: .loading, percent: progress.percent, status: progress.status, offerRetryDownload: false)+ isDownloading = true+ return+ }++ if isReady {+ if modelDownloadLoggedStart {+ logger.info("Model download complete", details: progress.status)+ modelDownloadLoggedStart = false+ }+ downloadToast = DownloadToastState(phase: .complete, percent: 100, status: progress.status, offerRetryDownload: false)+ isDownloading = false+ isModelDownloaded = true+ modelDownloadSizeBytes = nil+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: 1_500_000_000)+ if self.downloadToast?.phase == .complete {+ self.downloadToast = nil+ }+ }+ return+ }++ downloadToast = DownloadToastState(phase: .downloading, percent: progress.percent, status: progress.status, offerRetryDownload: false)+ isDownloading = progress.percent >= 0 && progress.percent < 100+ }++ private func buildSyncAuth() -> SyncAuth? {+ guard CredentialStore.shared.hasConfiguredAccount,+ let token = CredentialStore.shared.token,+ let masterKey = CredentialStore.shared.masterKey else {+ return nil+ }++ let baseUrl = EnsuDeveloperSettings.networkConfiguration.apiEndpoint.absoluteString+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String+ return SyncAuth(+ baseUrl: baseUrl,+ authToken: token,+ masterKey: masterKey,+ userAgent: EntePlatform.current.userAgent,+ clientPackage: EnteApp.ensu.packageIdentifier,+ clientVersion: version+ )+ }++ private nonisolated func syncErrorMessage(from error: Error) -> String {+ if let syncError = error as? SyncError {+ switch syncError {+ case let .Message(message):+ return message+ case .SyncInProgress:+ return "Sync already in progress"+ }+ }+ let description = error.localizedDescription+ if description.isEmpty {+ return String(describing: error)+ }+ return description+ }++ private func formatSyncErrorMessage(_ message: String) -> String {+ let normalized = message.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ if normalized.contains("sync already in progress") {+ return message+ }+ return "Sync failed: \(message)"+ }++ private func queueMissingAttachments(for sessionId: UUID, missing: [AttachmentDownloadItem]? = nil) {+ Task { @MainActor in+ let resolvedMissing: [AttachmentDownloadItem]+ if let missing {+ resolvedMissing = missing+ } else {+ resolvedMissing = await self.missingAttachments(for: sessionId)+ }++ guard !resolvedMissing.isEmpty else {+ self.refreshAttachmentDownloadState(missing: [])+ return+ }++ var updated = self.attachmentDownloads+ for item in resolvedMissing {+ if let existingIndex = updated.firstIndex(where: { $0.id == item.id }) {+ if updated[existingIndex].status == AttachmentDownloadItem.Status.failed ||+ updated[existingIndex].status == AttachmentDownloadItem.Status.canceled {+ updated[existingIndex].status = AttachmentDownloadItem.Status.queued+ updated[existingIndex].errorMessage = nil+ }+ } else {+ updated.append(item)+ }+ }++ self.attachmentDownloads = updated+ for item in resolvedMissing {+ if !self.attachmentDownloadQueue.contains(item.id) && self.attachmentDownloadTasks[item.id] == nil {+ self.attachmentDownloadQueue.append(item.id)+ }+ }++ self.refreshAttachmentDownloadState(missing: resolvedMissing)+ self.startNextAttachmentDownloads()+ }+ }++ private func missingAttachments(for sessionId: UUID) async -> [AttachmentDownloadItem] {+ guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }+ let attachments = nodes.flatMap { $0.attachments }+ let existingDownloads = attachmentDownloads+ let attachmentsDir = attachmentsDir++ let result: (missing: [AttachmentDownloadItem], availableIds: Set<String>) = await Task.detached {+ var seen = Set<String>()+ var missing: [AttachmentDownloadItem] = []+ var availableIds = Set<String>()++ for attachment in attachments {+ let id = attachment.id.uuidString.lowercased()+ if seen.contains(id) { continue }+ seen.insert(id)+ let path = attachmentsDir.appendingPathComponent(id).path+ if FileManager.default.fileExists(atPath: path) {+ availableIds.insert(id)+ continue+ }+ let existing = existingDownloads.first { $0.id == id }+ let status = existing?.status ?? AttachmentDownloadItem.Status.queued+ missing.append(AttachmentDownloadItem(+ id: id,+ sessionId: sessionId,+ name: attachment.name,+ size: attachment.size,+ status: status,+ errorMessage: existing?.errorMessage+ ))+ }++ return (missing, availableIds)+ }.value++ if !result.availableIds.isEmpty {+ for id in result.availableIds {+ attachmentDownloadTasks[id]?.cancel()+ attachmentDownloadTasks[id] = nil+ }+ attachmentDownloadQueue.removeAll { result.availableIds.contains($0) }+ attachmentDownloads.removeAll { result.availableIds.contains($0.id) }+ }++ return result.missing+ }++ private func startNextAttachmentDownloads() {+ reopenSyncStoresIfNeeded()+ guard attachmentDownloadTasks.count < maxAttachmentDownloads else { return }+ guard let auth = buildSyncAuth() else { return }++ let syncEngine = self.syncEngine+ while attachmentDownloadTasks.count < maxAttachmentDownloads, !attachmentDownloadQueue.isEmpty {+ let id = attachmentDownloadQueue.removeFirst()+ guard let index = attachmentDownloads.firstIndex(where: { $0.id == id }) else { continue }+ if attachmentDownloads[index].status == AttachmentDownloadItem.Status.canceled ||+ attachmentDownloads[index].status == AttachmentDownloadItem.Status.completed {+ continue+ }+ let sessionId = attachmentDownloads[index].sessionId+ attachmentDownloads[index].status = AttachmentDownloadItem.Status.downloading++ let task = Task.detached { [weak self] in+ guard let self else { return }+ do {+ _ = try syncEngine.downloadAttachment(+ attachmentId: id,+ sessionUuid: sessionId.uuidString,+ auth: auth+ )+ await MainActor.run {+ self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.completed, errorMessage: nil)+ }+ } catch {+ let message = self.syncErrorMessage(from: error)+ await MainActor.run {+ self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.failed, errorMessage: message)+ }+ }+ }+ attachmentDownloadTasks[id] = task+ }+ }++ private func updateAttachmentDownloadStatus(+ id: String,+ status: AttachmentDownloadItem.Status,+ errorMessage: String?+ ) {+ if let index = attachmentDownloads.firstIndex(where: { $0.id == id }) {+ if attachmentDownloads[index].status != AttachmentDownloadItem.Status.canceled {+ attachmentDownloads[index].status = status+ attachmentDownloads[index].errorMessage = status == AttachmentDownloadItem.Status.failed ? errorMessage : nil+ }+ }+ attachmentDownloadTasks[id] = nil+ refreshAttachmentDownloadState()+ startNextAttachmentDownloads()+ }++ private func refreshAttachmentDownloadState(missing: [AttachmentDownloadItem]? = nil) {+ guard let sessionId = currentSessionId else {+ currentSessionMissingAttachments = []+ return+ }++ if let missing {+ currentSessionMissingAttachments = missing+ return+ }++ Task { @MainActor in+ self.currentSessionMissingAttachments = await self.missingAttachments(for: sessionId)+ }+ }++ func cancelAttachmentDownload(_ id: String) {+ if let task = attachmentDownloadTasks[id] {+ task.cancel()+ attachmentDownloadTasks[id] = nil+ }+ if let index = attachmentDownloads.firstIndex(where: { $0.id == id }) {+ attachmentDownloads[index].status = AttachmentDownloadItem.Status.canceled+ }+ attachmentDownloadQueue.removeAll { $0 == id }+ refreshAttachmentDownloadState()+ startNextAttachmentDownloads()+ }++ private func purgeAttachmentDownloads(for sessionId: UUID) {+ let ids = attachmentDownloads.filter { $0.sessionId == sessionId }.map { $0.id }+ for id in ids {+ attachmentDownloadTasks[id]?.cancel()+ attachmentDownloadTasks[id] = nil+ attachmentDownloadQueue.removeAll { $0 == id }+ attachmentDownloads.removeAll { $0.id == id }+ }+ refreshAttachmentDownloadState()+ startNextAttachmentDownloads()+ }++ private nonisolated static func buildSessions(+ from loaded: [LlmChatSession],- chatDb: LlmChatDb,++ chatDb: EnsuDb,+ summaries: [String: String]+ ) -> [ChatSession] {+ let sessions: [ChatSession] = loaded.compactMap { session in+ guard let id = UUID(uuidString: session.uuid) else { return nil }+ let messages = (try? chatDb.getMessages(sessionUuid: session.uuid)) ?? []+ let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }+ let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""+ let lastMessageNode = sortedMessages.last+ let lastMessage = lastMessageNode?.text ?? ""+ let summary = summaries[session.uuid.lowercased()]+ let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ session.title.caseInsensitiveCompare("New chat") == .orderedSame+ let seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)+ let title = Self.sessionTitle(from: seedTitle, fallback: session.title)+ let updatedAtUs = lastMessageNode?.createdAtUs ?? session.updatedAtUs+ return ChatSession(+ id: id,+ title: title,+ lastMessage: lastMessage,+ updatedAt: Date(timeIntervalSince1970: Double(updatedAtUs) / 1_000_000.0)+ )+ }+ return sessions.sorted { $0.updatedAt > $1.updatedAt }+ }++ private func reloadFromDb() {+ reloadTask?.cancel()+ reopenSyncStoresIfNeeded()+ let chatDb = chatDb+ let summaries = sessionSummaries+ let selected = currentSessionId++ reloadTask = Task.detached { [weak self, chatDb, summaries, selected] in+ let loaded = (try? chatDb.listSessions()) ?? []+ let refreshed = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)++ let resolved = selected.flatMap { id in+ refreshed.first(where: { $0.id == id })?.id+ } ?? (selected == nil ? nil : refreshed.first?.id)++ if Task.isCancelled { return }++ await MainActor.run {+ guard let self else { return }+ if Task.isCancelled { return }++ let previousSessionId = self.currentSessionId+ let shouldPreserveMessages = resolved == previousSessionId && !self.messages.isEmpty+ let preservedMessages = self.messages+ let preservedMessageStore = self.messageStore+ let preservedBranchSelections = self.branchSelections++ self.sessions = refreshed+ self.currentSessionId = resolved+ self.messageStore = [:]+ self.branchSelections = [:]+ self.childrenByParentCache = [:]++ for session in refreshed {+ if shouldPreserveMessages, session.id == resolved, let nodes = preservedMessageStore[session.id] {+ self.messageStore[session.id] = nodes+ self.branchSelections[session.id] = preservedBranchSelections[session.id] ?? [:]+ } else {+ self.messageStore[session.id] = []+ self.branchSelections[session.id] = [:]+ }+ }++ if shouldPreserveMessages {+ self.messages = preservedMessages+ } else {+ self.messages = []+ }++ if let current = resolved {+ self.loadMessagesFromDb(for: current)+ } else {+ self.refreshAttachmentDownloadState()+ }+ }+ }+ }++ private func loadMessagesFromDb(for sessionId: UUID) {+ reopenSyncStoresIfNeeded()+ if messageStore[sessionId] == nil {+ messageStore[sessionId] = []+ branchSelections[sessionId] = [:]+ }++ let chatDb = chatDb+ let attachmentsDir = attachmentsDir++ Task.detached { [weak self, chatDb, attachmentsDir] in+ guard let self else { return }++ let rawMessages = (try? chatDb.getMessages(sessionUuid: sessionId.uuidString)) ?? []++ let nodes: [MessageNode] = rawMessages.compactMap { msg in+ guard let messageId = UUID(uuidString: msg.uuid) else { return nil }+ let parentId = msg.parentMessageUuid.flatMap { UUID(uuidString: $0) }+ let role: ChatMessage.Role = (msg.sender == .selfUser) ? .user : .assistant+ let timestamp = Date(timeIntervalSince1970: Double(msg.createdAtUs) / 1_000_000.0)++ let attachments: [ChatAttachment] = msg.attachments.compactMap { meta in+ guard let attachmentId = UUID(uuidString: meta.id) else { return nil }+ let kind: ChatAttachment.Kind = (meta.kind == .image) ? .image : .document+ let url = attachmentsDir.appendingPathComponent(meta.id)+ return ChatAttachment(+ id: attachmentId,+ name: meta.name,+ size: meta.size,+ kind: kind,+ url: url,+ isUploading: false+ )+ }++ return MessageNode(+ id: messageId,+ sessionId: sessionId,+ parentId: parentId,+ role: role,+ text: msg.text,+ timestamp: timestamp,+ attachments: attachments,+ isInterrupted: false,+ tokensPerSecond: nil+ )+ }++ await MainActor.run {+ guard self.messageStore[sessionId] != nil else { return }+ self.messageStore[sessionId] = nodes+ // Branch selection is computed in-memory.+ self.branchSelections[sessionId] = [:]+ self.invalidateChildrenCache(for: sessionId)+ if self.currentSessionId == sessionId {+ self.rebuildMessages(for: sessionId)+ self.queueMissingAttachments(for: sessionId)+ }+ }+ }+ }++ private func rebuildMessages(for sessionId: UUID) {+ let childrenMap = childrenByParent(sessionId: sessionId)+ let path = buildSelectedPath(for: sessionId, childrenMap: childrenMap)+ let selectionMap = branchSelections[sessionId, default: [:]]++ messages = path.map { node in+ let parentKey = node.parentId?.uuidString ?? "__root__"+ let parentId = node.parentId ?? rootId+ let siblings = dedupeSiblings(childrenMap[parentId] ?? [])+ let selectedId = selectionMap[parentKey]+ let index = siblings.firstIndex { $0.id == selectedId } ?? (siblings.count - 1)++ return ChatMessage(+ id: node.id,+ role: node.role,+ text: node.text,+ timestamp: node.timestamp,+ attachments: node.attachments,+ isInterrupted: node.isInterrupted,+ tokensPerSecond: node.tokensPerSecond,+ branchIndex: max(1, index + 1),+ branchCount: max(1, siblings.count)+ )+ }+ }++ private func buildSelectedPath(for sessionId: UUID, childrenMap: [UUID: [MessageNode]]) -> [MessageNode] {+ guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }+ let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })+ let roots = dedupeSiblings(nodes.filter { node in+ guard let parentId = node.parentId else { return true }+ return byId[parentId] == nil+ })+ guard !roots.isEmpty else { return [] }++ let selectionMap = branchSelections[sessionId, default: [:]]+ var current = selectChild(selectionMap: selectionMap, selectionKey: "__root__", candidates: roots)+ var path: [MessageNode] = []+ var visited = Set<UUID>()++ while let node = current, visited.insert(node.id).inserted {+ path.append(node)+ if node.id == streamingParentId { break }+ let children = dedupeSiblings(childrenMap[node.id] ?? [])+ if children.isEmpty { break }+ current = selectChild(selectionMap: selectionMap, selectionKey: node.id.uuidString, candidates: children)+ }+ return path+ }++ private func selectChild(selectionMap: [String: UUID], selectionKey: String, candidates: [MessageNode]) -> MessageNode? {+ guard !candidates.isEmpty else { return nil }+ if let selectedId = selectionMap[selectionKey],+ let selected = candidates.first(where: { $0.id == selectedId }) {+ return selected+ }+ return candidates.last+ }++ private func invalidateChildrenCache(for sessionId: UUID) {+ childrenByParentCache[sessionId] = nil+ }++ private func childrenByParent(sessionId: UUID) -> [UUID: [MessageNode]] {+ if let cached = childrenByParentCache[sessionId] {+ return cached+ }+ var map: [UUID: [MessageNode]] = [:]+ guard let nodes = messageStore[sessionId] else { return map }+ let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })+ for node in nodes {+ let parent = node.parentId.flatMap { byId[$0] != nil ? $0 : nil } ?? rootId+ map[parent, default: []].append(node)+ }+ childrenByParentCache[sessionId] = map+ return map+ }++ private func childrenFor(sessionId: UUID, parentId: UUID) -> [MessageNode] {+ let map = childrenByParent(sessionId: sessionId)+ return map[parentId] ?? []+ }++ private func dedupeSiblings(_ nodes: [MessageNode]) -> [MessageNode] {+ guard nodes.count > 1 else { return nodes.sorted(by: { $0.timestamp < $1.timestamp }) }+ let sorted = nodes.sorted(by: { $0.timestamp < $1.timestamp })+ var result: [MessageNode] = []+ for node in sorted {+ if let last = result.last, isDuplicate(last, node) {+ continue+ }+ result.append(node)+ }+ return result+ }++ private func isDuplicate(_ lhs: MessageNode, _ rhs: MessageNode) -> Bool {+ guard lhs.role == rhs.role else { return false }+ guard lhs.text == rhs.text else { return false }+ guard attachmentSignature(lhs.attachments) == attachmentSignature(rhs.attachments) else { return false }+ return abs(lhs.timestamp.timeIntervalSince(rhs.timestamp)) <= 2+ }++ private func attachmentSignature(_ attachments: [ChatAttachment]) -> [String] {+ attachments.map { "\($0.kind)-\($0.name)" }+ }++ private func updateSelection(for sessionId: UUID, parentId: UUID?, childId: UUID) {+ let key = parentId?.uuidString ?? "__root__"+ branchSelections[sessionId, default: [:]][key] = childId+ }++ private func updateSessionPreview(sessionId: UUID, preview: String, date: Date) {+ sessions = sessions.map { session in+ guard session.id == sessionId else { return session }+ var updated = session+ let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ session.title.caseInsensitiveCompare("New chat") == .orderedSame+ if isPlaceholderTitle {+ let updatedTitle = Self.sessionTitle(from: preview, fallback: session.title)+ if updatedTitle != session.title {+ _ = try? chatDb.updateSessionTitle(uuid: sessionId.uuidString, title: updatedTitle)+ }+ updated.title = updatedTitle+ }+ updated.lastMessage = preview+ updated.updatedAt = date+ return updated+ }+ }++ private func scheduleSessionSummary(for sessionId: UUID) {+ sessionSummaryTask?.cancel()+ let summaryKey = sessionSummaryKey(sessionId)+ guard sessionSummaries[summaryKey] == nil else { return }+ guard let summaryInput = buildSessionSummaryInput(sessionId: sessionId) else { return }+ let existingSummary = sessionSummaries[summaryKey]+ let target = modelSettings.currentTarget()+ let provider = provider++ sessionSummaryTask = Task.detached(priority: .utility) { [weak self] in+ guard let self else { return }+ do {+ try await Task.sleep(nanoseconds: 200_000_000)+ } catch {+ return+ }+ guard !Task.isCancelled else { return }++ let summary = await Self.generateSessionSummary(+ input: summaryInput.text,+ fallback: summaryInput.fallback,+ existingSummary: existingSummary,+ provider: provider,+ target: target+ )+ guard let summary else { return }++ await MainActor.run {+ self.applySessionSummary(sessionId: sessionId, summary: summary)+ }+ }+ }++ private func buildSessionSummaryInput(sessionId: UUID) -> (text: String, fallback: String)? {+ guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return nil }+ let sorted = nodes.sorted(by: { $0.timestamp < $1.timestamp })+ guard let firstUser = sorted.first(where: { $0.role == .user }) else { return nil }+ let input = "User: \(firstUser.text)"+ let fallback = Self.summarizeQuestion(firstUser.text)+ return (text: input, fallback: fallback)+ }++ private func applySessionSummary(sessionId: UUID, summary: String) {+ let sanitized = Self.sessionTitle(from: summary, fallback: "New chat")+ guard !sanitized.isEmpty else { return }+ let summaryKey = sessionSummaryKey(sessionId)+ if sessionSummaries[summaryKey] == sanitized { return }+ sessionSummaries[summaryKey] = sanitized+ persistSessionSummaries()+ _ = try? chatDb.updateSessionTitle(uuid: sessionId.uuidString, title: sanitized)+ sessions = sessions.map { session in+ guard session.id == sessionId else { return session }+ var updated = session+ updated.title = sanitized+ return updated+ }+ }++ private func persistSessionSummaries() {+ guard let data = try? JSONEncoder().encode(sessionSummaries) else { return }+ UserDefaults.standard.set(data, forKey: Self.sessionSummaryStoreKey)+ }++ private func sessionSummaryKey(_ id: UUID) -> String {+ id.uuidString.lowercased()+ }++ private func sessionSummaryKey(_ id: String) -> String {+ id.lowercased()+ }++ private static func loadSessionSummaries() -> [String: String] {+ guard let data = UserDefaults.standard.data(forKey: Self.sessionSummaryStoreKey) else { return [:] }+ return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]+ }++ private static func summarizeQuestion(_ text: String) -> String {+ let cleaned = sanitizeTitleText(text)+ guard !cleaned.isEmpty else { return "" }+ let words = cleaned.split(separator: " ").map {+ String($0).trimmingCharacters(in: .punctuationCharacters)+ }.filter { !$0.isEmpty }+ guard !words.isEmpty else { return "" }+ let summaryWords = words.prefix(Self.sessionSummaryMaxWords)+ return summaryWords.joined(separator: " ")+ }++ private nonisolated static func sanitizeTitleText(_ text: String) -> String {+ text+ .replacingOccurrences(of: "[\\r\\n\\t]+", with: " ", options: .regularExpression)+ .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ }++ nonisolated static func sessionTitle(from text: String, fallback: String = "New chat") -> String {+ let trimmed = sanitizeTitleText(text)+ guard !trimmed.isEmpty else { return fallback }+ if trimmed.count <= Self.sessionTitleMaxLength {+ return trimmed+ }+ let prefix = trimmed.prefix(Self.sessionTitleMaxLength)+ return String(prefix).trimmingCharacters(in: .whitespacesAndNewlines) + "…"+ }++ private static func generateSessionSummary(+ input: String,+ fallback: String,+ existingSummary: String?,+ provider: InferenceRsProvider,+ target: InferenceModelTarget+ ) async -> String? {+ if let existingSummary, !existingSummary.isEmpty { return nil }+ let cleanedInput = sanitizeTitleText(input)+ guard !cleanedInput.isEmpty else { return sessionTitle(from: fallback, fallback: fallback) }++ let messages = [+ InferenceMessage(text: sessionSummarySystemPrompt, role: .system, hasAttachments: false),+ InferenceMessage(text: cleanedInput, role: .user, hasAttachments: false)+ ]++ let bufferLock = NSLock()+ var buffer = ""++ do {+ _ = try await provider.generateChat(+ target: target,+ messages: messages,+ imageFiles: [],+ temperature: 0.2,+ maxTokens: 64+ ) { token in+ bufferLock.lock()+ buffer.append(token)+ bufferLock.unlock()+ }+ } catch {+ let fallbackSummary = summarizeQuestion(fallback)+ return fallbackSummary.isEmpty ? nil : sessionTitle(from: fallbackSummary, fallback: fallback)+ }++ let raw = sanitizeTitleText(buffer)+ guard !raw.isEmpty else { return sessionTitle(from: fallback, fallback: fallback) }+ let words = raw.split(separator: " ").map { String($0) }.filter { !$0.isEmpty }+ guard !words.isEmpty else { return nil }+ let summaryWords = words.prefix(Self.sessionSummaryMaxWords)+ let summary = summaryWords.joined(separator: " ")+ return sessionTitle(from: summary, fallback: fallback)+ }++ private func isCancellation(_ error: Error) -> Bool {+ if error is CancellationError { return true }+ return error.localizedDescription.localizedCaseInsensitiveContains("cancel")+ }++ private nonisolated func attachmentsDirectory() throws -> URL {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? FileManager.default.temporaryDirectory+ let dir = base.appendingPathComponent("llmchat", isDirectory: true)+ .appendingPathComponent("chat_attachments", isDirectory: true)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)+ return dir+ }++ private nonisolated func writeAttachment(data: Data, attachmentId: UUID) throws -> URL {+ let dir = try attachmentsDirectory()+ let destination = dir.appendingPathComponent(attachmentId.uuidString.lowercased())+ try data.write(to: destination, options: .atomic)+ return destination+ }++ private nonisolated func copyAttachment(from url: URL, attachmentId: UUID) throws -> URL {+ let dir = try attachmentsDirectory()+ let destination = dir.appendingPathComponent(attachmentId.uuidString.lowercased())++ let needsSecurity = url.startAccessingSecurityScopedResource()+ defer {+ if needsSecurity {+ url.stopAccessingSecurityScopedResource()+ }+ }++ if FileManager.default.fileExists(atPath: destination.path) {+ try FileManager.default.removeItem(at: destination)+ }+ try FileManager.default.copyItem(at: url, to: destination)+ return destination+ }++ private struct HistorySelection {+ let messages: [InferenceMessage]+ let inputTokens: Int+ let inputBudget: Int+ let wasTrimmed: Bool+ }++ private struct PendingOverflow {+ let sessionId: UUID+ let messageId: UUID+ }++ private func buildPrompt(text: String, attachments: [ChatAttachment]) -> PromptResult {+ var prompt = text+ let documents = attachments.filter { $0.kind == .document }+ let images = attachments.filter { $0.kind == .image }++ for (index, attachment) in documents.enumerated() {+ prompt += "\n\n----- BEGIN DOCUMENT: Document \(index + 1) -----\n"+ prompt += "Attached document: \(attachment.name)\n"+ prompt += "----- END DOCUMENT: Document \(index + 1) -----"+ }++ let imageFiles = images.compactMap { $0.url }+ if !imageFiles.isEmpty {+ let mediaMarker = "<__media__>"+ prompt += "\n\n[\(imageFiles.count) image attachment"+ if imageFiles.count > 1 { prompt += "s" }+ prompt += " provided]"+ for _ in imageFiles {+ prompt += "\n\(mediaMarker)"+ }+ }++ return PromptResult(text: prompt, imageFiles: imageFiles)+ }++ private func buildHistorySelection(+ sessionId: UUID,+ promptText: String,+ promptImageCount: Int,+ currentMessageId: UUID,+ target: InferenceModelTarget+ ) -> HistorySelection {+ let childrenMap = childrenByParent(sessionId: sessionId)+ let path = buildSelectedPath(for: sessionId, childrenMap: childrenMap)+ let historyMessages = path.prefix { $0.id != currentMessageId }++ let contextSize: Int = target.contextLength ?? 4096+ let maxTokens: Int = target.maxTokens ?? 1024+ let inputBudget = max(0, contextSize - maxTokens - Self.overflowSafetyTokens)+ let systemTokens = estimateTokens(Self.systemPrompt)+ let promptTokens = estimatePromptTokens(promptText: promptText, imageCount: promptImageCount)+ let historyTokens = historyMessages.reduce(0) { total, node in+ total + estimateTokens(historyText(node))+ }+ let inputTokens = systemTokens + promptTokens + historyTokens+ var remaining = inputBudget - systemTokens - promptTokens++ if remaining <= 0 || historyMessages.isEmpty {+ return HistorySelection(messages: [], inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)+ }++ var selected: [InferenceMessage] = []+ for node in historyMessages.reversed() {+ let text = historyText(node)+ let cost = estimateTokens(text)+ if cost <= remaining {+ selected.append(InferenceMessage(text: text, role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty))+ remaining -= cost+ } else {+ break+ }+ }++ return HistorySelection(messages: selected.reversed(), inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)+ }++ private func historyText(_ node: MessageNode) -> String {+ var text = node.text+ if node.role == .assistant {+ if let regex = ChatMessageTagRegex.think {+ let range = NSRange(text.startIndex..., in: text)+ text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ } else {+ text = text.replacingOccurrences(of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)+ }+ if let regex = ChatMessageTagRegex.todoList {+ let range = NSRange(text.startIndex..., in: text)+ text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ } else {+ text = text.replacingOccurrences(of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)+ }+ } else if !node.attachments.isEmpty {+ text += "\n\n[\(node.attachments.count) attachments attached]"+ }+ return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)+ }++ private func trimToBudget(_ text: String, budget: Int) -> String {+ guard budget > 0 else { return "" }+ let maxChars = budget * 4+ if text.count <= maxChars { return text }+ return String(text.suffix(maxChars))+ }++ private func estimateTokens(_ text: String) -> Int {+ max(1, text.count / 4)+ }++ private func estimateImageTokens(_ imageCount: Int) -> Int {+ imageCount * Self.imageTokenEstimate+ }++ private func estimatePromptTokens(promptText: String, imageCount: Int) -> Int {+ estimateTokens(promptText) + estimateImageTokens(imageCount)+ }++ private func resolveTemperature() -> Float {+ let value = Float(modelSettings.temperature.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))+ let resolved = value.map { max(0, $0) } ?? Self.defaultTemperature+ return min(max(resolved, 0.35), 0.7)+ }++ private struct MessageNode: Identifiable {+ let id: UUID+ let sessionId: UUID+ let parentId: UUID?+ let role: ChatMessage.Role+ let text: String+ let timestamp: Date+ let attachments: [ChatAttachment]+ let isInterrupted: Bool+ let tokensPerSecond: Double?+ }++ private struct PromptResult {+ let text: String+ let imageFiles: [URL]+ }+}+#else+@MainActor+final class ChatViewModel: ObservableObject {+ init() {}+}+#endifdiff --cc mobile/native/darwin/Apps/ensu/scripts/build-rust.shindex a99e111efe,0000000000..47d4eaf404mode 100755,000000..100755--- a/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh+++ b/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh@@@ -1,194 -1,0 +1,194 @@@+#!/bin/sh+set -euo pipefail++# Build the UniFFI Rust static libraries for the current Xcode build platform.+#+# Outputs universal static libraries at:- # $TARGET_TEMP_DIR/ensu_rust/libcore_uniffi.a- # $TARGET_TEMP_DIR/ensu_rust/libllmchat_db_uniffi.a- # $TARGET_TEMP_DIR/ensu_rust/libllmchat_sync_uniffi.a++# $TARGET_TEMP_DIR/ensu_rust/libcore.a++# $TARGET_TEMP_DIR/ensu_rust/libdb.a++# $TARGET_TEMP_DIR/ensu_rust/libsync.a++if [ -z "${SRCROOT:-}" ] || [ -z "${TARGET_TEMP_DIR:-}" ] || [ -z "${PLATFORM_NAME:-}" ] || [ -z "${ARCHS:-}" ]; then+ echo "Missing required Xcode environment variables (SRCROOT/TARGET_TEMP_DIR/PLATFORM_NAME/ARCHS)" >&2+ exit 1+fi++REPO_ROOT="$(cd "${SRCROOT}/../../../../.." && pwd)"+OUT_DIR="${TARGET_TEMP_DIR}/ensu_rust"++mkdir -p "${OUT_DIR}"++# Use debug profile for Debug builds to speed iteration.+CARGO_FLAGS="--locked"+PROFILE="debug"+if [ "${CONFIGURATION:-Debug}" = "Release" ]; then+ CARGO_FLAGS="${CARGO_FLAGS} --release"+ PROFILE="release"+fi++write_endpoint_config() {+ endpoint_value="${ENTE_API_ENDPOINT:-}"++ endpoint_value="$(printf "%s" "${endpoint_value}")"+ endpoint_value="${endpoint_value%%$'\n'*}"+ endpoint_value="$(echo "${endpoint_value}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"++ generated_file="${SRCROOT}/ensu/Generated/EndpointConfig.swift"+ mkdir -p "$(dirname "${generated_file}")"++ if [ -n "${endpoint_value}" ]; then+ escaped_value="${endpoint_value//\\/\\\\}"+ escaped_value="${escaped_value//\"/\\\"}"+ endpoint_literal="\"${escaped_value}\""+ else+ endpoint_literal="nil"+ fi++ cat > "${generated_file}" <<EOF+// This file is generated by scripts/build-rust.sh. Do not edit manually.+import Foundation++enum BuildEndpointConfig {+ static let endpoint: String? = ${endpoint_literal}+}+EOF+}++write_endpoint_config++# Map Xcode platform+arch to Rust target triple.+# Note: For iOS simulator on arm64, Rust uses aarch64-apple-ios-sim.+rust_target_for() {+ platform="$1"+ arch="$2"++ case "$platform" in+ iphoneos)+ if [ "$arch" = "arm64" ]; then+ echo "aarch64-apple-ios"+ else+ echo "" # unsupported+ fi+ ;;+ iphonesimulator)+ if [ "$arch" = "arm64" ]; then+ echo "aarch64-apple-ios-sim"+ elif [ "$arch" = "x86_64" ]; then+ echo "x86_64-apple-ios"+ else+ echo "" # unsupported+ fi+ ;;+ macosx)+ if [ "$arch" = "arm64" ]; then+ echo "aarch64-apple-darwin"+ elif [ "$arch" = "x86_64" ]; then+ echo "x86_64-apple-darwin"+ else+ echo "" # unsupported+ fi+ ;;+ *)+ echo "" # unsupported+ ;;+ esac+}++sdk_for_platform() {+ platform="$1"+ case "$platform" in+ iphoneos)+ echo "iphoneos";+ ;;+ iphonesimulator)+ echo "iphonesimulator";+ ;;+ macosx)+ echo "macosx";+ ;;+ *)+ echo "";+ ;;+ esac+}++TARGET_SDK_NAME="$(sdk_for_platform "${PLATFORM_NAME}")"+if [ -z "${TARGET_SDK_NAME}" ]; then+ echo "Unsupported platform: ${PLATFORM_NAME}" >&2+ exit 1+fi++TARGET_SDKROOT="$(xcrun --sdk "${TARGET_SDK_NAME}" --show-sdk-path)"+TARGET_CLANG="$(xcrun --sdk "${TARGET_SDK_NAME}" --find clang)"+HOST_SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"++# Ensure host builds (build scripts) use the macOS SDK.+export SDKROOT="${HOST_SDKROOT}"++build_crate_universal() {- crate_name="$1" # e.g. core_uniffi++ crate_name="$1" # e.g. core+ crate_dir="$2" # absolute path- lib_name="$3" # e.g. libcore_uniffi.a++ lib_name="$3" # e.g. libcore.a++ echo "🔧 Building ${crate_name} → ${lib_name}"++ INPUT_LIBS=""++ for arch in ${ARCHS}; do+ target="$(rust_target_for "${PLATFORM_NAME}" "$arch")"+ if [ -z "$target" ]; then+ echo "Skipping unsupported arch/platform: ${PLATFORM_NAME} ${arch}" >&2+ continue+ fi++ if ! rustup target list --installed | grep -q "^${target}$"; then+ echo "Installing Rust target ${target}..."+ rustup target add "${target}"+ fi++ target_env="$(echo "${target}" | tr '[:lower:]-' '[:upper:]_')"++ eval "export CARGO_TARGET_${target_env}_LINKER=\"${TARGET_CLANG}\""+ eval "export CFLAGS_${target_env}=\"-isysroot ${TARGET_SDKROOT}\""+ eval "export CXXFLAGS_${target_env}=\"-isysroot ${TARGET_SDKROOT}\""++ RUSTFLAGS_TARGET="${RUSTFLAGS:-} -C link-arg=-isysroot -C link-arg=${TARGET_SDKROOT}"+ if [ "${PLATFORM_NAME}" = "iphonesimulator" ] && [ -n "${IPHONEOS_DEPLOYMENT_TARGET:-}" ]; then+ RUSTFLAGS_TARGET="${RUSTFLAGS_TARGET} -C link-arg=-mios-simulator-version-min=${IPHONEOS_DEPLOYMENT_TARGET}"+ elif [ "${PLATFORM_NAME}" = "iphoneos" ] && [ -n "${IPHONEOS_DEPLOYMENT_TARGET:-}" ]; then+ RUSTFLAGS_TARGET="${RUSTFLAGS_TARGET} -C link-arg=-miphoneos-version-min=${IPHONEOS_DEPLOYMENT_TARGET}"+ fi++ echo "Building ${crate_name} for ${PLATFORM_NAME} ${arch} (${target}) [${PROFILE}]"+ (cd "${crate_dir}" && RUSTFLAGS="${RUSTFLAGS_TARGET}" cargo build ${CARGO_FLAGS} --target "${target}")++ lib_path="${crate_dir}/target/${target}/${PROFILE}/${lib_name}"+ if [ ! -f "${lib_path}" ]; then+ echo "Expected library not found: ${lib_path}" >&2+ exit 1+ fi++ arch_lib="${OUT_DIR}/${lib_name%.a}_${arch}.a"+ cp "${lib_path}" "${arch_lib}"+ INPUT_LIBS="${INPUT_LIBS} ${arch_lib}"+ done++ universal_lib="${OUT_DIR}/${lib_name}"+ rm -f "${universal_lib}"++ set -- ${INPUT_LIBS}+ if [ "$#" -eq 0 ]; then+ echo "No supported architectures found for ${crate_name} (${PLATFORM_NAME} ${ARCHS})" >&2+ exit 1+ elif [ "$#" -eq 1 ]; then+ cp "$1" "${universal_lib}"+ else+ lipo -create ${INPUT_LIBS} -output "${universal_lib}"+ fi++ echo "✅ Built ${universal_lib}"+}+- build_crate_universal "core_uniffi" "${REPO_ROOT}/rust/uniffi/core_uniffi" "libcore_uniffi.a"- build_crate_universal "llmchat_db_uniffi" "${REPO_ROOT}/rust/llmchat/uniffi/llmchat_db_uniffi" "libllmchat_db_uniffi.a"- build_crate_universal "llmchat_sync_uniffi" "${REPO_ROOT}/rust/llmchat/uniffi/llmchat_sync_uniffi" "libllmchat_sync_uniffi.a"++build_crate_universal "core" "${REPO_ROOT}/rust/uniffi/core" "libcore.a"++build_crate_universal "db" "${REPO_ROOT}/rust/uniffi/ensu/db" "libdb.a"++build_crate_universal "sync" "${REPO_ROOT}/rust/uniffi/ensu/sync" "libsync.a"diff --cc mobile/native/darwin/Packages/Rust/README.mdindex af3e32e77a,0000000000..904e3788c7mode 100644,000000..100644--- a/mobile/native/darwin/Packages/Rust/README.md+++ b/mobile/native/darwin/Packages/Rust/README.md@@@ -1,107 -1,0 +1,107 @@@+# InferenceRS (Swift)+- Swift bindings generated via UniFFI for the Rust core in `rust/llmchat/inference`.++Swift bindings generated via UniFFI for the Rust core in `rust/ensu/inference`.++## Generate bindings++From the repo root:++```bash+cd mobile/native/darwin/Packages/Rust+./tool/generate_bindings.sh+```++This writes the Swift sources plus the UniFFI header/modulemap into+`Sources/InferenceRS`. These generated files are gitignored—re-run the script+whenever you need to regenerate bindings.++Note: The script applies the llama.cpp mtmd patch (requires `python3`). Set+`APPLY_LLAMA_MTMD_PATCH=0` to skip it.++## Build the xcframework++From the repo root:++```bash+cd mobile/native/darwin/Packages/Rust+./tool/build_xcframework.sh+```++This produces `InferenceRSFFI.xcframework`, which the Swift package references+as a binary target. The xcframework is gitignored and should be generated+locally as needed.++Note: The build applies the llama.cpp mtmd patch (requires `python3`). Set+`APPLY_LLAMA_MTMD_PATCH=0` to skip it.++## Use in an app (SwiftPM)++Add the package to your app and import `InferenceRS`:++```swift+import InferenceRS++try initBackend()+let model = try loadModel(+ params: ModelLoadParams(modelPath: "/path/to/model.gguf", nGpuLayers: nil, useMmap: nil, useMlock: nil)+)+let context = try createContext(+ model: model,+ params: ContextParams(contextSize: 4096, nThreads: 4, nBatch: 128)+)++let request = GenerateChatRequest(+ messages: [+ ChatMessage(role: "system", content: "You are a helpful assistant."),+ ChatMessage(role: "user", content: "Say hello")+ ],+ templateOverride: nil,+ addAssistant: true,+ imagePaths: nil,+ mmprojPath: nil,+ mediaMarker: nil,+ maxTokens: 64,+ temperature: 0.7,+ topP: 0.9,+ topK: nil,+ repeatPenalty: nil,+ frequencyPenalty: nil,+ presencePenalty: nil,+ seed: nil,+ stopSequences: nil,+ grammar: nil+)++final class StreamHandler: GenerateEventCallback {+ func onEvent(event: GenerateEvent) {+ switch event {+ case let .text(_, text, _):+ print(text)+ case let .done(summary):+ print("Done: \(summary.generatedTokens ?? 0) tokens")+ case let .error(_, message):+ print("Error: \(message)")+ }+ }+}++let summary = try generateChatStream(+ context: context,+ request: request,+ callback: StreamHandler()+)+print("Summary job id: \(summary.jobId)")+```++Notes:+- Generation runs synchronously; invoke on a background queue if needed.+- Callback interfaces are class-only (`AnyObject`) in Swift.++## Run tests++Build the xcframework first, then set a model path to enable the integration test:++```bash+./tool/build_xcframework.sh+INFERENCE_RS_TEST_MODEL=/path/to/model.gguf swift test+```diff --cc mobile/native/darwin/Packages/Rust/rust/Cargo.tomlindex ecbcb6b423,0000000000..7dac98c0demode 100644,000000..100644--- a/mobile/native/darwin/Packages/Rust/rust/Cargo.toml+++ b/mobile/native/darwin/Packages/Rust/rust/Cargo.toml@@@ -1,14 -1,0 +1,14 @@@+[package]+name = "inference_rs_uniffi"+version = "0.1.0"+edition = "2024"++[lib]+name = "inference_rs_uniffi"+crate-type = ["staticlib", "cdylib"]++[dependencies]- inference_rs = { path = "../../../../../../rust/llmchat/inference" }++inference_rs = { path = "../../../../../../rust/ensu/inference" }+serde = { version = "1", features = ["derive"] }+thiserror = "1"+uniffi = { version = "0.31.0" }diff --cc mobile/native/darwin/Packages/Rust/tool/build_xcframework.shindex 2c5f72ba12,0000000000..87980498femode 100755,000000..100755--- a/mobile/native/darwin/Packages/Rust/tool/build_xcframework.sh+++ b/mobile/native/darwin/Packages/Rust/tool/build_xcframework.sh@@@ -1,70 -1,0 +1,70 @@@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"+RUST_DIR="$ROOT/rust"- CORE_ROOT="$REPO_ROOT/rust/llmchat/inference"++CORE_ROOT="$REPO_ROOT/rust/ensu/inference"+PATCH_SCRIPT="$CORE_ROOT/tool/patch_llama_mtmd.sh"+APPLY_LLAMA_MTMD_PATCH="${APPLY_LLAMA_MTMD_PATCH:-1}"+LIB_NAME="libinference_rs_uniffi.a"++if [[ "$APPLY_LLAMA_MTMD_PATCH" != "0" && -f "$PATCH_SCRIPT" ]]; then+ if ! command -v python3 >/dev/null 2>&1; then+ echo "python3 is required to apply the llama mtmd patch." >&2+ exit 1+ fi+ echo "Applying llama mtmd patch..."+ bash "$PATCH_SCRIPT"+fi++"$ROOT/tool/generate_bindings.sh"++HEADER_DIR="$ROOT/build/headers"+HEADER_SRC="$ROOT/Sources/InferenceRS/inference_rs_uniffiFFI.h"+MODULEMAP_SRC="$ROOT/Sources/InferenceRS/inference_rs_uniffiFFI.modulemap"++rm -rf "$HEADER_DIR"+mkdir -p "$ROOT/build/ios" "$ROOT/build/macos" "$HEADER_DIR"++if [[ ! -f "$HEADER_SRC" ]] || [[ ! -f "$MODULEMAP_SRC" ]]; then+ echo "Expected UniFFI headers in $ROOT/Sources/InferenceRS" >&2+ exit 1+fi++cp "$HEADER_SRC" "$HEADER_DIR/"+cp "$MODULEMAP_SRC" "$HEADER_DIR/module.modulemap"++export IPHONEOS_DEPLOYMENT_TARGET=13.0+export CMAKE_OSX_DEPLOYMENT_TARGET=13.0++cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-ios --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-ios-sim --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target x86_64-apple-ios --lib --crate-type staticlib++cp "$RUST_DIR/target/aarch64-apple-ios/release/$LIB_NAME" "$ROOT/build/ios/$LIB_NAME"++lipo -create \+ "$RUST_DIR/target/aarch64-apple-ios-sim/release/$LIB_NAME" \+ "$RUST_DIR/target/x86_64-apple-ios/release/$LIB_NAME" \+ -output "$ROOT/build/ios/${LIB_NAME%.a}-sim.a"++unset IPHONEOS_DEPLOYMENT_TARGET+export MACOSX_DEPLOYMENT_TARGET=10.15+export CMAKE_OSX_DEPLOYMENT_TARGET=10.15++cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-darwin --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target x86_64-apple-darwin --lib --crate-type staticlib++lipo -create \+ "$RUST_DIR/target/aarch64-apple-darwin/release/$LIB_NAME" \+ "$RUST_DIR/target/x86_64-apple-darwin/release/$LIB_NAME" \+ -output "$ROOT/build/macos/$LIB_NAME"++rm -rf "$ROOT/InferenceRSFFI.xcframework"++xcodebuild -create-xcframework \+ -library "$ROOT/build/ios/$LIB_NAME" -headers "$HEADER_DIR" \+ -library "$ROOT/build/ios/${LIB_NAME%.a}-sim.a" -headers "$HEADER_DIR" \+ -library "$ROOT/build/macos/$LIB_NAME" -headers "$HEADER_DIR" \+ -output "$ROOT/InferenceRSFFI.xcframework"diff --cc mobile/native/darwin/Packages/Rust/tool/generate_bindings.shindex 3b499a6ec8,0000000000..27b72e7b1cmode 100755,000000..100755--- a/mobile/native/darwin/Packages/Rust/tool/generate_bindings.sh+++ b/mobile/native/darwin/Packages/Rust/tool/generate_bindings.sh@@@ -1,43 -1,0 +1,43 @@@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"+RUST_DIR="$ROOT/rust"- CORE_ROOT="$REPO_ROOT/rust/llmchat/inference"++CORE_ROOT="$REPO_ROOT/rust/ensu/inference"+PATCH_SCRIPT="$CORE_ROOT/tool/patch_llama_mtmd.sh"+APPLY_LLAMA_MTMD_PATCH="${APPLY_LLAMA_MTMD_PATCH:-1}"+OUT_DIR="$ROOT/Sources/InferenceRS"++if [[ "$APPLY_LLAMA_MTMD_PATCH" != "0" && -f "$PATCH_SCRIPT" ]]; then+ if ! command -v python3 >/dev/null 2>&1; then+ echo "python3 is required to apply the llama mtmd patch." >&2+ exit 1+ fi+ echo "Applying llama mtmd patch..."+ bash "$PATCH_SCRIPT"+fi++cargo build --manifest-path "$RUST_DIR/Cargo.toml" --release++if [[ "$(uname -s)" == "Darwin" ]]; then+ LIB_EXT="dylib"+elif [[ "$(uname -s)" == "Linux" ]]; then+ LIB_EXT="so"+else+ LIB_EXT="dll"+fi++LIB_PATH="$RUST_DIR/target/release/libinference_rs_uniffi.$LIB_EXT"++if [[ ! -f "$LIB_PATH" ]]; then+ echo "Expected $LIB_PATH to exist" >&2+ exit 1+fi++mkdir -p "$OUT_DIR"+rm -f "$OUT_DIR"/inference_rs_*++pushd "$RUST_DIR" >/dev/null+uniffi-bindgen generate "$LIB_PATH" --language swift --out-dir "$OUT_DIR" --crate inference_rs_uniffi+popd >/dev/nulldiff --cc rust/ensu/inference/src/api.rsindex 0000000000,02875ecac5..78f29098ffmode 000000,100644..100644--- a/rust/ensu/inference/src/api.rs+++ b/rust/ensu/inference/src/api.rs@@@ -1,0 -1,1172 +1,1182 @@@+ use llama_cpp_2::context::LlamaContext;+ use llama_cpp_2::context::params::LlamaContextParams;+ use llama_cpp_2::llama_backend::LlamaBackend;+ use llama_cpp_2::llama_batch::LlamaBatch;+ use llama_cpp_2::model::{AddBos, LlamaChatMessage, LlamaChatTemplate, LlamaModel, Special};+ use llama_cpp_2::mtmd::{+ MtmdBitmap, MtmdContext, MtmdContextParams, MtmdInputText, mtmd_default_marker,+ };+ use llama_cpp_2::sampling::LlamaSampler;+ use llama_cpp_2::token::LlamaToken;+ use llama_cpp_sys_2::{+ GGML_LOG_LEVEL_ERROR, GGML_LOG_LEVEL_WARN, ggml_log_level, mtmd_helper_log_set,+ };+ use parking_lot::Mutex;+ use self_cell::self_cell;+ use serde::{Deserialize, Serialize};+ use std::collections::HashMap;+ use std::ffi::{CStr, CString};+ use std::num::NonZeroU32;+ use std::panic::{AssertUnwindSafe, catch_unwind};+ use std::path::Path;+ use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};+ use std::sync::{Arc, OnceLock};+ use std::time::Instant;++ pub type JobId = i64;++ pub trait EventSink {+ fn add(&mut self, event: GenerateEvent);+ }++ impl<F> EventSink for F+ where+ F: FnMut(GenerateEvent),+ {+ fn add(&mut self, event: GenerateEvent) {+ (self)(event);+ }+ }++ static BACKEND: OnceLock<Result<LlamaBackend, String>> = OnceLock::new();+ static JOB_COUNTER: AtomicI64 = AtomicI64::new(1);+ static CANCEL_FLAGS: OnceLock<Mutex<HashMap<JobId, Arc<AtomicBool>>>> = OnceLock::new();+ static MTMD_LOG_BUFFER: OnceLock<Mutex<String>> = OnceLock::new();+ static MTMD_LOG_HOOK: OnceLock<()> = OnceLock::new();++ const CANCEL_MESSAGE: &str = "Generation cancelled";++ fn backend() -> Result<&'static LlamaBackend, String> {+ match BACKEND.get_or_init(|| LlamaBackend::init().map_err(|err| err.to_string())) {+ Ok(backend) => Ok(backend),+ Err(err) => Err(format!("Failed to initialize backend: {err}")),+ }+ }++ fn cancel_flags() -> &'static Mutex<HashMap<JobId, Arc<AtomicBool>>> {+ CANCEL_FLAGS.get_or_init(|| Mutex::new(HashMap::new()))+ }++ fn mtmd_log_buffer() -> &'static Mutex<String> {+ MTMD_LOG_BUFFER.get_or_init(|| Mutex::new(String::new()))+ }++ unsafe extern "C" fn mtmd_log_callback(+ level: ggml_log_level,+ text: *const ::std::os::raw::c_char,+ _user_data: *mut ::std::os::raw::c_void,+ ) {+ if text.is_null() {+ return;+ }+ if level != GGML_LOG_LEVEL_WARN && level != GGML_LOG_LEVEL_ERROR {+ return;+ }+ let cstr = unsafe { CStr::from_ptr(text) };+ if let Ok(message) = cstr.to_str() {+ let mut guard = mtmd_log_buffer().lock();+ guard.push_str(message);+ const MAX_LEN: usize = 8192;+ if guard.len() > MAX_LEN {+ let drain = guard.len() - MAX_LEN;+ guard.drain(..drain);+ }+ }+ }++ fn init_mtmd_logging() {+ MTMD_LOG_HOOK.get_or_init(|| unsafe {+ mtmd_helper_log_set(Some(mtmd_log_callback), std::ptr::null_mut());+ });+ }++ fn take_mtmd_logs() -> String {+ let mut guard = mtmd_log_buffer().lock();+ let logs = guard.clone();+ guard.clear();+ logs+ }++ fn register_job() -> (JobId, Arc<AtomicBool>) {+ let job_id = JOB_COUNTER.fetch_add(1, Ordering::Relaxed);+ let flag = Arc::new(AtomicBool::new(false));+ cancel_flags().lock().insert(job_id, flag.clone());+ (job_id, flag)+ }++ fn cancel_all() {+ for flag in cancel_flags().lock().values() {+ flag.store(true, Ordering::Relaxed);+ }+ }++ fn check_cancelled(cancel_flag: &AtomicBool) -> Result<(), String> {+ if cancel_flag.load(Ordering::Relaxed) {+ Err(CANCEL_MESSAGE.to_string())+ } else {+ Ok(())+ }+ }++ struct JobGuard(JobId);++ impl Drop for JobGuard {+ fn drop(&mut self) {+ cancel_flags().lock().remove(&self.0);+ }+ }++ fn format_error(context: &str, err: impl std::fmt::Display) -> String {+ format!("{context}: {err}")+ }++ fn build_chat_prompt(+ model: &LlamaModel,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+ ) -> Result<String, String> {+ let template = match template_override {+ Some(template) => LlamaChatTemplate::new(&template)+ .map_err(|err| format_error("Invalid chat template", err))?,+ None => model+ .chat_template(None)+ .or_else(|_| LlamaChatTemplate::new("chatml"))+ .map_err(|err| format_error("Failed to load chat template", err))?,+ };++ let chat_messages = messages+ .into_iter()+ .map(|message| {+ LlamaChatMessage::new(message.role, message.content)+ .map_err(|err| format_error("Invalid chat message", err))+ })+ .collect::<Result<Vec<_>, String>>()?;++ model+ .apply_chat_template(&template, &chat_messages, add_assistant)+ .map_err(|err| format_error("Failed to apply chat template", err))+ }++ fn should_add_bos(model: &LlamaModel, prompt: &str) -> AddBos {+ if let Ok(bos) = model.token_to_str(model.token_bos(), Special::Tokenize)+ && !bos.is_empty()+ && prompt.starts_with(&bos)+ {+ return AddBos::Never;+ }+ AddBos::Always+ }++ fn find_stop_index(text: &str, stop_sequences: &[String], start: usize) -> Option<usize> {+ let mut found: Option<usize> = None;+ let search = &text[start.min(text.len())..];++ for stop in stop_sequences {+ if stop.is_empty() {+ continue;+ }+ if let Some(idx) = search.find(stop) {+ let idx = start + idx;+ found = match found {+ Some(existing) if existing <= idx => Some(existing),+ _ => Some(idx),+ };+ }+ }++ found+ }++ fn drain_utf8(pending: &mut Vec<u8>) -> String {+ let mut output = String::new();+ loop {+ match std::str::from_utf8(pending) {+ Ok(text) => {+ output.push_str(text);+ pending.clear();+ break;+ }+ Err(err) => {+ let valid_up_to = err.valid_up_to();+ if valid_up_to > 0 {- let valid = std::str::from_utf8(&pending[..valid_up_to])- .expect("valid UTF-8 prefix");++ let valid =++ std::str::from_utf8(&pending[..valid_up_to]).expect("valid UTF-8 prefix");+ output.push_str(valid);+ pending.drain(..valid_up_to);+ }++ match err.error_len() {+ None => break,+ Some(len) => {+ let len = len.min(pending.len());+ let lossy = String::from_utf8_lossy(&pending[..len]);+ output.push_str(&lossy);+ pending.drain(..len);+ }+ }+ }+ }+ }+ output+ }++ struct DecodeStep {+ text: Option<String>,+ stop: bool,+ }++ /// Incremental UTF-8 streaming decoder with stop-sequence handling.+ struct StreamDecoder {+ generated_text: String,+ pending_bytes: Vec<u8>,+ stop_sequences: Vec<String>,+ max_stop_len: usize,+ }++ impl StreamDecoder {+ fn new(stop_sequences: &[String]) -> Self {+ let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);+ Self {+ generated_text: String::new(),+ pending_bytes: Vec::new(),+ stop_sequences: stop_sequences.to_vec(),+ max_stop_len,+ }+ }++ fn push_bytes(&mut self, bytes: &[u8]) -> DecodeStep {+ if !bytes.is_empty() {+ self.pending_bytes.extend_from_slice(bytes);+ }+ let piece = drain_utf8(&mut self.pending_bytes);+ self.push_text(piece)+ }++ fn flush(&mut self) -> DecodeStep {+ if self.pending_bytes.is_empty() {- return DecodeStep { text: None, stop: false };++ return DecodeStep {++ text: None,++ stop: false,++ };+ }+ let piece = String::from_utf8_lossy(&self.pending_bytes).to_string();+ self.pending_bytes.clear();+ self.push_text(piece)+ }++ fn push_text(&mut self, piece: String) -> DecodeStep {+ if piece.is_empty() {- return DecodeStep { text: None, stop: false };++ return DecodeStep {++ text: None,++ stop: false,++ };+ }++ let prev_len = self.generated_text.len();+ self.generated_text.push_str(&piece);++ if self.max_stop_len > 0 {+ let search_start = prev_len.saturating_sub(self.max_stop_len);+ if let Some(stop_index) =+ find_stop_index(&self.generated_text, &self.stop_sequences, search_start)+ {+ let new_piece = self.generated_text[prev_len..stop_index].to_string();+ self.generated_text.truncate(stop_index);+ return DecodeStep {- text: if new_piece.is_empty() { None } else { Some(new_piece) },++ text: if new_piece.is_empty() {++ None++ } else {++ Some(new_piece)++ },+ stop: true,+ };+ }+ }++ DecodeStep {+ text: Some(piece),+ stop: false,+ }+ }+ }++ #[allow(clippy::too_many_arguments)]+ fn run_generation_loop(+ ctx: &mut LlamaContext,+ sampler: &mut LlamaSampler,+ cancel_flag: &AtomicBool,+ sink: &mut dyn EventSink,+ job_id: JobId,+ max_tokens: usize,+ stop_sequences: &[String],+ generated_tokens_count: &mut i32,+ mut pos: i32,+ mut logits_index: i32,+ ) -> Result<(), String> {+ let mut decoder = StreamDecoder::new(stop_sequences);+ let mut stop_triggered = false;+ let n_ctx = ctx.n_ctx();++ for _ in 0..max_tokens {+ if cancel_flag.load(Ordering::Relaxed) {+ return Err("Generation cancelled".to_string());+ }+ if pos >= n_ctx as i32 {+ break;+ }++ let token = sampler.sample(ctx, logits_index);+ sampler.accept(token);+ *generated_tokens_count = generated_tokens_count.saturating_add(1);++ if ctx.model.is_eog_token(token) {+ break;+ }++ let bytes = ctx+ .model+ .token_to_bytes(token, Special::Tokenize)+ .map_err(|err| format_error("Detokenize failed", err))?;+ let step = decoder.push_bytes(&bytes);++ if let Some(text) = step.text {+ sink.add(GenerateEvent::Text {+ job_id,+ text,+ token_id: Some(token.0),+ });+ }++ if step.stop {+ stop_triggered = true;+ break;+ }++ let mut step_batch = LlamaBatch::new(1, 1);+ step_batch+ .add(token, pos, &[0], true)+ .map_err(|err| format_error("Failed to add token", err))?;+ ctx.decode(&mut step_batch)+ .map_err(|err| format_error("Decode failed", err))?;++ logits_index = 0;+ pos += 1;+ }++ if !stop_triggered {+ let step = decoder.flush();+ if let Some(text) = step.text {+ sink.add(GenerateEvent::Text {+ job_id,+ text,+ token_id: None,+ });+ }+ }++ Ok(())+ }++ fn build_sampler(model: &LlamaModel, request: &GenerateRequest) -> Result<LlamaSampler, String> {+ let mut samplers = Vec::new();++ let mut repeat_penalty = request.repeat_penalty.unwrap_or(1.0);+ if repeat_penalty <= 0.0 {+ repeat_penalty = 1.0;+ }+ let mut frequency_penalty = request.frequency_penalty.unwrap_or(0.0);+ if frequency_penalty < 0.0 {+ frequency_penalty = 0.0;+ }+ let mut presence_penalty = request.presence_penalty.unwrap_or(0.0);+ if presence_penalty < 0.0 {+ presence_penalty = 0.0;+ }++ if (repeat_penalty - 1.0).abs() > f32::EPSILON+ || frequency_penalty != 0.0+ || presence_penalty != 0.0+ {+ samplers.push(LlamaSampler::penalties(+ -1,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ ));+ }++ if let Some(grammar) = request.grammar.as_deref() {+ samplers.push(+ LlamaSampler::grammar(model, grammar, "root")+ .map_err(|err| format_error("Invalid grammar", err))?,+ );+ }++ if let Some(top_k) = request.top_k+ && top_k > 0+ {+ samplers.push(LlamaSampler::top_k(top_k));+ }++ if let Some(top_p) = request.top_p+ && top_p > 0.0+ && top_p < 1.0+ {+ samplers.push(LlamaSampler::top_p(top_p, 1));+ }++ let temperature = request.temperature.unwrap_or(1.0);+ if temperature > 0.0 {+ samplers.push(LlamaSampler::temp(temperature));+ let seed = request.seed.unwrap_or(0);+ let seed = u32::try_from(seed).unwrap_or(0);+ samplers.push(LlamaSampler::dist(seed));+ } else {+ samplers.push(LlamaSampler::greedy());+ }++ Ok(LlamaSampler::chain_simple(samplers))+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct ModelLoadParams {+ pub model_path: String,+ pub n_gpu_layers: Option<i32>,+ pub use_mmap: Option<bool>,+ pub use_mlock: Option<bool>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct ContextParams {+ pub context_size: Option<i32>,+ pub n_threads: Option<i32>,+ pub n_batch: Option<i32>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct ModelInfo {+ pub bos_token_id: Option<i32>,+ pub eos_token_id: Option<i32>,+ pub bos_token: Option<String>,+ pub eos_token: Option<String>,+ pub chat_template: Option<String>,+ pub metadata_json: Option<String>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct ChatMessage {+ pub role: String,+ pub content: String,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct GenerateRequest {+ pub prompt: String,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct GenerateChatRequest {+ pub messages: Vec<ChatMessage>,+ pub template_override: Option<String>,+ pub add_assistant: Option<bool>,+ pub image_paths: Option<Vec<String>>,+ pub mmproj_path: Option<String>,+ pub media_marker: Option<String>,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub struct GenerateSummary {+ pub job_id: JobId,+ pub prompt_tokens: Option<i32>,+ pub generated_tokens: Option<i32>,+ pub total_time_ms: Option<i64>,+ }++ #[derive(Debug, Clone, Serialize, Deserialize)]+ pub enum GenerateEvent {+ Text {+ job_id: JobId,+ text: String,+ token_id: Option<i32>,+ },+ Done {+ summary: GenerateSummary,+ },+ Error {+ job_id: JobId,+ message: String,+ },+ }++ pub struct ModelHandle {+ model: LlamaModel,+ }++ pub type ModelHandleRef = Arc<ModelHandle>;++ impl ModelHandle {+ fn model(&self) -> &LlamaModel {+ &self.model+ }+ }++ self_cell!(+ struct ContextHandleCell {+ owner: ModelHandleRef,++ #[covariant]+ dependent: LlamaContext,+ }+ );++ pub struct ContextHandle(Mutex<ContextHandleCell>);++ pub type ContextHandleRef = Arc<ContextHandle>;++ unsafe impl Send for ContextHandle {}+ unsafe impl Sync for ContextHandle {}++ impl ContextHandle {+ fn try_new(+ owner: ModelHandleRef,+ builder: impl for<'a> FnOnce(&'a ModelHandleRef) -> Result<LlamaContext<'a>, String>,+ ) -> Result<Self, String> {+ ContextHandleCell::try_new(owner, builder).map(|cell| ContextHandle(Mutex::new(cell)))+ }++ fn with_context_mut<R>(+ &self,+ func: impl for<'a, 'b> FnOnce(&'b mut LlamaContext<'a>) -> R,+ ) -> R {+ let mut guard = self.0.lock();+ guard.with_dependent_mut(|_owner, context| func(context))+ }+ }++ pub fn init_backend() -> Result<(), String> {+ backend().map(|_| ())+ }++ pub fn load_model(params: ModelLoadParams) -> Result<ModelHandleRef, String> {+ let backend = backend()?;+ let mut model_params = llama_cpp_2::model::params::LlamaModelParams::default();++ if let Some(n_gpu_layers) = params.n_gpu_layers {+ let layers =+ u32::try_from(n_gpu_layers).map_err(|_| "n_gpu_layers must be >= 0".to_string())?;+ model_params = model_params.with_n_gpu_layers(layers);+ }++ if let Some(use_mlock) = params.use_mlock {+ model_params = model_params.with_use_mlock(use_mlock);+ }++ let model = LlamaModel::load_from_file(backend, Path::new(¶ms.model_path), &model_params)+ .map_err(|err| format_error("Failed to load model", err))?;++ Ok(Arc::new(ModelHandle { model }))+ }++ pub fn create_context(+ model: ModelHandleRef,+ params: ContextParams,+ ) -> Result<ContextHandleRef, String> {+ let mut context_params = LlamaContextParams::default();++ if let Some(context_size) = params.context_size {+ let context_size =+ u32::try_from(context_size).map_err(|_| "context_size must be > 0".to_string())?;+ let context_size =+ NonZeroU32::new(context_size).ok_or_else(|| "context_size must be > 0".to_string())?;+ context_params = context_params.with_n_ctx(Some(context_size));+ }++ if let Some(n_threads) = params.n_threads {+ if n_threads <= 0 {+ return Err("n_threads must be > 0".to_string());+ }+ context_params = context_params+ .with_n_threads(n_threads)+ .with_n_threads_batch(n_threads);+ }++ if let Some(n_batch) = params.n_batch {+ let n_batch = u32::try_from(n_batch).map_err(|_| "n_batch must be > 0".to_string())?;+ context_params = context_params.with_n_batch(n_batch);+ }++ let context = ContextHandle::try_new(model, |model| {+ let backend = backend()?;+ model+ .model()+ .new_context(backend, context_params)+ .map_err(|err| format_error("Failed to create context", err))+ })?;++ Ok(Arc::new(context))+ }++ pub fn tokenize(+ model: &ModelHandle,+ text: String,+ add_bos: bool,+ special: bool,+ ) -> Result<Vec<i32>, String> {+ let add_bos = if add_bos {+ AddBos::Always+ } else {+ AddBos::Never+ };+ let _ = special;++ let tokens = model+ .model()+ .str_to_token(&text, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ Ok(tokens.into_iter().map(|token| token.0).collect())+ }++ pub fn detokenize(model: &ModelHandle, tokens: Vec<i32>) -> Result<String, String> {+ let tokens = tokens.into_iter().map(LlamaToken::new).collect::<Vec<_>>();+ model+ .model()+ .tokens_to_str(&tokens, Special::Tokenize)+ .map_err(|err| format_error("Detokenize failed", err))+ }++ pub fn get_model_info(model: &ModelHandle) -> Result<ModelInfo, String> {+ let model_ref = model.model();+ let bos_token = model_ref.token_bos();+ let eos_token = model_ref.token_eos();++ let bos_token_str = model_ref+ .token_to_str(bos_token, Special::Tokenize)+ .ok()+ .filter(|value| !value.is_empty());+ let eos_token_str = model_ref+ .token_to_str(eos_token, Special::Tokenize)+ .ok()+ .filter(|value| !value.is_empty());++ let chat_template = model_ref+ .chat_template(None)+ .ok()+ .and_then(|tmpl| tmpl.to_string().ok());++ let meta_count = model_ref.meta_count();+ let mut metadata_json = None;++ if meta_count > 0 {+ let mut map = serde_json::Map::new();+ for index in 0..meta_count {+ let key = model_ref+ .meta_key_by_index(index)+ .map_err(|err| format_error("Failed to read metadata key", err))?;+ let value = model_ref+ .meta_val_str_by_index(index)+ .map_err(|err| format_error("Failed to read metadata value", err))?;+ map.insert(key, serde_json::Value::String(value));+ }+ if !map.is_empty() {+ metadata_json = Some(serde_json::Value::Object(map).to_string());+ }+ }++ Ok(ModelInfo {+ bos_token_id: Some(bos_token.0),+ eos_token_id: Some(eos_token.0),+ bos_token: bos_token_str,+ eos_token: eos_token_str,+ chat_template,+ metadata_json,+ })+ }++ pub fn apply_chat_template(+ model: &ModelHandle,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+ ) -> Result<String, String> {+ build_chat_prompt(model.model(), messages, template_override, add_assistant)+ }++ pub fn generate_chat_stream(+ context: &ContextHandle,+ request: GenerateChatRequest,+ sink: &mut dyn EventSink,+ ) -> Result<GenerateSummary, String> {+ let GenerateChatRequest {+ messages,+ template_override,+ add_assistant,+ image_paths,+ mmproj_path,+ media_marker,+ max_tokens,+ temperature,+ top_p,+ top_k,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ seed,+ stop_sequences,+ grammar,+ } = request;++ let (job_id, cancel_flag) = register_job();+ let _job_guard = JobGuard(job_id);+ let start = Instant::now();++ sink.add(GenerateEvent::Text {+ job_id,+ text: String::new(),+ token_id: None,+ });++ let max_tokens = max_tokens.unwrap_or(128);+ let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);+ let stop_sequences = stop_sequences.unwrap_or_default();++ let mut prompt_tokens_count: i32 = 0;+ let mut generated_tokens_count: i32 = 0;+ let mut error_message: Option<String> = None;++ let result = match catch_unwind(AssertUnwindSafe(|| {+ context.with_context_mut(|ctx| -> Result<(), String> {+ let add_assistant = add_assistant.unwrap_or(true);+ let mut messages = messages;+ let image_paths = image_paths.unwrap_or_default();+ let marker = media_marker+ .clone()+ .unwrap_or_else(|| mtmd_default_marker().to_string());++ if !image_paths.is_empty() {+ let mut marker_count = messages+ .iter()+ .map(|message| message.content.matches(&marker).count())+ .sum::<usize>();+ if marker_count == 0 {+ let target_index = messages+ .iter()+ .rposition(|message| message.role == "user")+ .or_else(|| messages.len().checked_sub(1))+ .ok_or_else(|| "No chat messages provided".to_string())?;+ if !messages[target_index].content.ends_with('\n') {+ messages[target_index].content.push('\n');+ }+ messages[target_index].content.push_str(&marker);+ marker_count = messages+ .iter()+ .map(|message| message.content.matches(&marker).count())+ .sum();+ }+ if marker_count != image_paths.len() {+ return Err(format!(+ "Found {marker_count} media markers but {} images were provided",+ image_paths.len()+ ));+ }+ }++ let prompt = build_chat_prompt(ctx.model, messages, template_override, add_assistant)?;++ let sampler_request = GenerateRequest {+ prompt: prompt.clone(),+ max_tokens: None,+ temperature,+ top_p,+ top_k,+ repeat_penalty,+ frequency_penalty,+ presence_penalty,+ seed,+ stop_sequences: Some(stop_sequences.clone()),+ grammar: grammar.clone(),+ };++ if image_paths.is_empty() {+ let add_bos = should_add_bos(ctx.model, &prompt);+ let prompt_tokens = ctx+ .model+ .str_to_token(&prompt, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ if prompt_tokens.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count = i32::try_from(prompt_tokens.len())+ .map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ if prompt_tokens.len() as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ prompt_tokens.len(),+ n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as usize;+ if n_batch == 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();++ let mut token_offset = 0usize;+ let mut logits_index: i32 = 0;+ while token_offset < prompt_tokens.len() {+ check_cancelled(&cancel_flag)?;+ let end = (token_offset + n_batch).min(prompt_tokens.len());+ let chunk = &prompt_tokens[token_offset..end];+ let mut batch = LlamaBatch::new(chunk.len(), 1);+ for (idx, token) in chunk.iter().enumerate() {+ let pos = (token_offset + idx) as i32;+ let logits = token_offset + idx + 1 == prompt_tokens.len();+ batch+ .add(*token, pos, &[0], logits)+ .map_err(|err| format_error("Failed to add prompt token", err))?;+ }+ ctx.decode(&mut batch)+ .map_err(|err| format_error("Prompt decode failed", err))?;+ if end == prompt_tokens.len() {+ logits_index = (chunk.len() - 1) as i32;+ }+ token_offset = end;+ }++ let mut sampler = build_sampler(ctx.model, &sampler_request)?;+ sampler.accept_many(prompt_tokens.iter());++ let pos = prompt_tokens.len() as i32;+ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ &mut generated_tokens_count,+ pos,+ logits_index,+ )?;++ return Ok(());+ }++ let mmproj_path = mmproj_path.ok_or_else(|| {+ "mmproj_path is required when image_paths are provided".to_string()+ })?;+ if !Path::new(&mmproj_path).exists() {+ return Err(format!("mmproj file not found at {mmproj_path}"));+ }++ init_mtmd_logging();+ take_mtmd_logs();++ let media_marker = CString::new(marker.clone())+ .map_err(|err| format_error("Invalid media marker", err))?;+ let mtmd_params = MtmdContextParams {+ use_gpu: false,+ print_timings: false,+ media_marker,+ ..Default::default()+ };++ let mtmd_ctx = MtmdContext::init_from_file(&mmproj_path, ctx.model, &mtmd_params)+ .map_err(|err| {+ let logs = take_mtmd_logs();+ if logs.trim().is_empty() {+ format_error("Failed to initialize mmproj", err)+ } else {+ format!("Failed to initialize mmproj: {err}. Logs: {logs}")+ }+ })?;++ if !mtmd_ctx.support_vision() {+ return Err("Model does not support vision input".to_string());+ }++ let mut bitmaps = Vec::with_capacity(image_paths.len());+ for image_path in &image_paths {+ check_cancelled(&cancel_flag)?;+ if !Path::new(image_path).exists() {+ return Err(format!("Image file not found at {image_path}"));+ }+ let bitmap = MtmdBitmap::from_file(&mtmd_ctx, image_path)+ .map_err(|err| format_error("Failed to load image", err))?;+ if bitmap.is_audio() {+ return Err("Audio inputs are not supported".to_string());+ }+ bitmaps.push(bitmap);+ }+ let bitmap_refs = bitmaps.iter().collect::<Vec<_>>();++ let add_special = matches!(should_add_bos(ctx.model, &prompt), AddBos::Always);+ let input_text = MtmdInputText {+ text: prompt,+ add_special,+ parse_special: true,+ };++ let chunks = mtmd_ctx+ .tokenize(input_text, &bitmap_refs)+ .map_err(|err| format_error("Failed to tokenize multimodal input", err))?;++ if chunks.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count = i32::try_from(chunks.total_tokens())+ .map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ let total_positions = chunks.total_positions();+ if total_positions as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ total_positions, n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as i32;+ if n_batch <= 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();+ check_cancelled(&cancel_flag)?;++ let n_past = chunks+ .eval_chunks(&mtmd_ctx, ctx, 0, 0, n_batch, true)+ .map_err(|err| format_error("Failed to evaluate multimodal prompt", err))?;+ check_cancelled(&cancel_flag)?;++ let mut sampler = build_sampler(ctx.model, &sampler_request)?;+ let mut prompt_tokens = Vec::new();+ for index in 0..chunks.len() {+ if let Some(chunk) = chunks.get(index)+ && let Some(tokens) = chunk.text_tokens()+ {+ prompt_tokens.extend_from_slice(tokens);+ }+ }+ sampler.accept_many(prompt_tokens.iter());++ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ &mut generated_tokens_count,+ n_past,+ -1,+ )?;++ Ok(())+ })+ })) {+ Ok(inner) => inner,+ Err(_) => Err("Generation panicked".to_string()),+ };++ if let Err(err) = result {+ error_message = Some(err);+ }++ let summary = GenerateSummary {+ job_id,+ prompt_tokens: Some(prompt_tokens_count),+ generated_tokens: Some(generated_tokens_count),+ total_time_ms: Some(start.elapsed().as_millis() as i64),+ };++ if let Some(message) = error_message {+ sink.add(GenerateEvent::Error { job_id, message });+ }++ sink.add(GenerateEvent::Done {+ summary: summary.clone(),+ });++ Ok(summary)+ }++ pub fn generate_stream(+ context: &ContextHandle,+ request: GenerateRequest,+ sink: &mut dyn EventSink,+ ) -> Result<GenerateSummary, String> {+ let (job_id, cancel_flag) = register_job();+ let _job_guard = JobGuard(job_id);+ let start = Instant::now();++ sink.add(GenerateEvent::Text {+ job_id,+ text: String::new(),+ token_id: None,+ });++ let max_tokens = request.max_tokens.unwrap_or(128);+ let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);+ let stop_sequences = request.stop_sequences.clone().unwrap_or_default();++ let mut prompt_tokens_count: i32 = 0;+ let mut generated_tokens_count: i32 = 0;+ let mut error_message: Option<String> = None;++ let result = match catch_unwind(AssertUnwindSafe(|| {+ context.with_context_mut(|ctx| -> Result<(), String> {+ let add_bos = should_add_bos(ctx.model, &request.prompt);+ let prompt_tokens = ctx+ .model+ .str_to_token(&request.prompt, add_bos)+ .map_err(|err| format_error("Tokenize failed", err))?;++ if prompt_tokens.is_empty() {+ return Err("Prompt produced no tokens".to_string());+ }++ prompt_tokens_count =+ i32::try_from(prompt_tokens.len()).map_err(|_| "Prompt is too long".to_string())?;++ let n_ctx = ctx.n_ctx();+ if prompt_tokens.len() as u32 > n_ctx {+ return Err(format!(+ "Prompt length {} exceeds context size {}",+ prompt_tokens.len(),+ n_ctx+ ));+ }++ let n_batch = ctx.n_batch() as usize;+ if n_batch == 0 {+ return Err("Context batch size is 0".to_string());+ }++ ctx.clear_kv_cache();++ let mut token_offset = 0usize;+ let mut logits_index: i32 = 0;+ while token_offset < prompt_tokens.len() {+ check_cancelled(&cancel_flag)?;+ let end = (token_offset + n_batch).min(prompt_tokens.len());+ let chunk = &prompt_tokens[token_offset..end];+ let mut batch = LlamaBatch::new(chunk.len(), 1);+ for (idx, token) in chunk.iter().enumerate() {+ let pos = (token_offset + idx) as i32;+ let logits = token_offset + idx + 1 == prompt_tokens.len();+ batch+ .add(*token, pos, &[0], logits)+ .map_err(|err| format_error("Failed to add prompt token", err))?;+ }+ ctx.decode(&mut batch)+ .map_err(|err| format_error("Prompt decode failed", err))?;+ if end == prompt_tokens.len() {+ logits_index = (chunk.len() - 1) as i32;+ }+ token_offset = end;+ }++ let mut sampler = build_sampler(ctx.model, &request)?;+ sampler.accept_many(prompt_tokens.iter());++ let pos = prompt_tokens.len() as i32;+ run_generation_loop(+ ctx,+ &mut sampler,+ &cancel_flag,+ sink,+ job_id,+ max_tokens,+ &stop_sequences,+ &mut generated_tokens_count,+ pos,+ logits_index,+ )?;++ Ok(())+ })+ })) {+ Ok(inner) => inner,+ Err(_) => Err("Generation panicked".to_string()),+ };++ if let Err(err) = result {+ error_message = Some(err);+ }++ let summary = GenerateSummary {+ job_id,+ prompt_tokens: Some(prompt_tokens_count),+ generated_tokens: Some(generated_tokens_count),+ total_time_ms: Some(start.elapsed().as_millis() as i64),+ };++ if let Some(message) = error_message {+ sink.add(GenerateEvent::Error { job_id, message });+ }++ sink.add(GenerateEvent::Done {+ summary: summary.clone(),+ });++ Ok(summary)+ }++ pub fn cancel(job_id: JobId) -> Result<(), String> {+ if job_id <= 0 {+ cancel_all();+ return Ok(());+ }+ if let Some(flag) = cancel_flags().lock().get(&job_id) {+ flag.store(true, Ordering::Relaxed);+ }+ Ok(())+ }++ #[cfg(test)]+ mod tests {+ use super::StreamDecoder;++ #[test]+ fn stream_decoder_emits_complete_utf8() {+ let mut decoder = StreamDecoder::new(&[]);+ let step = decoder.push_bytes(&[0xF0, 0x9F]);+ assert!(step.text.is_none());+ assert!(!step.stop);++ let step = decoder.push_bytes(&[0x99, 0x82]);+ assert_eq!(step.text.as_deref(), Some("🙂"));+ assert!(!step.stop);+ }+ }diff --cc rust/ensu/inference/src/capi.rsindex 0000000000,9c1fbfd981..cfaee6db0cmode 000000,100644..100644--- a/rust/ensu/inference/src/capi.rs+++ b/rust/ensu/inference/src/capi.rs@@@ -1,0 -1,377 +1,384 @@@+ use crate::api::{+ self, ChatMessage, ContextHandleRef, GenerateChatRequest, GenerateEvent, GenerateRequest,+ GenerateSummary, ModelHandleRef,+ };+ use serde::Serialize;+ use std::ffi::{CStr, CString};+ use std::os::raw::{c_char, c_void};-use std::panic::{catch_unwind, AssertUnwindSafe};++use std::panic::{AssertUnwindSafe, catch_unwind};+ use std::ptr;++ #[repr(C)]+ pub struct inference_model {+ handle: ModelHandleRef,+ }++ #[repr(C)]+ pub struct inference_context {+ handle: ContextHandleRef,+ }++ type EventCallback = Option<extern "C" fn(*const u8, usize, *mut c_void)>;++ #[derive(Serialize)]+ #[serde(tag = "type", rename_all = "snake_case")]+ enum CapiEvent {+ Text {+ job_id: api::JobId,+ text: String,+ token_id: Option<i32>,+ },- Done { summary: GenerateSummary },++ Done {++ summary: GenerateSummary,++ },+ Error {+ job_id: api::JobId,+ message: String,+ },+ }++ impl From<GenerateEvent> for CapiEvent {+ fn from(value: GenerateEvent) -> Self {+ match value {+ GenerateEvent::Text {+ job_id,+ text,+ token_id,+ } => Self::Text {+ job_id,+ text,+ token_id,+ },+ GenerateEvent::Done { summary } => Self::Done { summary },+ GenerateEvent::Error { job_id, message } => Self::Error { job_id, message },+ }+ }+ }++ struct CapiEventSink {+ callback: EventCallback,+ user_data: *mut c_void,+ }++ impl api::EventSink for CapiEventSink {+ fn add(&mut self, event: GenerateEvent) {+ let Some(callback) = self.callback else {+ return;+ };++ let payload = CapiEvent::from(event);+ let json = serde_json::to_vec(&payload)+ .unwrap_or_else(|_| br#"{"type":"error","message":"serialization_failed"}"#.to_vec());+ callback(json.as_ptr(), json.len(), self.user_data);+ }+ }++ fn clear_error(error_out: *mut *mut c_char) {+ if error_out.is_null() {+ return;+ }+ unsafe {+ *error_out = ptr::null_mut();+ }+ }++ fn set_error(error_out: *mut *mut c_char, message: impl AsRef<str>) {+ if error_out.is_null() {+ return;+ }+ let message = message.as_ref();+ let cstring = CString::new(message).unwrap_or_else(|_| CString::new("invalid error").unwrap());+ unsafe {+ *error_out = cstring.into_raw();+ }+ }++ fn with_error<T>(error_out: *mut *mut c_char, result: Result<T, String>) -> Option<T> {+ match result {+ Ok(value) => {+ clear_error(error_out);+ Some(value)+ }+ Err(err) => {+ set_error(error_out, err);+ None+ }+ }+ }++ fn cstr_to_string(ptr: *const c_char, field: &str) -> Result<String, String> {+ if ptr.is_null() {+ return Err(format!("{field} is required"));+ }+ let cstr = unsafe { CStr::from_ptr(ptr) };+ cstr.to_str()+ .map(|value| value.to_string())+ .map_err(|err| format!("Invalid {field}: {err}"))+ }++ fn optional_cstr(ptr: *const c_char) -> Result<Option<String>, String> {+ if ptr.is_null() {+ return Ok(None);+ }+ let cstr = unsafe { CStr::from_ptr(ptr) };+ let value = cstr+ .to_str()+ .map_err(|err| format!("Invalid string: {err}"))?;+ if value.is_empty() {+ Ok(None)+ } else {+ Ok(Some(value.to_string()))+ }+ }++ fn parse_json<T>(json_ptr: *const c_char, field: &str) -> Result<T, String>+ where+ T: serde::de::DeserializeOwned,+ {+ let json = cstr_to_string(json_ptr, field)?;+ serde_json::from_str(&json).map_err(|err| format!("Invalid {field} JSON: {err}"))+ }++ fn to_json_string<T: Serialize>(value: &T) -> Result<*mut c_char, String> {+ let json = serde_json::to_string(value).map_err(|err| err.to_string())?;+ CString::new(json)+ .map_err(|err| err.to_string())+ .map(|value| value.into_raw())+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_string_free(value: *mut c_char) {+ if value.is_null() {+ return;+ }+ unsafe {+ drop(CString::from_raw(value));+ }+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_init_backend(error_out: *mut *mut c_char) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| api::init_backend()));+ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("init_backend panicked".to_string()),+ };+ with_error(error_out, result).is_some()+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_load_model(+ params_json: *const c_char,+ error_out: *mut *mut c_char,+ ) -> *mut inference_model {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let params = parse_json::<api::ModelLoadParams>(params_json, "params_json")?;+ api::load_model(params)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("load_model panicked".to_string()),+ };++ let Some(handle) = with_error(error_out, result) else {+ return ptr::null_mut();+ };++ Box::into_raw(Box::new(inference_model { handle }))+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_model_free(model: *mut inference_model) {+ if model.is_null() {+ return;+ }+ unsafe {+ drop(Box::from_raw(model));+ }+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_create_context(+ model: *const inference_model,+ params_json: *const c_char,+ error_out: *mut *mut c_char,+ ) -> *mut inference_context {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let params = parse_json::<api::ContextParams>(params_json, "params_json")?;+ api::create_context(model.handle.clone(), params)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("create_context panicked".to_string()),+ };++ let Some(handle) = with_error(error_out, result) else {+ return ptr::null_mut();+ };++ Box::into_raw(Box::new(inference_context { handle }))+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_context_free(context: *mut inference_context) {+ if context.is_null() {+ return;+ }+ unsafe {+ drop(Box::from_raw(context));+ }+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_tokenize_json(+ model: *const inference_model,+ text: *const c_char,+ add_bos: bool,+ special: bool,+ error_out: *mut *mut c_char,+ ) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let text = cstr_to_string(text, "text")?;+ let tokens = api::tokenize(model.handle.as_ref(), text, add_bos, special)?;+ to_json_string(&tokens)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("tokenize panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_detokenize_json(+ model: *const inference_model,+ tokens_json: *const c_char,+ error_out: *mut *mut c_char,+ ) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let tokens = parse_json::<Vec<i32>>(tokens_json, "tokens_json")?;+ let text = api::detokenize(model.handle.as_ref(), tokens)?;+ to_json_string(&text)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("detokenize panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_get_model_info_json(+ model: *const inference_model,+ error_out: *mut *mut c_char,+ ) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let info = api::get_model_info(model.handle.as_ref())?;+ to_json_string(&info)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("get_model_info panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_apply_chat_template_json(+ model: *const inference_model,+ messages_json: *const c_char,+ template_override: *const c_char,+ add_assistant: bool,+ error_out: *mut *mut c_char,+ ) -> *mut c_char {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let model = unsafe { model.as_ref() }.ok_or_else(|| "model is required".to_string())?;+ let messages = parse_json::<Vec<ChatMessage>>(messages_json, "messages_json")?;+ let template_override = optional_cstr(template_override)?;+ let rendered = api::apply_chat_template(+ model.handle.as_ref(),+ messages,+ template_override,+ add_assistant,+ )?;+ to_json_string(&rendered)+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("apply_chat_template panicked".to_string()),+ };++ with_error(error_out, result).unwrap_or(ptr::null_mut())+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_generate_chat_stream(+ context: *const inference_context,+ request_json: *const c_char,+ callback: EventCallback,+ user_data: *mut c_void,+ error_out: *mut *mut c_char,+ ) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let context =+ unsafe { context.as_ref() }.ok_or_else(|| "context is required".to_string())?;+ let request = parse_json::<GenerateChatRequest>(request_json, "request_json")?;- let mut sink = CapiEventSink { callback, user_data };- api::generate_chat_stream(context.handle.as_ref(), request, &mut sink)- .map(|_| ())++ let mut sink = CapiEventSink {++ callback,++ user_data,++ };++ api::generate_chat_stream(context.handle.as_ref(), request, &mut sink).map(|_| ())+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("generate_chat_stream panicked".to_string()),+ };++ with_error(error_out, result).is_some()+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_generate_stream(+ context: *const inference_context,+ request_json: *const c_char,+ callback: EventCallback,+ user_data: *mut c_void,+ error_out: *mut *mut c_char,+ ) -> bool {+ let result = catch_unwind(AssertUnwindSafe(|| {+ let context =+ unsafe { context.as_ref() }.ok_or_else(|| "context is required".to_string())?;+ let request = parse_json::<GenerateRequest>(request_json, "request_json")?;- let mut sink = CapiEventSink { callback, user_data };++ let mut sink = CapiEventSink {++ callback,++ user_data,++ };+ api::generate_stream(context.handle.as_ref(), request, &mut sink).map(|_| ())+ }));++ let result = match result {+ Ok(inner) => inner,+ Err(_) => Err("generate_stream panicked".to_string()),+ };++ with_error(error_out, result).is_some()+ }++ #[unsafe(no_mangle)]+ pub extern "C" fn inference_cancel(job_id: i64) {+ let _ = api::cancel(job_id);+ }diff --cc rust/uniffi/ensu/db/Cargo.tomlindex 0000000000,a1f04674dd..a09ca66c90mode 000000,100644..100644--- a/rust/uniffi/ensu/db/Cargo.toml+++ b/rust/uniffi/ensu/db/Cargo.toml@@@ -1,0 -1,16 +1,15 @@@+ [package]+ name = "db"+ version = "0.1.0"+ edition = "2024"++ [lib]+ name = "db"+ crate-type = ["staticlib", "cdylib"]++ [dependencies]+ ensu-db = { path = "../../../ensu/db" }+ serde = { version = "1", features = ["derive"] }+ thiserror = "2"+ uniffi = { version = "0.31.0" }+ uuid = { version = "1" }-