This commit is contained in:
mayunfei committed 2026-12-04 09:40:59 +08:00
commit a20f3c0925
77 files changed
+6707

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
*.iml
.gradle/
/local.properties
/.idea/
.DS_Store
/build/
/app/build/
/captures/
.externalNativeBuild/
.cxx/
*.apk
*.ap_
*.aab
*.dex
*.class
bin/
gen/
out/
.kotlin/
+104
View File
@@ -0,0 +1,104 @@
产品需求与技术架构文档(PRD):OmniChat Android
目标定位: 融合 Cherry Studio(多提供商直连、智能端点路由、原生多模态高还原生图)与 Open WebUI(强大工具调用、提示词预设、重型长连接防超时持久化)优点的原生 Android 客户端。
1. 技术栈选型(Cursor 友好且现代化)
开发语言: Kotlin 2.x
UI 框架: Jetpack Compose + Material 3(深色/浅色主题自适应)
架构模式: MVVM + Clean Architecture(UI 层 -> ViewModel -> Repository -> Network / Local DB)
网络层: OkHttp 5.x + Retrofit + Kotlinx Serialization(严禁使用默认短超时,必须配置长连接池与自定义超时拦截器)
流式解析: OkHttp SSE (okhttp-sse) + Kotlin Flow(处理对话与生图流式响应)
本地持久化: Room Database(存储会话、消息、服务商配置、提示词预设)+ DataStore(全局设置)+ 内部存储文件目录(高清原图落盘,数据库仅存本地 URI,避免 SQLite CursorWindow 溢出)
图片加载与压缩: Coil 3(异步加载与缓存)+ 原生 Bitmap 压缩工具(上传前可选自动缩放至长边 1536px,避免请求体过大超时)
2. 核心功能模块与业务逻辑
模块一:多服务商与模型路由管理(融合 Cherry Studio)
API 服务商配置(Providers):
支持添加多个 OpenAI 兼容服务商(自定义名称、Base URL 自动补全/校验 /v1、API Key 加密存储)。
一键拉取 /v1/models 列表,支持手动添加隐藏模型 ID,支持按关键字搜索与分组折叠。
模型能力标签(Model Capabilities):
每个模型可配置或自动识别标签:Chat(文本对话)、Vision(多模态识图)、ImageGen(图像生成/编辑)、Reasoning(深度思考,解析 <think> 或 reasoning_content 标签)。
默认全局角色指定:
默认对话模型
默认文生图模型
默认图像编辑(参考图)模型(独立指定,防止对话模型误调纯文生图接口)
模块二:智能生图与参考图高还原引擎(核心差异化痛点解决)
必须严格区分以下两种生图路由,彻底避免“参考图人脸丢失”和“客户端超时不出图”:
智能端点路由器(Smart Image Router):
路径 A:图像专用模型(如 gpt-image-*、dall-e-*、flux 等不支持 Chat Completions 的模型)
无参考图时: 自动请求 POST /v1/images/generations(JSON Body)。
有参考图时: 强制自动切换为 POST /v1/images/edits(支持 multipart/form-data 上传原图二进制流,同时兼容部分中转站的 JSON images: [{image_url}] 格式),将用户的原始提示词直传后端,严禁经由对话 LLM 二次改写提示词。
路径 B:原生多模态生图模型(如 gemini-*-image*、支持图生图的 Chat Completions 模型)
直接打包「参考图 Base64 + 用户原始指令」走 POST /v1/chat/completions,解析返回体中的 Markdown 图片链接或内联 Base64 图像数据。
路径 C:对话模式外挂生图工具(类似 Open WebUI 的工具开关)
在普通文本对话界面提供「生图模式」快捷开关。开启后,若用户未传图则调用文生图模型;若用户上传了参考图,强制路由至「默认图像编辑模型」的 /v1/images/edits 端点,并附带原始图像字节流。
重型图像防超时与落盘机制(解决中转站已出图但端侧超时):
专用 OkHttpClient 实例(共享连接池):
connectTimeout:30 秒
writeTimeout:120 秒(应对多张高清参考图上传)
readTimeout:300 秒(应对生图静默等待期,防止代理或客户端过早掐断连接)
callTimeout:360 秒
双格式响应解析器: 同时兼容返回 data[0].b64_json(十余 MB 的 Base64 字符串)和 data[0].url。
流式解码落盘: 收到 b64_json 后立即在 Dispatchers.IO 线程解码为 PNG/JPG 文件写入 App 私有目录 files/generated_images/,或收到 url 后立即异步下载到本地(防止中转站临时 URL 过期),UI 层仅通过本地 file:// URI 渲染。
模块三:多模态对话与增强体验(融合 Open WebUI)
富文本与推理渲染:
支持标准 Markdown 渲染、代码块语法高亮及一键复制、LaTeX 数学公式渲染。
自动折叠/展开模型的深度思考过程(兼容 reasoning_content 字段及 <think>...</think> 标签)。
上下文与附件管理:
支持拍照、相册多选(参考图对比/融合)、本地文档(TXT/MD/PDF 提取文本注入上下文)。
上传参考图前提供「原图 / 智能压缩(长边 1536px, 85% 质量)」切换开关,兼顾面部细节保留与传输速度。
支持单条消息重新生成、编辑历史消息重发、滑动调节上下文携带轮数(Context Window)。
助手预设(System Prompts / Agents):
内置常用提示词模板(如“参考图面部一致性精修”、“代码架构师”),支持一键新建角色并绑定专属默认模型与 temperature 参数。
后台保活(Foreground Service):
当发起耗时较长的生图请求或长文本流式输出时,启动轻量级 Android 前台服务(通知栏显示“正在生成图像…”),防止切出 App 或锁屏后系统杀掉网络请求。
3. 数据库表结构设计(Room)
providers:id, name, baseUrl, apiKey, isEnabled
models:id, providerId, modelId, displayName, capabilities (JSON List: CHAT, VISION, IMAGE_GEN, IMAGE_EDIT, REASONING)
conversations:id, title, modelId, providerId, systemPrompt, updatedAt
messages:id, conversationId, role (user/assistant/system), content, reasoningContent, imagePaths (JSON List of local file paths), status (SENDING/STREAMING/SUCCESS/ERROR), errorMessage, timestamp
+36
View File
@@ -0,0 +1,36 @@
# OmniChat
Android client that combines Cherry Studio–style high-fidelity image edits with Open WebUI–style long-running, OpenAI-compatible chat.
## Requirements
- Android Studio Ladybug (2024.2+) or newer
- JDK 17
- Android SDK 35 (device or emulator; tested target: Android 15)
## Open in Android Studio
1. **File → Open** and select this folder (`MyOpenChat`)
2. Wait for Gradle Sync
3. Run the `app` configuration on a phone/emulator (API 29+)
## CLI build
```bash
./gradlew :app:assembleDebug
```
On Windows PowerShell:
```powershell
.\gradlew.bat :app:assembleDebug
```
## Current status (Phase 1–4)
- Compose + Material 3 shell with tabs: 对话 / 生图 / 设置
- Network: shared OkHttp pool, chat/image clients, OpenAI-compatible APIs + SSE
- Room + encrypted API keys + Provider/Model settings
- Chat: streaming multimodal + Path C「生图模式」
- SmartImageRouter: Path A generations/edits, Path B chat multimodal, b64/url 落盘
- Foreground service during image gen + save to system gallery
+84
View File
@@ -0,0 +1,84 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
}
android {
namespace = "com.omnichat.app"
compileSdk = 35
defaultConfig {
applicationId = "com.omnichat.app"
minSdk = 29
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons)
implementation(libs.androidx.navigation.compose)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.okhttp)
implementation(libs.okhttp.sse)
implementation(libs.okhttp.logging)
implementation(libs.retrofit)
implementation(libs.retrofit.kotlinx.serialization)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
ksp(libs.androidx.room.compiler)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.security.crypto)
implementation(libs.coil.compose)
implementation(libs.coil.network.okhttp)
implementation(libs.markwon.core)
implementation(libs.markwon.ext.strikethrough)
implementation(libs.markwon.linkify)
}
+1
View File
@@ -0,0 +1 @@
# OmniChat — keep rules will expand with networking / Room in later steps.
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<application
android:name=".OmniChatApp"
android:allowBackup="true"
android:icon="@drawable/ic_launcher_foreground"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@drawable/ic_launcher_foreground"
android:supportsRtl="true"
android:theme="@style/Theme.OmniChat">
<activity
android:name=".MainActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize"
android:theme="@style/Theme.OmniChat">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".service.ImageGenerationForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -0,0 +1,22 @@
package com.omnichat.app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import com.omnichat.app.ui.navigation.OmniChatNavHost
import com.omnichat.app.ui.theme.OmniChatTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OmniChatTheme {
OmniChatNavHost(modifier = Modifier.fillMaxSize())
}
}
}
}
@@ -0,0 +1,14 @@
package com.omnichat.app
import android.app.Application
import com.omnichat.app.di.AppContainer
class OmniChatApp : Application() {
lateinit var container: AppContainer
private set
override fun onCreate() {
super.onCreate()
container = AppContainer(this)
}
}
@@ -0,0 +1,6 @@
package com.omnichat.app.data.local
/**
* Room / DataStore implementations land in later steps (Provider CRUD, conversations).
*/
object LocalDataPlaceholders
@@ -0,0 +1,98 @@
package com.omnichat.app.data.local.datastore
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.omnichat.app.domain.model.ImageUploadMode
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "omnichat_settings")
data class DefaultModelRefs(
val chatModelRowId: Long? = null,
val imageGenModelRowId: Long? = null,
val imageEditModelRowId: Long? = null,
)
data class ChatPrefs(
val contextWindowRounds: Int = 20,
val imageUploadMode: ImageUploadMode = ImageUploadMode.SMART_COMPRESS,
val lastConversationId: Long? = null,
)
class AppSettingsDataStore(private val context: Context) {
private object Keys {
val defaultChatModel = longPreferencesKey("default_chat_model_id")
val defaultImageGenModel = longPreferencesKey("default_image_gen_model_id")
val defaultImageEditModel = longPreferencesKey("default_image_edit_model_id")
val contextWindowRounds = intPreferencesKey("context_window_rounds")
val smartCompress = booleanPreferencesKey("smart_compress_images")
val lastConversationId = longPreferencesKey("last_conversation_id")
}
val defaults: Flow<DefaultModelRefs> = context.dataStore.data.map { prefs ->
DefaultModelRefs(
chatModelRowId = prefs[Keys.defaultChatModel],
imageGenModelRowId = prefs[Keys.defaultImageGenModel],
imageEditModelRowId = prefs[Keys.defaultImageEditModel],
)
}
val chatPrefs: Flow<ChatPrefs> = context.dataStore.data.map { prefs ->
ChatPrefs(
contextWindowRounds = prefs[Keys.contextWindowRounds] ?: 20,
imageUploadMode = if (prefs[Keys.smartCompress] == false) {
ImageUploadMode.ORIGINAL
} else {
ImageUploadMode.SMART_COMPRESS
},
lastConversationId = prefs[Keys.lastConversationId],
)
}
suspend fun setDefaultChatModel(modelRowId: Long?) {
context.dataStore.edit { prefs ->
if (modelRowId == null) prefs.remove(Keys.defaultChatModel)
else prefs[Keys.defaultChatModel] = modelRowId
}
}
suspend fun setDefaultImageGenModel(modelRowId: Long?) {
context.dataStore.edit { prefs ->
if (modelRowId == null) prefs.remove(Keys.defaultImageGenModel)
else prefs[Keys.defaultImageGenModel] = modelRowId
}
}
suspend fun setDefaultImageEditModel(modelRowId: Long?) {
context.dataStore.edit { prefs ->
if (modelRowId == null) prefs.remove(Keys.defaultImageEditModel)
else prefs[Keys.defaultImageEditModel] = modelRowId
}
}
suspend fun setContextWindowRounds(rounds: Int) {
context.dataStore.edit { prefs ->
prefs[Keys.contextWindowRounds] = rounds.coerceIn(2, 64)
}
}
suspend fun setSmartCompress(enabled: Boolean) {
context.dataStore.edit { prefs ->
prefs[Keys.smartCompress] = enabled
}
}
suspend fun setLastConversationId(id: Long?) {
context.dataStore.edit { prefs ->
if (id == null) prefs.remove(Keys.lastConversationId)
else prefs[Keys.lastConversationId] = id
}
}
}
@@ -0,0 +1,40 @@
package com.omnichat.app.data.local.db
import androidx.room.TypeConverter
import com.omnichat.app.domain.model.MessageStatus
import com.omnichat.app.domain.model.ModelCapability
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class Converters {
private val json = Json { ignoreUnknownKeys = true }
@TypeConverter
fun capabilitiesToString(value: List<ModelCapability>): String =
json.encodeToString(value.map { it.name })
@TypeConverter
fun capabilitiesFromString(value: String): List<ModelCapability> {
if (value.isBlank()) return emptyList()
return json.decodeFromString<List<String>>(value).mapNotNull { name ->
runCatching { ModelCapability.valueOf(name) }.getOrNull()
}
}
@TypeConverter
fun stringListToString(value: List<String>): String =
json.encodeToString(value)
@TypeConverter
fun stringListFromString(value: String): List<String> {
if (value.isBlank()) return emptyList()
return json.decodeFromString(value)
}
@TypeConverter
fun messageStatusToString(value: MessageStatus): String = value.name
@TypeConverter
fun messageStatusFromString(value: String): MessageStatus =
runCatching { MessageStatus.valueOf(value) }.getOrDefault(MessageStatus.SUCCESS)
}
@@ -0,0 +1,43 @@
package com.omnichat.app.data.local.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.omnichat.app.data.local.db.dao.ConversationDao
import com.omnichat.app.data.local.db.dao.MessageDao
import com.omnichat.app.data.local.db.dao.ModelDao
import com.omnichat.app.data.local.db.dao.ProviderDao
import com.omnichat.app.data.local.db.entity.ConversationEntity
import com.omnichat.app.data.local.db.entity.MessageEntity
import com.omnichat.app.data.local.db.entity.ModelEntity
import com.omnichat.app.data.local.db.entity.ProviderEntity
@Database(
entities = [
ProviderEntity::class,
ModelEntity::class,
ConversationEntity::class,
MessageEntity::class,
],
version = 1,
exportSchema = false,
)
@TypeConverters(Converters::class)
abstract class OmniChatDatabase : RoomDatabase() {
abstract fun providerDao(): ProviderDao
abstract fun modelDao(): ModelDao
abstract fun conversationDao(): ConversationDao
abstract fun messageDao(): MessageDao
companion object {
fun create(context: Context): OmniChatDatabase =
Room.databaseBuilder(
context.applicationContext,
OmniChatDatabase::class.java,
"omnichat.db",
).fallbackToDestructiveMigration()
.build()
}
}
@@ -0,0 +1,27 @@
package com.omnichat.app.data.local.db.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.omnichat.app.data.local.db.entity.ConversationEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface ConversationDao {
@Query("SELECT * FROM conversations ORDER BY updatedAt DESC")
fun observeAll(): Flow<List<ConversationEntity>>
@Query("SELECT * FROM conversations WHERE id = :id")
suspend fun getById(id: Long): ConversationEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(entity: ConversationEntity): Long
@Update
suspend fun update(entity: ConversationEntity)
@Query("DELETE FROM conversations WHERE id = :id")
suspend fun deleteById(id: Long)
}
@@ -0,0 +1,40 @@
package com.omnichat.app.data.local.db.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.omnichat.app.data.local.db.entity.MessageEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface MessageDao {
@Query("SELECT * FROM messages WHERE conversationId = :conversationId ORDER BY timestamp ASC")
fun observeByConversation(conversationId: Long): Flow<List<MessageEntity>>
@Query("SELECT * FROM messages WHERE conversationId = :conversationId ORDER BY timestamp ASC")
suspend fun getByConversation(conversationId: Long): List<MessageEntity>
@Query("SELECT * FROM messages WHERE id = :id")
suspend fun getById(id: Long): MessageEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(entity: MessageEntity): Long
@Update
suspend fun update(entity: MessageEntity)
@Query("DELETE FROM messages WHERE id = :id")
suspend fun deleteById(id: Long)
@Query(
"""
DELETE FROM messages WHERE conversationId = :conversationId AND id >= :fromId
""",
)
suspend fun deleteFromId(conversationId: Long, fromId: Long)
@Query("DELETE FROM messages WHERE conversationId = :conversationId")
suspend fun deleteByConversation(conversationId: Long)
}
@@ -0,0 +1,45 @@
package com.omnichat.app.data.local.db.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.omnichat.app.data.local.db.entity.ModelEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface ModelDao {
@Query("SELECT * FROM models WHERE providerId = :providerId ORDER BY displayName COLLATE NOCASE ASC")
fun observeByProvider(providerId: Long): Flow<List<ModelEntity>>
@Query("SELECT * FROM models WHERE providerId = :providerId ORDER BY displayName COLLATE NOCASE ASC")
suspend fun getByProvider(providerId: Long): List<ModelEntity>
@Query("SELECT * FROM models ORDER BY providerId ASC, displayName COLLATE NOCASE ASC")
fun observeAll(): Flow<List<ModelEntity>>
@Query("SELECT * FROM models WHERE id = :id")
suspend fun getById(id: Long): ModelEntity?
@Query("SELECT * FROM models WHERE providerId = :providerId AND modelId = :modelId LIMIT 1")
suspend fun getByProviderAndModelId(providerId: Long, modelId: String): ModelEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(entity: ModelEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(entities: List<ModelEntity>)
@Update
suspend fun update(entity: ModelEntity)
@Query("DELETE FROM models WHERE id = :id")
suspend fun deleteById(id: Long)
@Query("DELETE FROM models WHERE providerId = :providerId AND isManual = 0")
suspend fun deleteFetchedByProvider(providerId: Long)
@Query("DELETE FROM models WHERE providerId = :providerId")
suspend fun deleteByProvider(providerId: Long)
}
@@ -0,0 +1,31 @@
package com.omnichat.app.data.local.db.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.omnichat.app.data.local.db.entity.ProviderEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface ProviderDao {
@Query("SELECT * FROM providers ORDER BY id ASC")
fun observeAll(): Flow<List<ProviderEntity>>
@Query("SELECT * FROM providers WHERE id = :id")
suspend fun getById(id: Long): ProviderEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(entity: ProviderEntity): Long
@Update
suspend fun update(entity: ProviderEntity)
@Delete
suspend fun delete(entity: ProviderEntity)
@Query("DELETE FROM providers WHERE id = :id")
suspend fun deleteById(id: Long)
}
@@ -0,0 +1,14 @@
package com.omnichat.app.data.local.db.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "conversations")
data class ConversationEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
val modelId: String?,
val providerId: Long?,
val systemPrompt: String? = null,
val updatedAt: Long = System.currentTimeMillis(),
)
@@ -0,0 +1,31 @@
package com.omnichat.app.data.local.db.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.omnichat.app.domain.model.MessageStatus
@Entity(
tableName = "messages",
foreignKeys = [
ForeignKey(
entity = ConversationEntity::class,
parentColumns = ["id"],
childColumns = ["conversationId"],
onDelete = ForeignKey.CASCADE,
),
],
indices = [Index(value = ["conversationId"])],
)
data class MessageEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val conversationId: Long,
val role: String,
val content: String,
val reasoningContent: String? = null,
val imagePaths: List<String> = emptyList(),
val status: MessageStatus = MessageStatus.SUCCESS,
val errorMessage: String? = null,
val timestamp: Long = System.currentTimeMillis(),
)
@@ -0,0 +1,32 @@
package com.omnichat.app.data.local.db.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.omnichat.app.domain.model.ModelCapability
@Entity(
tableName = "models",
foreignKeys = [
ForeignKey(
entity = ProviderEntity::class,
parentColumns = ["id"],
childColumns = ["providerId"],
onDelete = ForeignKey.CASCADE,
),
],
indices = [
Index(value = ["providerId"]),
Index(value = ["providerId", "modelId"], unique = true),
],
)
data class ModelEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val providerId: Long,
val modelId: String,
val displayName: String,
val capabilities: List<ModelCapability> = emptyList(),
/** True when user typed the model id manually (not from /v1/models). */
val isManual: Boolean = false,
)
@@ -0,0 +1,15 @@
package com.omnichat.app.data.local.db.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "providers")
data class ProviderEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
/** Normalized base URL ending with `/v1/` (display may strip trailing slash). */
val baseUrl: String,
/** Ciphertext produced by [com.omnichat.app.data.local.security.ApiKeyCipher]. */
val apiKeyEncrypted: String,
val isEnabled: Boolean = true,
)
@@ -0,0 +1,43 @@
package com.omnichat.app.data.local.media
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.provider.MediaStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
class GallerySaver(
private val context: Context,
) {
suspend fun saveImage(file: File): Result<Unit> = withContext(Dispatchers.IO) {
runCatching {
require(file.exists()) { "文件不存在" }
val mime = when (file.extension.lowercase()) {
"jpg", "jpeg" -> "image/jpeg"
"webp" -> "image/webp"
else -> "image/png"
}
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, file.name)
put(MediaStore.Images.Media.MIME_TYPE, mime)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/OmniChat")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
?: error("无法写入系统相册")
resolver.openOutputStream(uri)?.use { output ->
file.inputStream().use { input -> input.copyTo(output) }
} ?: error("无法打开相册输出流")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
resolver.update(uri, values, null, null)
}
}
}
}
@@ -0,0 +1,99 @@
package com.omnichat.app.data.local.media
import android.content.Context
import android.util.Base64
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.util.concurrent.TimeUnit
/**
* Persists generated images under `files/generated_images/` immediately so
* temporary relay URLs cannot expire before the UI renders them.
*/
class GeneratedImageStore(
private val context: Context,
) {
private val downloadClient: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.callTimeout(180, TimeUnit.SECONDS)
.build()
private val dir: File
get() = File(context.filesDir, "generated_images").apply { mkdirs() }
suspend fun saveFromB64Json(b64: String, preferredExt: String = "png"): File =
withContext(Dispatchers.IO) {
val cleaned = b64
.substringAfter("base64,", b64)
.replace("\n", "")
.replace("\r", "")
.trim()
val bytes = Base64.decode(cleaned, Base64.DEFAULT)
val ext = detectExt(bytes) ?: preferredExt
val out = File(dir, "gen_${System.currentTimeMillis()}_${bytes.hashCode().toUInt()}.$ext")
out.writeBytes(bytes)
out
}
suspend fun saveFromUrl(url: String): File = withContext(Dispatchers.IO) {
if (url.startsWith("data:image", ignoreCase = true)) {
val b64 = url.substringAfter("base64,", missingDelimiterValue = "")
require(b64.isNotBlank()) { "无效的 data URL" }
return@withContext saveFromB64Json(b64)
}
val request = Request.Builder().url(url).get().build()
downloadClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
error("下载图片失败: HTTP ${response.code}")
}
val bytes = response.body?.bytes() ?: error("空图片响应")
val ext = detectExt(bytes)
?: guessExtFromContentType(response.header("Content-Type"))
?: "png"
val out = File(dir, "gen_${System.currentTimeMillis()}.$ext")
out.writeBytes(bytes)
out
}
}
fun listRecent(limit: Int = 50): List<File> {
return dir.listFiles()
?.filter { it.isFile }
?.sortedByDescending { it.lastModified() }
?.take(limit)
.orEmpty()
}
private fun detectExt(bytes: ByteArray): String? {
if (bytes.size >= 8 &&
bytes[0] == 0x89.toByte() && bytes[1] == 0x50.toByte() &&
bytes[2] == 0x4E.toByte() && bytes[3] == 0x47.toByte()
) {
return "png"
}
if (bytes.size >= 3 &&
bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() && bytes[2] == 0xFF.toByte()
) {
return "jpg"
}
if (bytes.size >= 12 &&
bytes.copyOfRange(0, 4).toString(Charsets.US_ASCII) == "RIFF" &&
bytes.copyOfRange(8, 12).toString(Charsets.US_ASCII) == "WEBP"
) {
return "webp"
}
return null
}
private fun guessExtFromContentType(contentType: String?): String? = when {
contentType == null -> null
contentType.contains("png") -> "png"
contentType.contains("jpeg") || contentType.contains("jpg") -> "jpg"
contentType.contains("webp") -> "webp"
else -> null
}
}
@@ -0,0 +1,117 @@
package com.omnichat.app.data.local.media
import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import com.omnichat.app.domain.model.ImageUploadMode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import kotlin.math.max
class ImageCompressor(
private val context: Context,
) {
/**
* Copies / compresses [uri] into app private storage.
* Pass the Activity [ContentResolver] when reading Photo Picker URIs —
* temporary grants are tied to the Activity that launched the picker.
*/
suspend fun materialize(
uri: Uri,
mode: ImageUploadMode,
subDir: String = "chat_attachments",
resolver: ContentResolver = context.contentResolver,
): File = withContext(Dispatchers.IO) {
val dir = File(context.filesDir, subDir).apply { mkdirs() }
val outFile = File(dir, "img_${System.currentTimeMillis()}.jpg")
when (mode) {
ImageUploadMode.ORIGINAL -> copyOriginal(uri, outFile, resolver)
ImageUploadMode.SMART_COMPRESS -> compressSmart(uri, outFile, resolver)
}
outFile
}
/** Re-process an already-local file (e.g. after compress mode changes). */
suspend fun materializeFile(
source: File,
mode: ImageUploadMode,
subDir: String = "chat_attachments",
): File = withContext(Dispatchers.IO) {
require(source.exists()) { "本地参考图不存在: ${source.absolutePath}" }
if (mode == ImageUploadMode.ORIGINAL) return@withContext source
materialize(Uri.fromFile(source), mode, subDir, context.contentResolver)
}
private fun openStream(uri: Uri, resolver: ContentResolver): InputStream {
if (uri.scheme.equals("file", ignoreCase = true)) {
val path = uri.path ?: error("无效的 file URI")
return FileInputStream(File(path))
}
return resolver.openInputStream(uri)
?: resolver.openAssetFileDescriptor(uri, "r")?.createInputStream()
?: error("无法读取图片(URI 权限可能已失效,请重新选择): $uri")
}
private fun copyOriginal(uri: Uri, outFile: File, resolver: ContentResolver): File {
openStream(uri, resolver).use { input ->
FileOutputStream(outFile).use { output -> input.copyTo(output) }
}
return outFile
}
private fun compressSmart(uri: Uri, outFile: File, resolver: ContentResolver): File {
// Read fully once — some providers only allow a single open.
val bytes = openStream(uri, resolver).use { it.readBytes() }
require(bytes.isNotEmpty()) { "图片内容为空" }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
val longEdge = max(bounds.outWidth, bounds.outHeight).coerceAtLeast(1)
val sample = if (longEdge > 1536) {
Integer.highestOneBit((longEdge / 1536).coerceAtLeast(1))
} else {
1
}
val decode = BitmapFactory.Options().apply { inSampleSize = sample }
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, decode)
?: error("无法解码图片")
val scaled = scaleToLongEdge(bitmap, 1536)
if (scaled !== bitmap) bitmap.recycle()
FileOutputStream(outFile).use { fos ->
scaled.compress(Bitmap.CompressFormat.JPEG, 85, fos)
}
scaled.recycle()
return outFile
}
private fun scaleToLongEdge(source: Bitmap, maxLongEdge: Int): Bitmap {
val longEdge = max(source.width, source.height)
if (longEdge <= maxLongEdge) return source
val scale = maxLongEdge.toFloat() / longEdge
val w = (source.width * scale).toInt().coerceAtLeast(1)
val h = (source.height * scale).toInt().coerceAtLeast(1)
return Bitmap.createScaledBitmap(source, w, h, true)
}
fun toDataUrl(file: File): String {
val bytes = file.readBytes()
val mime = when (file.extension.lowercase()) {
"png" -> "image/png"
"webp" -> "image/webp"
else -> "image/jpeg"
}
val b64 = android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
return "data:$mime;base64,$b64"
}
}
@@ -0,0 +1,43 @@
package com.omnichat.app.data.local.security
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import java.util.UUID
/**
* Encrypts API keys via AndroidX Security Crypto (AES256-GCM).
* Room stores only opaque tokens that map back to ciphertext blobs.
*/
class ApiKeyCipher(context: Context) {
private val prefs = EncryptedSharedPreferences.create(
"omnichat_api_keys",
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
context.applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
)
fun encrypt(plainApiKey: String): String {
val token = "key_${UUID.randomUUID()}"
prefs.edit().putString(token, plainApiKey).apply()
return token
}
fun decrypt(token: String): String {
if (token.isBlank()) return ""
return prefs.getString(token, "") ?: ""
}
fun rotate(oldToken: String?, plainApiKey: String): String {
if (!oldToken.isNullOrBlank()) {
prefs.edit().remove(oldToken).apply()
}
return encrypt(plainApiKey)
}
fun delete(token: String?) {
if (token.isNullOrBlank()) return
prefs.edit().remove(token).apply()
}
}
@@ -0,0 +1,146 @@
package com.omnichat.app.data.remote
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import com.omnichat.app.data.remote.api.OpenAiApi
import com.omnichat.app.data.remote.sse.ChatCompletionsSseClient
import kotlinx.serialization.json.Json
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit
/**
* Central networking factory.
*
* Shares one [ConnectionPool] across clients so chat SSE and long-running image calls
* reuse keep-alive sockets. Image client uses PRD timeouts (read=300s, call=360s).
*/
object NetworkModule {
private const val MAX_IDLE_CONNECTIONS = 10
private const val KEEP_ALIVE_DURATION_MINUTES = 5L
val json: Json = Json {
ignoreUnknownKeys = true
explicitNulls = false
encodeDefaults = true
isLenient = true
}
private val sharedConnectionPool = ConnectionPool(
MAX_IDLE_CONNECTIONS,
KEEP_ALIVE_DURATION_MINUTES,
TimeUnit.MINUTES,
)
private val loggingInterceptor: Interceptor by lazy {
HttpLoggingInterceptor().apply {
// BODY logging can dump multi-MB b64_json; keep headers in debug builds.
level = HttpLoggingInterceptor.Level.HEADERS
}
}
/**
* Regular chat / models client.
* Long enough for SSE streams, shorter than image generation waits.
*/
fun createChatOkHttpClient(apiKey: String): OkHttpClient {
return baseClientBuilder(apiKey)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(180, TimeUnit.SECONDS)
.callTimeout(210, TimeUnit.SECONDS)
.build()
}
/**
* Dedicated image generation / edits client (PRD §重型图像防超时).
*/
fun createImageOkHttpClient(apiKey: String): OkHttpClient {
return baseClientBuilder(apiKey)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS)
.callTimeout(360, TimeUnit.SECONDS)
.build()
}
fun createChatRetrofit(baseUrl: String, apiKey: String): Retrofit {
return Retrofit.Builder()
.baseUrl(normalizeBaseUrl(baseUrl))
.client(createChatOkHttpClient(apiKey))
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
}
fun createImageRetrofit(baseUrl: String, apiKey: String): Retrofit {
return Retrofit.Builder()
.baseUrl(normalizeBaseUrl(baseUrl))
.client(createImageOkHttpClient(apiKey))
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
}
fun createOpenAiApi(baseUrl: String, apiKey: String, forImage: Boolean = false): OpenAiApi {
val retrofit = if (forImage) {
createImageRetrofit(baseUrl, apiKey)
} else {
createChatRetrofit(baseUrl, apiKey)
}
return retrofit.create(OpenAiApi::class.java)
}
fun createChatCompletionsSseClient(baseUrl: String, apiKey: String): ChatCompletionsSseClient {
return ChatCompletionsSseClient(
baseUrl = normalizeBaseUrl(baseUrl),
okHttpClient = createChatOkHttpClient(apiKey),
json = json,
)
}
/** Ensures trailing slash and optional `/v1` segment for OpenAI-compatible gateways. */
fun normalizeBaseUrl(raw: String): String {
var url = raw.trim()
if (url.isEmpty()) error("Base URL must not be empty")
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "https://$url"
}
url = url.trimEnd('/')
if (!url.endsWith("/v1")) {
url = "$url/v1"
}
return "$url/"
}
private fun baseClientBuilder(apiKey: String): OkHttpClient.Builder {
return OkHttpClient.Builder()
.connectionPool(sharedConnectionPool)
.retryOnConnectionFailure(true)
.addInterceptor(AuthInterceptor(apiKey))
.addInterceptor(loggingInterceptor)
}
}
class AuthInterceptor(
private val apiKey: String,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
val original = chain.request()
val builder = original.newBuilder()
.header("Authorization", "Bearer $apiKey")
// Do not overwrite Accept — SSE needs text/event-stream.
if (original.header("Accept").isNullOrBlank()) {
builder.header("Accept", "application/json")
}
if (original.header("User-Agent").isNullOrBlank()) {
builder.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android 15) OmniChat/0.1 AppleWebKit/537.36 CherryCompat",
)
}
return chain.proceed(builder.build())
}
}
@@ -0,0 +1,77 @@
package com.omnichat.app.data.remote.api
import com.omnichat.app.data.remote.dto.ChatCompletionRequest
import com.omnichat.app.data.remote.dto.ChatCompletionResponse
import com.omnichat.app.data.remote.dto.ImageEditJsonRequest
import com.omnichat.app.data.remote.dto.ImageGenerationRequest
import com.omnichat.app.data.remote.dto.ImageResponse
import com.omnichat.app.data.remote.dto.ModelsListResponse
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
/**
* OpenAI-compatible REST surface used by OmniChat.
*
* Streaming chat completions are handled by [com.omnichat.app.data.remote.sse.ChatCompletionsSseClient]
* (OkHttp SSE + Flow) rather than Retrofit, because okhttp-sse needs the raw EventSource API.
*/
interface OpenAiApi {
@GET("models")
suspend fun listModels(): ModelsListResponse
/** Non-streaming chat completion (multimodal Path B when stream=false). */
@POST("chat/completions")
suspend fun createChatCompletion(
@Body request: ChatCompletionRequest,
): ChatCompletionResponse
/** Text-to-image: POST /v1/images/generations */
@POST("images/generations")
suspend fun createImageGeneration(
@Body request: ImageGenerationRequest,
): ImageResponse
/**
* Image-to-image / edits with binary upload: POST /v1/images/edits
* Prefer this path for high-fidelity reference image features (Cherry Studio style).
*/
@Multipart
@POST("images/edits")
suspend fun createImageEdit(
@Part image: MultipartBody.Part,
@Part("prompt") prompt: RequestBody,
@Part("model") model: RequestBody?,
@Part("n") n: RequestBody?,
@Part("size") size: RequestBody?,
@Part("response_format") responseFormat: RequestBody?,
): ImageResponse
/**
* Multipart edits with multiple reference images (some gateways accept repeated `image` parts).
*/
@Multipart
@POST("images/edits")
suspend fun createImageEditMulti(
@Part images: List<MultipartBody.Part>,
@Part("prompt") prompt: RequestBody,
@Part("model") model: RequestBody?,
@Part("n") n: RequestBody?,
@Part("size") size: RequestBody?,
@Part("response_format") responseFormat: RequestBody?,
): ImageResponse
/**
* JSON image edits for relay stations that expect
* `images: [{ image_url: { url } }]` instead of multipart binary.
*/
@POST("images/edits")
suspend fun createImageEditJson(
@Body request: ImageEditJsonRequest,
): ImageResponse
}
@@ -0,0 +1,55 @@
package com.omnichat.app.data.remote.chat
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.remote.dto.ChatMessageDto
import com.omnichat.app.domain.model.ChatMessage
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import java.io.File
object ChatMessageFactory {
fun textMessage(role: String, text: String): ChatMessageDto =
ChatMessageDto(role = role, content = JsonPrimitive(text))
fun multimodalUserMessage(
text: String,
imageFiles: List<File>,
compressor: ImageCompressor,
): ChatMessageDto {
val content = buildJsonArray {
if (text.isNotBlank()) {
add(
buildJsonObject {
put("type", "text")
put("text", text)
},
)
}
imageFiles.forEach { file ->
add(
buildJsonObject {
put("type", "image_url")
put(
"image_url",
buildJsonObject {
put("url", compressor.toDataUrl(file))
},
)
},
)
}
}
return ChatMessageDto(role = "user", content = content)
}
fun fromHistory(message: ChatMessage, compressor: ImageCompressor): ChatMessageDto {
val files = message.imagePaths.map(::File).filter { it.exists() }
return if (message.role == "user" && files.isNotEmpty()) {
multimodalUserMessage(message.content, files, compressor)
} else {
textMessage(message.role, message.content)
}
}
}
@@ -0,0 +1,262 @@
package com.omnichat.app.data.remote.chat
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.remote.NetworkModule
import com.omnichat.app.data.remote.dto.ChatCompletionResponse
import com.omnichat.app.data.remote.sse.ChatSseException
import com.omnichat.app.data.remote.sse.ChatStreamEvent
import com.omnichat.app.domain.model.ChatMessage
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources
import java.io.File
/**
* Cherry / OpenWebUI compatible chat client using raw OkHttp + explicit JSON.
* Avoids Retrofit/JsonElement edge cases that some relays reject.
*/
class OpenAiChatClient(
private val baseUrl: String,
private val apiKey: String,
private val imageCompressor: ImageCompressor,
) {
private val json = NetworkModule.json
private val client = NetworkModule.createChatOkHttpClient(apiKey)
private val endpoint = NetworkModule.normalizeBaseUrl(baseUrl).trimEnd('/') + "/chat/completions"
fun buildMessagesPayload(
history: List<ChatMessage>,
systemPrompt: String? = null,
): JsonArray = buildJsonArray {
systemPrompt?.takeIf { it.isNotBlank() }?.let { sys ->
add(
buildJsonObject {
put("role", "system")
put("content", sys)
},
)
}
history.forEach { msg ->
add(messageToJson(msg))
}
}
private fun messageToJson(message: ChatMessage): JsonObject {
val files = message.imagePaths.map(::File).filter { it.exists() }
return if (message.role == "user" && files.isNotEmpty()) {
buildJsonObject {
put("role", "user")
put(
"content",
buildJsonArray {
if (message.content.isNotBlank()) {
add(
buildJsonObject {
put("type", "text")
put("text", message.content)
},
)
}
files.forEach { file ->
add(
buildJsonObject {
put("type", "image_url")
put(
"image_url",
buildJsonObject {
put("url", imageCompressor.toDataUrl(file))
},
)
},
)
}
},
)
}
} else {
buildJsonObject {
put("role", message.role)
put("content", message.content)
}
}
}
fun buildRequestBody(
model: String,
messages: JsonArray,
stream: Boolean,
): String = buildJsonObject {
put("model", model)
put("messages", messages)
put("stream", stream)
}.toString()
/**
* Non-stream chat completion — same shape Cherry Studio uses for non-stream calls.
*/
fun chatOnce(model: String, messages: JsonArray): ChatOnceResult {
val body = buildRequestBody(model, messages, stream = false)
val request = Request.Builder()
.url(endpoint)
.post(body.toRequestBody("application/json; charset=utf-8".toMediaType()))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("User-Agent", USER_AGENT)
.build()
client.newCall(request).execute().use { response ->
val raw = response.body?.string().orEmpty()
if (!response.isSuccessful) {
return ChatOnceResult.Error(
httpCode = response.code,
requestUrl = endpoint,
requestBody = body,
responseBody = raw,
)
}
val parsed = runCatching {
json.decodeFromString(ChatCompletionResponse.serializer(), raw)
}.getOrElse {
return ChatOnceResult.Error(
httpCode = response.code,
requestUrl = endpoint,
requestBody = body,
responseBody = raw,
message = "响应 JSON 解析失败: ${it.message}",
)
}
val msg = parsed.choices.firstOrNull()?.message
val contentElement = msg?.content
val text = when (contentElement) {
is JsonPrimitive -> contentElement.contentOrNull.orEmpty()
is JsonArray -> contentElement.joinToString("\n") { el ->
el.jsonObject["text"]?.jsonPrimitive?.contentOrNull.orEmpty()
}
is JsonObject -> contentElement.toString()
null -> ""
else -> contentElement.toString()
}
return ChatOnceResult.Success(
content = text,
reasoning = msg?.reasoningContent,
requestUrl = endpoint,
requestBody = body,
responseBody = raw,
)
}
}
fun streamChat(model: String, messages: JsonArray): Flow<ChatStreamEvent> = callbackFlow {
val body = buildRequestBody(model, messages, stream = true)
val request = Request.Builder()
.url(endpoint)
.post(body.toRequestBody("application/json; charset=utf-8".toMediaType()))
.header("Content-Type", "application/json")
.header("Accept", "text/event-stream")
.header("Cache-Control", "no-cache")
.header("User-Agent", USER_AGENT)
.build()
val factory = EventSources.createFactory(client)
val listener = object : EventSourceListener() {
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String,
) {
val trimmed = data.trim()
if (trimmed.isEmpty()) return
if (trimmed == "[DONE]") {
trySend(ChatStreamEvent.Done)
close()
return
}
runCatching {
val obj = json.parseToJsonElement(trimmed).jsonObject
val choice = obj["choices"]?.jsonArray?.firstOrNull()?.jsonObject
val delta = choice?.get("delta")?.jsonObject
val content = delta?.get("content")?.jsonPrimitive?.contentOrNull
val reasoning = delta?.get("reasoning_content")?.jsonPrimitive?.contentOrNull
if (!content.isNullOrEmpty() || !reasoning.isNullOrEmpty()) {
trySend(
ChatStreamEvent.Delta(
content = content.orEmpty(),
reasoningContent = reasoning,
),
)
}
}
}
override fun onFailure(
eventSource: EventSource,
t: Throwable?,
response: okhttp3.Response?,
) {
val snippet = runCatching { response?.body?.string()?.take(400) }.getOrNull()
val err = ChatSseException(
message = buildString {
append("SSE failed: HTTP ${response?.code ?: "?"}")
if (!snippet.isNullOrBlank()) {
append(" — ")
append(snippet.replace('\n', ' '))
}
t?.message?.let { append(" ($it)") }
},
httpCode = response?.code,
cause = t,
)
trySend(ChatStreamEvent.Error(err))
close(err)
}
override fun onClosed(eventSource: EventSource) {
trySend(ChatStreamEvent.Done)
close()
}
}
val es = factory.newEventSource(request, listener)
awaitClose { es.cancel() }
}
sealed class ChatOnceResult {
data class Success(
val content: String,
val reasoning: String?,
val requestUrl: String,
val requestBody: String,
val responseBody: String,
) : ChatOnceResult()
data class Error(
val httpCode: Int,
val requestUrl: String,
val requestBody: String,
val responseBody: String,
val message: String? = null,
) : ChatOnceResult()
}
companion object {
// Closer to desktop clients; some gateways fingerprint bare okhttp UA.
const val USER_AGENT =
"Mozilla/5.0 (Linux; Android 15) OmniChat/0.1 AppleWebKit/537.36 CherryCompat"
}
}
@@ -0,0 +1,64 @@
package com.omnichat.app.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
@Serializable
data class ChatCompletionRequest(
val model: String,
val messages: List<ChatMessageDto>,
val stream: Boolean = false,
val temperature: Double? = null,
@SerialName("max_tokens") val maxTokens: Int? = null,
)
/**
* Content may be a plain string or a multimodal array (text + image_url parts).
* Represented as [JsonElement] so both shapes serialize correctly.
*/
@Serializable
data class ChatMessageDto(
val role: String,
val content: JsonElement,
@SerialName("reasoning_content") val reasoningContent: String? = null,
)
@Serializable
data class ChatContentPart(
val type: String,
val text: String? = null,
@SerialName("image_url") val imageUrl: ImageUrlPart? = null,
)
@Serializable
data class ImageUrlPart(
val url: String,
)
@Serializable
data class ChatCompletionResponse(
val id: String? = null,
val choices: List<ChatChoice> = emptyList(),
)
@Serializable
data class ChatChoice(
val index: Int = 0,
val message: ChatMessageDto? = null,
val delta: ChatDelta? = null,
@SerialName("finish_reason") val finishReason: String? = null,
)
@Serializable
data class ChatDelta(
val role: String? = null,
val content: String? = null,
@SerialName("reasoning_content") val reasoningContent: String? = null,
)
@Serializable
data class ChatCompletionChunk(
val id: String? = null,
val choices: List<ChatChoice> = emptyList(),
)
@@ -0,0 +1,47 @@
package com.omnichat.app.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ImageGenerationRequest(
val model: String? = null,
val prompt: String,
val n: Int = 1,
val size: String? = null,
@SerialName("response_format") val responseFormat: String? = "b64_json",
val quality: String? = null,
)
/**
* JSON variant of image edits used by some relay gateways
* (`images: [{ image_url: { url: "data:..." } }]`). Multipart binary upload
* is preferred via [com.omnichat.app.data.remote.api.OpenAiApi.createImageEdit].
*/
@Serializable
data class ImageEditJsonRequest(
val model: String? = null,
val prompt: String,
val n: Int = 1,
val size: String? = null,
@SerialName("response_format") val responseFormat: String? = "b64_json",
val images: List<ImageEditImageRef> = emptyList(),
)
@Serializable
data class ImageEditImageRef(
@SerialName("image_url") val imageUrl: ImageUrlPart,
)
@Serializable
data class ImageResponse(
val created: Long? = null,
val data: List<ImageData> = emptyList(),
)
@Serializable
data class ImageData(
val url: String? = null,
@SerialName("b64_json") val b64Json: String? = null,
@SerialName("revised_prompt") val revisedPrompt: String? = null,
)
@@ -0,0 +1,16 @@
package com.omnichat.app.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ModelsListResponse(
val data: List<ModelObject> = emptyList(),
)
@Serializable
data class ModelObject(
val id: String,
val created: Long? = null,
@SerialName("owned_by") val ownedBy: String? = null,
)
@@ -0,0 +1,62 @@
package com.omnichat.app.data.remote.image
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
/**
* Extracts image URLs / data-URIs / bare base64 blobs from chat completion content.
*/
object ChatImageResponseParser {
private val markdownImage = Regex("""!\[[^\]]*]\(([^)]+)\)""")
private val dataUri = Regex("""data:image\/[a-zA-Z0-9+.-]+;base64,[A-Za-z0-9+/=\s]+""")
private val bareHttp = Regex("""https?://\S+\.(?:png|jpe?g|webp)(?:\?\S*)?""", RegexOption.IGNORE_CASE)
fun extractImageRefs(content: JsonElement?): List<String> {
if (content == null) return emptyList()
val text = flattenContent(content)
return extractFromText(text)
}
fun extractFromText(text: String): List<String> {
if (text.isBlank()) return emptyList()
val found = linkedSetOf<String>()
markdownImage.findAll(text).forEach { found += it.groupValues[1].trim() }
dataUri.findAll(text).forEach { found += it.value.replace("\\s".toRegex(), "") }
bareHttp.findAll(text).forEach { found += it.value.trim().trimEnd(')', ',', '"', '\'') }
// Some gateways return only a huge base64 blob
val compact = text.trim()
if (found.isEmpty() && compact.length > 256 && compact.matches(Regex("^[A-Za-z0-9+/=\r\n]+$"))) {
found += compact.replace("\n", "").replace("\r", "")
}
return found.toList()
}
private fun flattenContent(content: JsonElement): String = when (content) {
is JsonPrimitive -> content.contentOrNull.orEmpty()
is JsonArray -> content.joinToString("\n") { element ->
when (element) {
is JsonObject -> {
val type = (element["type"] as? JsonPrimitive)?.contentOrNull
when (type) {
"text" -> (element["text"] as? JsonPrimitive)?.contentOrNull.orEmpty()
"image_url" -> {
val imageUrl = element["image_url"]
when (imageUrl) {
is JsonPrimitive -> imageUrl.contentOrNull.orEmpty()
is JsonObject -> (imageUrl["url"] as? JsonPrimitive)?.contentOrNull.orEmpty()
else -> ""
}
}
else -> element.toString()
}
}
else -> flattenContent(element)
}
}
is JsonObject -> content.toString()
else -> content.toString()
}
}
@@ -0,0 +1,37 @@
package com.omnichat.app.data.remote.multipart
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
/**
* Helpers for building multipart bodies for POST /v1/images/edits.
*/
object ImageEditParts {
private val plainText = "text/plain".toMediaType()
fun textPart(value: String): RequestBody = value.toRequestBody(plainText)
fun imagePart(
file: File,
mediaType: String = "image/png",
formName: String = "image",
fileName: String = file.name,
): MultipartBody.Part {
val body = file.asRequestBody(mediaType.toMediaType())
return MultipartBody.Part.createFormData(formName, fileName, body)
}
fun imagePartFromBytes(
bytes: ByteArray,
fileName: String,
mediaType: String = "image/png",
formName: String = "image",
): MultipartBody.Part {
val body = bytes.toRequestBody(mediaType.toMediaType())
return MultipartBody.Part.createFormData(formName, fileName, body)
}
}
@@ -0,0 +1,129 @@
package com.omnichat.app.data.remote.sse
import com.omnichat.app.data.remote.dto.ChatCompletionChunk
import com.omnichat.app.data.remote.dto.ChatCompletionRequest
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources
/**
* Streams POST /v1/chat/completions with `stream=true` via OkHttp SSE → Kotlin Flow.
*/
class ChatCompletionsSseClient(
private val baseUrl: String,
private val okHttpClient: OkHttpClient,
private val json: Json,
) {
fun streamChatCompletions(request: ChatCompletionRequest): Flow<ChatStreamEvent> = callbackFlow {
val bodyJson = json.encodeToString(
ChatCompletionRequest.serializer(),
request.copy(stream = true),
)
val httpRequest = Request.Builder()
.url(baseUrl.trimEnd('/') + "/chat/completions")
.post(bodyJson.toRequestBody("application/json".toMediaType()))
.header("Accept", "text/event-stream")
.header("Cache-Control", "no-cache")
.build()
val factory = EventSources.createFactory(okHttpClient)
val listener = object : EventSourceListener() {
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String,
) {
val trimmed = data.trim()
if (trimmed.isEmpty()) return
if (trimmed == "[DONE]") {
trySend(ChatStreamEvent.Done)
close()
return
}
try {
val chunk = json.decodeFromString(ChatCompletionChunk.serializer(), trimmed)
val delta = chunk.choices.firstOrNull()?.delta
val content = delta?.content
val reasoning = delta?.reasoningContent
if (!content.isNullOrEmpty() || !reasoning.isNullOrEmpty()) {
trySend(
ChatStreamEvent.Delta(
content = content.orEmpty(),
reasoningContent = reasoning,
),
)
}
} catch (e: Exception) {
// Some gateways wrap payload; ignore unparsable keep-alive lines.
if (trimmed.startsWith("{")) {
trySend(ChatStreamEvent.Error(e))
}
}
}
override fun onFailure(
eventSource: EventSource,
t: Throwable?,
response: Response?,
) {
val bodySnippet = runCatching {
response?.body?.string()?.take(400)
}.getOrNull()
val detail = buildString {
append("SSE failed: HTTP ${response?.code ?: "?"} ${response?.message.orEmpty()}".trim())
if (!bodySnippet.isNullOrBlank()) {
append(" — ")
append(bodySnippet.replace('\n', ' '))
}
if (t != null && t.message != null) {
append(" (")
append(t.message)
append(')')
}
}
val error = ChatSseException(
message = detail,
httpCode = response?.code,
cause = t,
)
trySend(ChatStreamEvent.Error(error))
close(error)
}
override fun onClosed(eventSource: EventSource) {
trySend(ChatStreamEvent.Done)
close()
}
}
val eventSource = factory.newEventSource(httpRequest, listener)
awaitClose { eventSource.cancel() }
}
}
class ChatSseException(
message: String,
val httpCode: Int? = null,
cause: Throwable? = null,
) : IllegalStateException(message, cause)
sealed interface ChatStreamEvent {
data class Delta(
val content: String,
val reasoningContent: String? = null,
) : ChatStreamEvent
data object Done : ChatStreamEvent
data class Error(val throwable: Throwable) : ChatStreamEvent
}
@@ -0,0 +1,132 @@
package com.omnichat.app.data.repository
import com.omnichat.app.data.local.db.dao.ConversationDao
import com.omnichat.app.data.local.db.dao.MessageDao
import com.omnichat.app.data.local.db.entity.ConversationEntity
import com.omnichat.app.data.local.db.entity.MessageEntity
import com.omnichat.app.domain.model.ChatMessage
import com.omnichat.app.domain.model.Conversation
import com.omnichat.app.domain.model.MessageStatus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
class ChatRepository(
private val conversationDao: ConversationDao,
private val messageDao: MessageDao,
) {
val conversations: Flow<List<Conversation>> =
conversationDao.observeAll().map { list -> list.map { it.toDomain() } }
fun observeMessages(conversationId: Long): Flow<List<ChatMessage>> =
messageDao.observeByConversation(conversationId).map { list -> list.map { it.toDomain() } }
suspend fun getConversation(id: Long): Conversation? = withContext(Dispatchers.IO) {
conversationDao.getById(id)?.toDomain()
}
suspend fun createConversation(
title: String = "新对话",
providerId: Long?,
modelId: String?,
systemPrompt: String? = null,
): Long = withContext(Dispatchers.IO) {
conversationDao.upsert(
ConversationEntity(
title = title,
modelId = modelId,
providerId = providerId,
systemPrompt = systemPrompt,
updatedAt = System.currentTimeMillis(),
),
)
}
suspend fun renameConversation(id: Long, title: String) = withContext(Dispatchers.IO) {
val existing = conversationDao.getById(id) ?: return@withContext
conversationDao.update(existing.copy(title = title, updatedAt = System.currentTimeMillis()))
}
suspend fun touchConversation(id: Long) = withContext(Dispatchers.IO) {
val existing = conversationDao.getById(id) ?: return@withContext
conversationDao.update(existing.copy(updatedAt = System.currentTimeMillis()))
}
suspend fun updateConversationModel(
id: Long,
providerId: Long?,
modelId: String?,
) = withContext(Dispatchers.IO) {
val existing = conversationDao.getById(id) ?: return@withContext
conversationDao.update(
existing.copy(
providerId = providerId,
modelId = modelId,
updatedAt = System.currentTimeMillis(),
),
)
}
suspend fun deleteConversation(id: Long) = withContext(Dispatchers.IO) {
messageDao.deleteByConversation(id)
conversationDao.deleteById(id)
}
suspend fun insertMessage(message: ChatMessage): Long = withContext(Dispatchers.IO) {
messageDao.upsert(message.toEntity())
}
suspend fun updateMessage(message: ChatMessage) = withContext(Dispatchers.IO) {
messageDao.update(message.toEntity())
}
suspend fun getMessages(conversationId: Long): List<ChatMessage> = withContext(Dispatchers.IO) {
messageDao.getByConversation(conversationId).map { it.toDomain() }
}
suspend fun getMessage(id: Long): ChatMessage? = withContext(Dispatchers.IO) {
messageDao.getById(id)?.toDomain()
}
suspend fun deleteMessage(id: Long) = withContext(Dispatchers.IO) {
messageDao.deleteById(id)
}
suspend fun deleteMessagesFrom(conversationId: Long, fromId: Long) = withContext(Dispatchers.IO) {
messageDao.deleteFromId(conversationId, fromId)
}
private fun ConversationEntity.toDomain() = Conversation(
id = id,
title = title,
modelId = modelId,
providerId = providerId,
systemPrompt = systemPrompt,
updatedAt = updatedAt,
)
private fun MessageEntity.toDomain() = ChatMessage(
id = id,
conversationId = conversationId,
role = role,
content = content,
reasoningContent = reasoningContent,
imagePaths = imagePaths,
status = status,
errorMessage = errorMessage,
timestamp = timestamp,
)
private fun ChatMessage.toEntity() = MessageEntity(
id = id,
conversationId = conversationId,
role = role,
content = content,
reasoningContent = reasoningContent,
imagePaths = imagePaths,
status = status,
errorMessage = errorMessage,
timestamp = timestamp,
)
}
@@ -0,0 +1,281 @@
package com.omnichat.app.data.repository
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.remote.chat.OpenAiChatClient
import com.omnichat.app.data.remote.sse.ChatStreamEvent
import com.omnichat.app.domain.chat.ThinkParser
import com.omnichat.app.domain.model.ChatMessage
import com.omnichat.app.domain.model.MessageStatus
import com.omnichat.app.domain.model.isImagesApiOnlyModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.withContext
class ChatStreamingInteractor(
private val chatRepository: ChatRepository,
private val providerRepository: ProviderRepository,
private val imageCompressor: ImageCompressor,
) {
suspend fun streamAssistantReply(
conversationId: Long,
providerId: Long,
modelId: String,
contextWindowRounds: Int,
assistantMessageId: Long,
onPartial: (content: String, reasoning: String?) -> Unit = { _, _ -> },
) = withContext(Dispatchers.IO) {
if (isImagesApiOnlyModel(modelId)) {
val msg =
"模型「$modelId」是纯生图模型,不能用于对话。请到设置把「默认对话」改成聊天模型。"
persistAssistant(
assistantMessageId, conversationId, "", null, MessageStatus.ERROR, msg,
)
error(msg)
}
val provider = providerRepository.getProvider(providerId)
?: error("服务商不存在,请先在设置中配置")
if (!provider.isEnabled) error("服务商已禁用")
val apiKey = providerRepository.getDecryptedApiKey(providerId)
if (apiKey.isBlank()) error("API Key 为空")
val conversation = chatRepository.getConversation(conversationId)
?: error("会话不存在")
val history = chatRepository.getMessages(conversationId)
.filter { it.id != assistantMessageId }
.filter {
it.status == MessageStatus.SUCCESS || it.role == "user" || it.role == "system"
}
val capped = takeContextWindow(history, contextWindowRounds)
val client = OpenAiChatClient(provider.baseUrl, apiKey, imageCompressor)
val messages = client.buildMessagesPayload(capped, conversation.systemPrompt)
val contentBuf = StringBuilder()
val reasoningBuf = StringBuilder()
try {
onPartial("正在请求 $modelId …", null)
// Match Cherry/OpenWebUI: try stream first, then non-stream.
var usedStream = false
val streamError = runCatching {
var lastPersist = 0L
client.streamChat(modelId, messages).collect { event ->
when (event) {
is ChatStreamEvent.Delta -> {
usedStream = true
if (event.content.isNotEmpty()) contentBuf.append(event.content)
if (!event.reasoningContent.isNullOrEmpty()) {
reasoningBuf.append(event.reasoningContent)
}
val parsed = ThinkParser.parse(
contentBuf.toString(),
reasoningBuf.toString().ifBlank { null },
)
onPartial(parsed.visibleMarkdown, parsed.thinkBlocks)
val now = System.currentTimeMillis()
if (now - lastPersist > 400) {
lastPersist = now
persistAssistant(
assistantMessageId,
conversationId,
contentBuf.toString(),
reasoningBuf.toString().ifBlank { null },
MessageStatus.STREAMING,
null,
)
}
}
ChatStreamEvent.Done -> Unit
is ChatStreamEvent.Error -> throw event.throwable
}
}
}.exceptionOrNull()
if (streamError != null || (!usedStream && contentBuf.isEmpty())) {
contentBuf.clear()
reasoningBuf.clear()
onPartial("流式不可用,改用非流式…", null)
var lastFail: OpenAiChatClient.ChatOnceResult.Error? = null
repeat(2) { attempt ->
if (attempt > 0) delay(600)
when (val once = client.chatOnce(modelId, messages)) {
is OpenAiChatClient.ChatOnceResult.Success -> {
contentBuf.append(once.content)
once.reasoning?.let { reasoningBuf.append(it) }
val parsed = ThinkParser.parse(
contentBuf.toString(),
reasoningBuf.toString().ifBlank { null },
)
onPartial(parsed.visibleMarkdown, parsed.thinkBlocks)
lastFail = null
return@repeat
}
is OpenAiChatClient.ChatOnceResult.Error -> {
lastFail = once
}
}
}
lastFail?.let { err ->
error(formatChatFailure(modelId, err, streamError))
}
if (contentBuf.isEmpty() && reasoningBuf.isEmpty()) {
error(
formatChatFailure(
modelId,
OpenAiChatClient.ChatOnceResult.Error(
httpCode = -1,
requestUrl = "",
requestBody = client.buildRequestBody(modelId, messages, false),
responseBody = "",
message = "空响应",
),
streamError,
),
)
}
}
val raw = contentBuf.toString()
val streamedReasoning = reasoningBuf.toString().ifBlank { null }
val parsed = ThinkParser.parse(raw, streamedReasoning)
persistAssistant(
assistantMessageId,
conversationId,
raw.ifBlank { parsed.visibleMarkdown },
parsed.thinkBlocks,
MessageStatus.SUCCESS,
null,
)
onPartial(parsed.visibleMarkdown, parsed.thinkBlocks)
chatRepository.touchConversation(conversationId)
maybeAutoTitle(conversationId, capped)
} catch (e: Exception) {
persistAssistant(
assistantMessageId,
conversationId,
contentBuf.toString(),
reasoningBuf.toString().ifBlank { null },
MessageStatus.ERROR,
e.message ?: "对话请求失败",
)
throw e
}
}
/**
* Settings diagnostic — same request shape as real chat.
*/
suspend fun probeChat(
providerId: Long,
modelId: String,
prompt: String = "你好",
): String = withContext(Dispatchers.IO) {
val provider = providerRepository.getProvider(providerId)
?: return@withContext "服务商不存在"
val apiKey = providerRepository.getDecryptedApiKey(providerId)
val client = OpenAiChatClient(provider.baseUrl, apiKey, imageCompressor)
val messages = client.buildMessagesPayload(
listOf(
ChatMessage(
conversationId = 0,
role = "user",
content = prompt,
),
),
)
val body = client.buildRequestBody(modelId, messages, stream = false)
when (val result = client.chatOnce(modelId, messages)) {
is OpenAiChatClient.ChatOnceResult.Success -> buildString {
appendLine("✅ 对话接口可用")
appendLine("URL: ${result.requestUrl}")
appendLine("Model: $modelId")
appendLine("Request: $body")
appendLine("Reply: ${result.content.take(300)}")
}
is OpenAiChatClient.ChatOnceResult.Error -> buildString {
appendLine("❌ 对话接口失败 HTTP ${result.httpCode}")
appendLine("URL: ${result.requestUrl}")
appendLine("Model: $modelId")
appendLine("Request: ${result.requestBody}")
appendLine("Response: ${result.responseBody.take(500)}")
result.message?.let { appendLine("Note: $it") }
appendLine()
appendLine("请把以上内容与 Cherry Studio 里同模型的成功请求对比。")
}
}
}
private fun formatChatFailure(
modelId: String,
err: OpenAiChatClient.ChatOnceResult.Error,
streamError: Throwable?,
): String = buildString {
append("对话失败 · 模型 $modelId")
if (err.httpCode > 0) append(" · HTTP ${err.httpCode}")
appendLine()
when (err.httpCode) {
502, 503, 504 -> appendLine(
"中转站返回暂时不可用。若 Cherry/OpenWebUI 同模型可用,请点设置里「测试对话」对比 Request。",
)
}
if (err.responseBody.isNotBlank()) {
appendLine(err.responseBody.take(300).replace('\n', ' '))
} else {
err.message?.let { appendLine(it) }
}
streamError?.message?.let {
appendLine("流式:${it.take(160)}")
}
if (err.requestBody.isNotBlank()) {
appendLine("Request: ${err.requestBody.take(220)}")
}
}
private suspend fun persistAssistant(
id: Long,
conversationId: Long,
rawContent: String,
reasoning: String?,
status: MessageStatus,
error: String?,
) {
val parsed = ThinkParser.parse(rawContent, reasoning)
val existing = chatRepository.getMessage(id)
chatRepository.updateMessage(
ChatMessage(
id = id,
conversationId = conversationId,
role = "assistant",
content = if (status == MessageStatus.SUCCESS) {
parsed.visibleMarkdown.ifBlank { rawContent }
} else {
rawContent
},
reasoningContent = parsed.thinkBlocks,
status = status,
errorMessage = error,
timestamp = existing?.timestamp ?: System.currentTimeMillis(),
),
)
}
private fun takeContextWindow(history: List<ChatMessage>, rounds: Int): List<ChatMessage> {
val maxMessages = (rounds * 2).coerceAtLeast(2)
if (history.size <= maxMessages) return history
return history.takeLast(maxMessages)
}
private suspend fun maybeAutoTitle(conversationId: Long, history: List<ChatMessage>) {
val conversation = chatRepository.getConversation(conversationId) ?: return
if (conversation.title != "新对话") return
val firstUser = history.firstOrNull { it.role == "user" }?.content?.trim().orEmpty()
if (firstUser.isBlank()) return
chatRepository.renameConversation(
conversationId,
firstUser.lineSequence().first().take(24),
)
}
}
@@ -0,0 +1,207 @@
package com.omnichat.app.data.repository
import com.omnichat.app.data.local.db.dao.ModelDao
import com.omnichat.app.data.local.db.dao.ProviderDao
import com.omnichat.app.data.local.db.entity.ModelEntity
import com.omnichat.app.data.local.db.entity.ProviderEntity
import com.omnichat.app.data.local.security.ApiKeyCipher
import com.omnichat.app.data.remote.NetworkModule
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ModelCapability
import com.omnichat.app.domain.model.Provider
import com.omnichat.app.domain.model.ProviderDraft
import com.omnichat.app.domain.model.guessCapabilities
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
class ProviderRepository(
private val providerDao: ProviderDao,
private val modelDao: ModelDao,
private val apiKeyCipher: ApiKeyCipher,
) {
val providers: Flow<List<Provider>> = providerDao.observeAll().map { list ->
list.map { it.toDomain() }
}
val models: Flow<List<AiModel>> = modelDao.observeAll().map { list ->
list.map { it.toDomain() }
}
fun observeModels(providerId: Long): Flow<List<AiModel>> =
modelDao.observeByProvider(providerId).map { list -> list.map { it.toDomain() } }
fun observeProvidersWithModels(): Flow<List<Pair<Provider, List<AiModel>>>> =
combine(providers, models) { providerList, modelList ->
providerList.map { provider ->
provider to modelList.filter { it.providerId == provider.id }
}
}
suspend fun getDecryptedApiKey(providerId: Long): String = withContext(Dispatchers.IO) {
val entity = providerDao.getById(providerId) ?: return@withContext ""
apiKeyCipher.decrypt(entity.apiKeyEncrypted)
}
suspend fun getProvider(providerId: Long): Provider? = withContext(Dispatchers.IO) {
providerDao.getById(providerId)?.toDomain()
}
suspend fun getModel(modelRowId: Long): AiModel? = withContext(Dispatchers.IO) {
modelDao.getById(modelRowId)?.toDomain()
}
suspend fun findModel(providerId: Long, modelId: String): AiModel? = withContext(Dispatchers.IO) {
modelDao.getByProviderAndModelId(providerId, modelId)?.toDomain()
}
suspend fun saveProvider(draft: ProviderDraft): Long = withContext(Dispatchers.IO) {
require(draft.name.isNotBlank()) { "名称不能为空" }
require(draft.baseUrl.isNotBlank()) { "Base URL 不能为空" }
val normalized = NetworkModule.normalizeBaseUrl(draft.baseUrl)
if (draft.id == null) {
require(draft.apiKey.isNotBlank()) { "API Key 不能为空" }
val token = apiKeyCipher.encrypt(draft.apiKey.trim())
return@withContext providerDao.upsert(
ProviderEntity(
name = draft.name.trim(),
baseUrl = normalized,
apiKeyEncrypted = token,
isEnabled = draft.isEnabled,
),
)
}
val existing = providerDao.getById(draft.id)
?: error("服务商不存在")
val token = if (draft.apiKey.isNotBlank()) {
apiKeyCipher.rotate(existing.apiKeyEncrypted, draft.apiKey.trim())
} else {
existing.apiKeyEncrypted
}
providerDao.update(
existing.copy(
name = draft.name.trim(),
baseUrl = normalized,
apiKeyEncrypted = token,
isEnabled = draft.isEnabled,
),
)
draft.id
}
suspend fun deleteProvider(providerId: Long) = withContext(Dispatchers.IO) {
val existing = providerDao.getById(providerId) ?: return@withContext
apiKeyCipher.delete(existing.apiKeyEncrypted)
modelDao.deleteByProvider(providerId)
providerDao.deleteById(providerId)
}
suspend fun setProviderEnabled(providerId: Long, enabled: Boolean) = withContext(Dispatchers.IO) {
val existing = providerDao.getById(providerId) ?: return@withContext
providerDao.update(existing.copy(isEnabled = enabled))
}
/**
* Pulls `/v1/models`, preserves manual models and existing capability tags.
*/
suspend fun fetchModels(providerId: Long): Result<Int> = withContext(Dispatchers.IO) {
runCatching {
val provider = providerDao.getById(providerId)
?: error("服务商不存在")
val apiKey = apiKeyCipher.decrypt(provider.apiKeyEncrypted)
if (apiKey.isBlank()) error("API Key 为空")
val api = NetworkModule.createOpenAiApi(provider.baseUrl, apiKey, forImage = false)
val remote = api.listModels().data
val remoteIds = remote.map { it.id.trim() }.filter { it.isNotEmpty() }.toSet()
remote.forEach { remoteModel ->
val modelId = remoteModel.id.trim()
if (modelId.isEmpty()) return@forEach
val previous = modelDao.getByProviderAndModelId(providerId, modelId)
if (previous?.isManual == true) return@forEach
val capabilities = previous?.capabilities?.takeIf { it.isNotEmpty() }
?: guessCapabilities(modelId).toList()
modelDao.upsert(
ModelEntity(
id = previous?.id ?: 0,
providerId = providerId,
modelId = modelId,
displayName = previous?.displayName ?: modelId,
capabilities = capabilities,
isManual = false,
),
)
}
modelDao.getByProvider(providerId)
.filter { !it.isManual && it.modelId !in remoteIds }
.forEach { modelDao.deleteById(it.id) }
remoteIds.size
}
}
suspend fun addManualModel(
providerId: Long,
modelId: String,
displayName: String? = null,
capabilities: Set<ModelCapability> = guessCapabilities(modelId),
): Long = withContext(Dispatchers.IO) {
val id = modelId.trim()
require(id.isNotEmpty()) { "模型 ID 不能为空" }
val existing = modelDao.getByProviderAndModelId(providerId, id)
modelDao.upsert(
ModelEntity(
id = existing?.id ?: 0,
providerId = providerId,
modelId = id,
displayName = displayName?.takeIf { it.isNotBlank() } ?: existing?.displayName ?: id,
capabilities = capabilities.toList().ifEmpty { guessCapabilities(id).toList() },
isManual = true,
),
)
}
suspend fun updateModelCapabilities(modelRowId: Long, capabilities: Set<ModelCapability>) =
withContext(Dispatchers.IO) {
val existing = modelDao.getById(modelRowId) ?: return@withContext
modelDao.update(existing.copy(capabilities = capabilities.toList()))
}
suspend fun deleteModel(modelRowId: Long) = withContext(Dispatchers.IO) {
modelDao.deleteById(modelRowId)
}
private fun ProviderEntity.toDomain(): Provider {
val plain = apiKeyCipher.decrypt(apiKeyEncrypted)
return Provider(
id = id,
name = name,
baseUrl = baseUrl.trimEnd('/'),
apiKeyMasked = maskApiKey(plain),
hasApiKey = plain.isNotBlank(),
isEnabled = isEnabled,
)
}
private fun ModelEntity.toDomain() = AiModel(
id = id,
providerId = providerId,
modelId = modelId,
displayName = displayName,
capabilities = capabilities.toSet(),
isManual = isManual,
)
private fun maskApiKey(key: String): String {
if (key.isBlank()) return "未设置"
if (key.length <= 8) return "••••"
return key.take(3) + "••••" + key.takeLast(4)
}
}
@@ -0,0 +1,7 @@
package com.omnichat.app.data.repository
/**
* Repositories will compose [com.omnichat.app.data.remote.NetworkModule] with Room
* once settings and chat flows are implemented.
*/
object RepositoryPlaceholders
@@ -0,0 +1,31 @@
package com.omnichat.app.data.repository
import com.omnichat.app.data.local.datastore.AppSettingsDataStore
import com.omnichat.app.data.local.datastore.ChatPrefs
import com.omnichat.app.data.local.datastore.DefaultModelRefs
import kotlinx.coroutines.flow.Flow
class SettingsRepository(
private val dataStore: AppSettingsDataStore,
) {
val defaultModels: Flow<DefaultModelRefs> = dataStore.defaults
val chatPrefs: Flow<ChatPrefs> = dataStore.chatPrefs
suspend fun setDefaultChatModel(modelRowId: Long?) =
dataStore.setDefaultChatModel(modelRowId)
suspend fun setDefaultImageGenModel(modelRowId: Long?) =
dataStore.setDefaultImageGenModel(modelRowId)
suspend fun setDefaultImageEditModel(modelRowId: Long?) =
dataStore.setDefaultImageEditModel(modelRowId)
suspend fun setContextWindowRounds(rounds: Int) =
dataStore.setContextWindowRounds(rounds)
suspend fun setSmartCompress(enabled: Boolean) =
dataStore.setSmartCompress(enabled)
suspend fun setLastConversationId(id: Long?) =
dataStore.setLastConversationId(id)
}
@@ -0,0 +1,208 @@
package com.omnichat.app.data.repository
import com.omnichat.app.data.local.media.GeneratedImageStore
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.remote.NetworkModule
import com.omnichat.app.data.remote.chat.ChatMessageFactory
import com.omnichat.app.data.remote.dto.ChatCompletionRequest
import com.omnichat.app.data.remote.dto.ImageData
import com.omnichat.app.data.remote.dto.ImageEditImageRef
import com.omnichat.app.data.remote.dto.ImageEditJsonRequest
import com.omnichat.app.data.remote.dto.ImageGenerationRequest
import com.omnichat.app.data.remote.dto.ImageResponse
import com.omnichat.app.data.remote.dto.ImageUrlPart
import com.omnichat.app.data.remote.image.ChatImageResponseParser
import com.omnichat.app.data.remote.multipart.ImageEditParts
import com.omnichat.app.domain.image.ImageRouteResolver
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.GeneratedImage
import com.omnichat.app.domain.model.ImageGenerateRequest
import com.omnichat.app.domain.model.ImageGenerateResult
import com.omnichat.app.domain.model.ImageRouteKind
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.io.File
/**
* Smart Image Router (PRD §2.2):
* - Path A: dedicated images API (`/generations` or `/edits`)
* - Path B: native multimodal chat completions that emit images
* - Path C callers set [ImageGenerateRequest.forceImageEdit] with reference images
*
* Prompts are never rewritten by a secondary LLM.
*/
class SmartImageRouter(
private val providerRepository: ProviderRepository,
private val settingsRepository: SettingsRepository,
private val imageStore: GeneratedImageStore,
private val imageCompressor: ImageCompressor,
) {
suspend fun generate(request: ImageGenerateRequest): ImageGenerateResult = withContext(Dispatchers.IO) {
require(request.prompt.isNotBlank()) { "提示词不能为空" }
val (providerId, model) = resolveModel(request)
val provider = providerRepository.getProvider(providerId)
?: error("服务商不存在")
val apiKey = providerRepository.getDecryptedApiKey(providerId)
if (apiKey.isBlank()) error("API Key 为空")
val route = when {
request.forceImageEdit -> ImageRouteKind.IMAGES_API
else -> ImageRouteResolver.resolve(model)
}
val files = when (route) {
ImageRouteKind.IMAGES_API -> generateViaImagesApi(
baseUrl = provider.baseUrl,
apiKey = apiKey,
model = model,
prompt = request.prompt,
refs = request.referenceImageFiles,
forceEdit = request.forceImageEdit || request.referenceImageFiles.isNotEmpty(),
size = request.size,
)
ImageRouteKind.CHAT_MULTIMODAL -> generateViaChat(
baseUrl = provider.baseUrl,
apiKey = apiKey,
model = model,
prompt = request.prompt,
refs = request.referenceImageFiles,
)
}
ImageGenerateResult(
images = files.map { file ->
GeneratedImage(
localPath = file.absolutePath,
routeKind = route,
modelId = model.modelId,
)
},
routeKind = route,
modelId = model.modelId,
providerName = provider.name,
)
}
private suspend fun resolveModel(request: ImageGenerateRequest): Pair<Long, AiModel> {
val defaults = settingsRepository.defaultModels.first()
val preferredId = request.preferredModelRowId
?: if (request.referenceImageFiles.isNotEmpty() || request.forceImageEdit) {
defaults.imageEditModelRowId ?: defaults.imageGenModelRowId
} else {
defaults.imageGenModelRowId
}
?: error("请先在设置中指定默认文生图/图生图模型")
val model = providerRepository.getModel(preferredId)
?: error("指定的生图模型不存在")
return model.providerId to model
}
private suspend fun generateViaImagesApi(
baseUrl: String,
apiKey: String,
model: AiModel,
prompt: String,
refs: List<File>,
forceEdit: Boolean,
size: String?,
): List<File> {
val api = NetworkModule.createOpenAiApi(baseUrl, apiKey, forImage = true)
val response: ImageResponse = if (!forceEdit && refs.isEmpty()) {
api.createImageGeneration(
ImageGenerationRequest(
model = model.modelId,
prompt = prompt,
n = 1,
size = size,
responseFormat = "b64_json",
),
)
} else {
require(refs.isNotEmpty()) { "图生图需要至少一张参考图" }
runCatching {
val primary = refs.first()
api.createImageEdit(
image = ImageEditParts.imagePart(primary, mimeFor(primary)),
prompt = ImageEditParts.textPart(prompt),
model = ImageEditParts.textPart(model.modelId),
n = ImageEditParts.textPart("1"),
size = size?.let { ImageEditParts.textPart(it) },
responseFormat = ImageEditParts.textPart("b64_json"),
)
}.recoverCatching {
val images = refs.map { file ->
ImageEditImageRef(imageUrl = ImageUrlPart(url = imageCompressor.toDataUrl(file)))
}
api.createImageEditJson(
ImageEditJsonRequest(
model = model.modelId,
prompt = prompt,
n = 1,
size = size,
responseFormat = "b64_json",
images = images,
),
)
}.getOrThrow()
}
return persistImageResponse(response)
}
private suspend fun generateViaChat(
baseUrl: String,
apiKey: String,
model: AiModel,
prompt: String,
refs: List<File>,
): List<File> {
val api = NetworkModule.createOpenAiApi(baseUrl, apiKey, forImage = true)
val userMessage = if (refs.isEmpty()) {
ChatMessageFactory.textMessage("user", prompt)
} else {
ChatMessageFactory.multimodalUserMessage(prompt, refs, imageCompressor)
}
val response = api.createChatCompletion(
ChatCompletionRequest(
model = model.modelId,
messages = listOf(userMessage),
stream = false,
),
)
val content = response.choices.firstOrNull()?.message?.content
val refsFound = ChatImageResponseParser.extractImageRefs(content)
require(refsFound.isNotEmpty()) {
"多模态模型未返回可解析的图片(Markdown / data URI / URL)"
}
return refsFound.map { ref ->
when {
ref.startsWith("http://", ignoreCase = true) ||
ref.startsWith("https://", ignoreCase = true) ||
ref.startsWith("data:image", ignoreCase = true) -> imageStore.saveFromUrl(ref)
else -> imageStore.saveFromB64Json(ref)
}
}
}
private suspend fun persistImageResponse(response: ImageResponse): List<File> {
require(response.data.isNotEmpty()) { "生图响应为空" }
return response.data.map { item -> persistImageData(item) }
}
private suspend fun persistImageData(item: ImageData): File {
val b64 = item.b64Json
val url = item.url
return when {
!b64.isNullOrBlank() -> imageStore.saveFromB64Json(b64)
!url.isNullOrBlank() -> imageStore.saveFromUrl(url)
else -> error("响应缺少 b64_json 与 url")
}
}
private fun mimeFor(file: File): String = when (file.extension.lowercase()) {
"jpg", "jpeg" -> "image/jpeg"
"webp" -> "image/webp"
else -> "image/png"
}
}
@@ -0,0 +1,51 @@
package com.omnichat.app.di
import android.content.Context
import com.omnichat.app.data.local.datastore.AppSettingsDataStore
import com.omnichat.app.data.local.db.OmniChatDatabase
import com.omnichat.app.data.local.media.GallerySaver
import com.omnichat.app.data.local.media.GeneratedImageStore
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.local.security.ApiKeyCipher
import com.omnichat.app.data.repository.ChatRepository
import com.omnichat.app.data.repository.ChatStreamingInteractor
import com.omnichat.app.data.repository.ProviderRepository
import com.omnichat.app.data.repository.SettingsRepository
import com.omnichat.app.data.repository.SmartImageRouter
class AppContainer(context: Context) {
private val appContext = context.applicationContext
val database: OmniChatDatabase = OmniChatDatabase.create(appContext)
val apiKeyCipher = ApiKeyCipher(appContext)
val settingsDataStore = AppSettingsDataStore(appContext)
val imageCompressor = ImageCompressor(appContext)
val generatedImageStore = GeneratedImageStore(appContext)
val gallerySaver = GallerySaver(appContext)
val providerRepository = ProviderRepository(
providerDao = database.providerDao(),
modelDao = database.modelDao(),
apiKeyCipher = apiKeyCipher,
)
val settingsRepository = SettingsRepository(settingsDataStore)
val chatRepository = ChatRepository(
conversationDao = database.conversationDao(),
messageDao = database.messageDao(),
)
val chatStreamingInteractor = ChatStreamingInteractor(
chatRepository = chatRepository,
providerRepository = providerRepository,
imageCompressor = imageCompressor,
)
val smartImageRouter = SmartImageRouter(
providerRepository = providerRepository,
settingsRepository = settingsRepository,
imageStore = generatedImageStore,
imageCompressor = imageCompressor,
)
}
@@ -0,0 +1,38 @@
package com.omnichat.app.domain.chat
data class ParsedAssistantContent(
val visibleMarkdown: String,
val thinkBlocks: String?,
)
/**
* Splits assistant text into visible markdown and `<think>...</think>` blocks.
* Also handles an unclosed trailing `<think>` while streaming.
*/
object ThinkParser {
private val closedThink = Regex("(?is)<think>(.*?)</think>")
fun parse(raw: String, streamedReasoning: String? = null): ParsedAssistantContent {
val closed = closedThink.findAll(raw).map { it.groupValues[1].trim() }.filter { it.isNotEmpty() }
var remainder = raw.replace(closedThink, "")
var openThink: String? = null
val openIdx = remainder.indexOf("<think>", ignoreCase = true)
if (openIdx >= 0) {
openThink = remainder.substring(openIdx + "<think>".length).trim()
remainder = remainder.substring(0, openIdx)
}
val fromTags = buildList {
addAll(closed)
openThink?.takeIf { it.isNotEmpty() }?.let { add(it) }
}.joinToString("\n\n").ifBlank { null }
val reasoning = listOfNotNull(streamedReasoning?.trim()?.takeIf { it.isNotEmpty() }, fromTags)
.joinToString("\n\n")
.ifBlank { null }
return ParsedAssistantContent(
visibleMarkdown = remainder.trim(),
thinkBlocks = reasoning,
)
}
}
@@ -0,0 +1,35 @@
package com.omnichat.app.domain.image
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ImageRouteKind
import com.omnichat.app.domain.model.ModelCapability
object ImageRouteResolver {
private val imagesApiHints = listOf(
"dall-e", "gpt-image", "flux", "imagen", "stable-diffusion", "sdxl", "midjourney", "mj-",
)
private val chatImageHints = listOf(
"gemini", "gpt-4o-image", "chatgpt-image", "image-preview", "native-image",
)
fun resolve(model: AiModel): ImageRouteKind {
val id = model.modelId.lowercase()
if (chatImageHints.any { id.contains(it) } && id.contains("image")) {
return ImageRouteKind.CHAT_MULTIMODAL
}
if (id.contains("gemini") && (id.contains("image") || id.contains("flash-image"))) {
return ImageRouteKind.CHAT_MULTIMODAL
}
if (imagesApiHints.any { id.contains(it) }) {
return ImageRouteKind.IMAGES_API
}
// Chat-capable image models without classic images-API naming → Path B
if (ModelCapability.CHAT in model.capabilities &&
(ModelCapability.IMAGE_GEN in model.capabilities || ModelCapability.IMAGE_EDIT in model.capabilities) &&
id.contains("image")
) {
return ImageRouteKind.CHAT_MULTIMODAL
}
return ImageRouteKind.IMAGES_API
}
}
@@ -0,0 +1,32 @@
package com.omnichat.app.domain.model
data class Conversation(
val id: Long = 0,
val title: String,
val modelId: String?,
val providerId: Long?,
val systemPrompt: String? = null,
val updatedAt: Long = System.currentTimeMillis(),
)
data class ChatMessage(
val id: Long = 0,
val conversationId: Long,
val role: String,
val content: String,
val reasoningContent: String? = null,
val imagePaths: List<String> = emptyList(),
val status: MessageStatus = MessageStatus.SUCCESS,
val errorMessage: String? = null,
val timestamp: Long = System.currentTimeMillis(),
)
enum class ImageUploadMode {
ORIGINAL,
SMART_COMPRESS,
}
data class PendingAttachment(
val uriString: String,
val localPath: String? = null,
)
@@ -0,0 +1,33 @@
package com.omnichat.app.domain.model
enum class ImageRouteKind {
/** Path A: /v1/images/generations or /v1/images/edits */
IMAGES_API,
/** Path B: multimodal /v1/chat/completions that returns images */
CHAT_MULTIMODAL,
}
data class ImageGenerateRequest(
val prompt: String,
val referenceImageFiles: List<java.io.File> = emptyList(),
/** Force edits endpoint (Path C with refs). */
val forceImageEdit: Boolean = false,
val preferredModelRowId: Long? = null,
val size: String? = null,
)
data class GeneratedImage(
val localPath: String,
val revisedPrompt: String? = null,
val routeKind: ImageRouteKind,
val modelId: String,
val createdAt: Long = System.currentTimeMillis(),
)
data class ImageGenerateResult(
val images: List<GeneratedImage>,
val routeKind: ImageRouteKind,
val modelId: String,
val providerName: String,
)
@@ -0,0 +1,8 @@
package com.omnichat.app.domain.model
enum class MessageStatus {
SENDING,
STREAMING,
SUCCESS,
ERROR,
}
@@ -0,0 +1,9 @@
package com.omnichat.app.domain.model
enum class ModelCapability {
CHAT,
VISION,
IMAGE_GEN,
IMAGE_EDIT,
REASONING,
}
@@ -0,0 +1,27 @@
package com.omnichat.app.domain.model
/** Models that only speak the Images API and will 4xx/502 on /chat/completions. */
fun isImagesApiOnlyModel(modelId: String): Boolean {
val id = modelId.lowercase()
val exclusive = listOf(
"dall-e",
"gpt-image",
"flux",
"stable-diffusion",
"sdxl",
"midjourney",
"mj-",
"imagen",
)
return exclusive.any { id.contains(it) }
}
fun AiModel.isSuitableForChat(): Boolean {
if (isImagesApiOnlyModel(modelId)) return false
if (ModelCapability.CHAT in capabilities) return true
if (capabilities.isEmpty()) return true
// Vision/reasoning models without explicit CHAT tag are still chat-capable.
if (ModelCapability.VISION in capabilities || ModelCapability.REASONING in capabilities) return true
// Pure image-gen tags without chat → not for dialogue
return ModelCapability.IMAGE_GEN !in capabilities && ModelCapability.IMAGE_EDIT !in capabilities
}
@@ -0,0 +1,67 @@
package com.omnichat.app.domain.model
data class Provider(
val id: Long = 0,
val name: String,
val baseUrl: String,
val apiKeyMasked: String,
val hasApiKey: Boolean,
val isEnabled: Boolean = true,
)
data class AiModel(
val id: Long = 0,
val providerId: Long,
val modelId: String,
val displayName: String,
val capabilities: Set<ModelCapability> = emptySet(),
val isManual: Boolean = false,
)
data class ProviderDraft(
val id: Long? = null,
val name: String = "",
val baseUrl: String = "",
/** Empty means keep existing key when editing. */
val apiKey: String = "",
val isEnabled: Boolean = true,
)
fun guessCapabilities(modelId: String): Set<ModelCapability> {
val id = modelId.lowercase()
val caps = linkedSetOf<ModelCapability>()
val imageHints = listOf(
"dall-e", "gpt-image", "flux", "imagen", "stable-diffusion", "sdxl",
"image", "midjourney", "mj-",
)
val visionHints = listOf("vision", "gpt-4o", "gpt-4.1", "claude-3", "gemini", "qwen-vl", "llava")
val reasoningHints = listOf("o1", "o3", "r1", "reason", "thinking", "qwq")
when {
imageHints.any { id.contains(it) } &&
(id.contains("edit") || id.contains("img2img") || id.contains("image-edit")) -> {
caps += ModelCapability.IMAGE_EDIT
caps += ModelCapability.IMAGE_GEN
}
imageHints.any { id.contains(it) } -> {
caps += ModelCapability.IMAGE_GEN
if (id.contains("gpt-image") || id.contains("flux")) {
caps += ModelCapability.IMAGE_EDIT
}
}
else -> caps += ModelCapability.CHAT
}
if (visionHints.any { id.contains(it) }) {
caps += ModelCapability.VISION
if (ModelCapability.CHAT !in caps && ModelCapability.IMAGE_GEN !in caps) {
caps += ModelCapability.CHAT
}
}
if (reasoningHints.any { id.contains(it) }) {
caps += ModelCapability.REASONING
caps += ModelCapability.CHAT
}
if (caps.isEmpty()) caps += ModelCapability.CHAT
return caps
}
@@ -0,0 +1,7 @@
package com.omnichat.app.presentation
/**
* ViewModel packages are reserved for later steps (chat / image / settings).
* Network wiring happens in repositories once Provider configs exist.
*/
object PresentationPlaceholders
@@ -0,0 +1,494 @@
package com.omnichat.app.presentation.chat
import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.omnichat.app.data.local.datastore.ChatPrefs
import com.omnichat.app.data.local.datastore.DefaultModelRefs
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.repository.ChatRepository
import com.omnichat.app.data.repository.ChatStreamingInteractor
import com.omnichat.app.data.repository.ProviderRepository
import com.omnichat.app.data.repository.SettingsRepository
import com.omnichat.app.data.repository.SmartImageRouter
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ChatMessage
import com.omnichat.app.domain.model.Conversation
import com.omnichat.app.domain.model.ImageGenerateRequest
import com.omnichat.app.domain.model.MessageStatus
import com.omnichat.app.domain.model.Provider
import com.omnichat.app.domain.model.isSuitableForChat
import com.omnichat.app.service.ImageGenerationForegroundService
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class ChatUiState(
val conversations: List<Conversation> = emptyList(),
val currentConversationId: Long? = null,
val currentModelLabel: String? = null,
val messages: List<ChatMessage> = emptyList(),
val providers: List<Provider> = emptyList(),
val models: List<AiModel> = emptyList(),
val defaults: DefaultModelRefs = DefaultModelRefs(),
val chatPrefs: ChatPrefs = ChatPrefs(),
val input: String = "",
val pendingImageUris: List<String> = emptyList(),
val imageGenMode: Boolean = false,
val isStreaming: Boolean = false,
val streamingPreview: Pair<String, String?>? = null,
val error: String? = null,
)
private data class ChatLocalState(
val currentConversationId: Long? = null,
val input: String = "",
val pendingImageUris: List<String> = emptyList(),
val imageGenMode: Boolean = false,
val isStreaming: Boolean = false,
val streamingPreview: Pair<String, String?>? = null,
val error: String? = null,
)
@OptIn(ExperimentalCoroutinesApi::class)
class ChatViewModel(
application: Application,
private val chatRepository: ChatRepository,
private val providerRepository: ProviderRepository,
private val settingsRepository: SettingsRepository,
private val streamingInteractor: ChatStreamingInteractor,
private val imageCompressor: ImageCompressor,
private val smartImageRouter: SmartImageRouter,
) : AndroidViewModel(application) {
private val local = MutableStateFlow(ChatLocalState())
private var streamJob: Job? = null
private var bootstrapped = false
private val messagesFlow = local.flatMapLatest { state ->
val id = state.currentConversationId
if (id == null) flowOf(emptyList()) else chatRepository.observeMessages(id)
}
private val sessionFlow = combine(
chatRepository.conversations,
messagesFlow,
providerRepository.providers,
providerRepository.models,
local,
) { conversations, messages, providers, models, localState ->
SessionSlice(conversations, messages, providers, models, localState)
}
private val prefsFlow = combine(
settingsRepository.defaultModels,
settingsRepository.chatPrefs,
) { defaults, chatPrefs ->
defaults to chatPrefs
}
val uiState: StateFlow<ChatUiState> = combine(sessionFlow, prefsFlow) { session, prefs ->
val conversation = session.conversations
.firstOrNull { it.id == session.local.currentConversationId }
val modelId = conversation?.modelId
?: prefs.first.chatModelRowId?.let { rowId ->
session.models.firstOrNull { it.id == rowId }?.modelId
}
ChatUiState(
conversations = session.conversations,
currentConversationId = session.local.currentConversationId,
currentModelLabel = modelId,
messages = session.messages,
providers = session.providers,
models = session.models,
defaults = prefs.first,
chatPrefs = prefs.second,
input = session.local.input,
pendingImageUris = session.local.pendingImageUris,
imageGenMode = session.local.imageGenMode,
isStreaming = session.local.isStreaming,
streamingPreview = session.local.streamingPreview,
error = session.local.error,
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ChatUiState())
init {
viewModelScope.launch {
settingsRepository.chatPrefs.collect { prefs ->
if (!bootstrapped && local.value.currentConversationId == null) {
bootstrapped = true
val existing = prefs.lastConversationId
?.let { chatRepository.getConversation(it)?.id }
if (existing != null) {
local.update { it.copy(currentConversationId = existing) }
}
}
}
}
}
fun onInputChange(value: String) {
local.update { it.copy(input = value) }
}
fun selectConversation(id: Long) {
local.update { it.copy(currentConversationId = id, error = null, streamingPreview = null) }
viewModelScope.launch { settingsRepository.setLastConversationId(id) }
}
fun newConversation() {
viewModelScope.launch {
val defaults = uiState.value.defaults
val model = defaults.chatModelRowId?.let { providerRepository.getModel(it) }
val id = chatRepository.createConversation(
providerId = model?.providerId,
modelId = model?.modelId,
)
local.update {
it.copy(
currentConversationId = id,
input = "",
pendingImageUris = emptyList(),
streamingPreview = null,
)
}
settingsRepository.setLastConversationId(id)
}
}
fun deleteConversation(id: Long) {
viewModelScope.launch {
chatRepository.deleteConversation(id)
if (local.value.currentConversationId == id) {
local.update { it.copy(currentConversationId = null, streamingPreview = null) }
settingsRepository.setLastConversationId(null)
}
}
}
fun importImages(uris: List<Uri>, resolver: android.content.ContentResolver) {
viewModelScope.launch {
runCatching {
val mode = uiState.value.chatPrefs.imageUploadMode
uris.map { uri ->
imageCompressor.materialize(
uri = uri,
mode = mode,
resolver = resolver,
).absolutePath
}
}.onSuccess { paths ->
local.update { state ->
state.copy(pendingImageUris = (state.pendingImageUris + paths).distinct())
}
}.onFailure { e ->
local.update { it.copy(error = e.message ?: "导入图片失败") }
}
}
}
fun removePendingImage(path: String) {
local.update { it.copy(pendingImageUris = it.pendingImageUris - path) }
if (path.startsWith("/") || path.startsWith("file:")) {
runCatching { java.io.File(path.removePrefix("file://")).delete() }
}
}
fun setSmartCompress(enabled: Boolean) {
viewModelScope.launch { settingsRepository.setSmartCompress(enabled) }
}
fun setContextWindowRounds(rounds: Int) {
viewModelScope.launch { settingsRepository.setContextWindowRounds(rounds) }
}
fun setImageGenMode(enabled: Boolean) {
local.update { it.copy(imageGenMode = enabled) }
}
fun send() {
val text = local.value.input.trim()
val images = local.value.pendingImageUris
if ((text.isEmpty() && images.isEmpty()) || local.value.isStreaming) return
if (local.value.imageGenMode) {
sendImageGenMode(text, images)
return
}
viewModelScope.launch {
try {
local.update { it.copy(error = null) }
ensureConversation()
val conversationId = local.value.currentConversationId
?: error("无法创建会话")
val (providerId, modelId) = resolveChatEndpoint(conversationId)
val files = images.map { path ->
val file = java.io.File(path.removePrefix("file://"))
require(file.exists()) { "图片已失效,请重新选择: ${file.name}" }
file
}
val paths = files.map { it.absolutePath }
chatRepository.insertMessage(
ChatMessage(
conversationId = conversationId,
role = "user",
content = text,
imagePaths = paths,
status = MessageStatus.SUCCESS,
),
)
val assistantId = chatRepository.insertMessage(
ChatMessage(
conversationId = conversationId,
role = "assistant",
content = "",
status = MessageStatus.STREAMING,
),
)
local.update {
it.copy(
input = "",
pendingImageUris = emptyList(),
isStreaming = true,
streamingPreview = "" to null,
)
}
streamJob?.cancel()
streamJob = viewModelScope.launch {
runCatching {
streamingInteractor.streamAssistantReply(
conversationId = conversationId,
providerId = providerId,
modelId = modelId,
contextWindowRounds = uiState.value.chatPrefs.contextWindowRounds,
assistantMessageId = assistantId,
onPartial = { content, reasoning ->
local.update { state ->
state.copy(streamingPreview = content to reasoning)
}
},
)
}.onFailure { e ->
local.update { it.copy(error = e.message ?: "发送失败") }
}
local.update { it.copy(isStreaming = false, streamingPreview = null) }
}
} catch (e: Exception) {
local.update {
it.copy(isStreaming = false, error = e.message ?: "发送失败")
}
}
}
}
/** Path C: chat composer image-tool mode → SmartImageRouter. */
private fun sendImageGenMode(text: String, images: List<String>) {
viewModelScope.launch {
val appCtx = getApplication<Application>()
try {
require(text.isNotBlank()) { "生图模式需要提示词" }
local.update { it.copy(error = null, isStreaming = true) }
ensureConversation()
val conversationId = local.value.currentConversationId
?: error("无法创建会话")
val files = images.map { path ->
val file = java.io.File(path.removePrefix("file://"))
require(file.exists()) { "图片已失效,请重新选择: ${file.name}" }
file
}
chatRepository.insertMessage(
ChatMessage(
conversationId = conversationId,
role = "user",
content = text,
imagePaths = files.map { it.absolutePath },
status = MessageStatus.SUCCESS,
),
)
val assistantId = chatRepository.insertMessage(
ChatMessage(
conversationId = conversationId,
role = "assistant",
content = "正在生成图像…",
status = MessageStatus.STREAMING,
),
)
local.update {
it.copy(input = "", pendingImageUris = emptyList(), streamingPreview = "正在生成图像…" to null)
}
ImageGenerationForegroundService.start(appCtx)
val defaults = uiState.value.defaults
val result = smartImageRouter.generate(
ImageGenerateRequest(
prompt = text,
referenceImageFiles = files,
forceImageEdit = files.isNotEmpty(),
preferredModelRowId = if (files.isNotEmpty()) {
defaults.imageEditModelRowId ?: defaults.imageGenModelRowId
} else {
defaults.imageGenModelRowId
},
),
)
chatRepository.updateMessage(
ChatMessage(
id = assistantId,
conversationId = conversationId,
role = "assistant",
content = "已生成 ${result.images.size} 张图(${result.routeKind.name} / ${result.modelId})",
imagePaths = result.images.map { it.localPath },
status = MessageStatus.SUCCESS,
),
)
chatRepository.touchConversation(conversationId)
} catch (e: Exception) {
local.update { it.copy(error = e.message ?: "生图失败") }
} finally {
ImageGenerationForegroundService.stop(appCtx)
local.update { it.copy(isStreaming = false, streamingPreview = null) }
}
}
}
fun stopStreaming() {
streamJob?.cancel()
local.update { it.copy(isStreaming = false, streamingPreview = null) }
}
fun regenerateLast() {
val messages = uiState.value.messages
val lastAssistant = messages.lastOrNull { it.role == "assistant" } ?: return
if (local.value.isStreaming) return
viewModelScope.launch {
val conversationId = lastAssistant.conversationId
chatRepository.deleteMessage(lastAssistant.id)
val (providerId, modelId) = resolveChatEndpoint(conversationId)
val assistantId = chatRepository.insertMessage(
ChatMessage(
conversationId = conversationId,
role = "assistant",
content = "",
status = MessageStatus.STREAMING,
),
)
local.update { it.copy(isStreaming = true, streamingPreview = "" to null, error = null) }
streamJob?.cancel()
streamJob = viewModelScope.launch {
runCatching {
streamingInteractor.streamAssistantReply(
conversationId = conversationId,
providerId = providerId,
modelId = modelId,
contextWindowRounds = uiState.value.chatPrefs.contextWindowRounds,
assistantMessageId = assistantId,
onPartial = { content, reasoning ->
local.update { state -> state.copy(streamingPreview = content to reasoning) }
},
)
}.onFailure { e ->
local.update { it.copy(error = e.message ?: "重新生成失败") }
}
local.update { it.copy(isStreaming = false, streamingPreview = null) }
}
}
}
fun consumeError() {
local.update { it.copy(error = null) }
}
private suspend fun ensureConversation() {
if (local.value.currentConversationId != null) return
val defaults = uiState.value.defaults
val model = defaults.chatModelRowId?.let { providerRepository.getModel(it) }
if (model != null && (com.omnichat.app.domain.model.isImagesApiOnlyModel(model.modelId) || !model.isSuitableForChat())) {
error(
"默认对话模型「${model.modelId}」是生图模型,不能聊天。" +
"请到设置改选聊天模型后再发消息。",
)
}
val id = chatRepository.createConversation(
providerId = model?.providerId,
modelId = model?.modelId,
)
local.update { it.copy(currentConversationId = id) }
settingsRepository.setLastConversationId(id)
}
private suspend fun resolveChatEndpoint(conversationId: Long): Pair<Long, String> {
val conversation = chatRepository.getConversation(conversationId)
val providerId = conversation?.providerId
val modelId = conversation?.modelId
if (providerId != null && !modelId.isNullOrBlank()) {
if (com.omnichat.app.domain.model.isImagesApiOnlyModel(modelId)) {
// Conversation stuck on an image model — fall through to default chat model.
} else {
return providerId to modelId
}
}
val defaultRowId = uiState.value.defaults.chatModelRowId
?: error("请先在设置中指定默认对话模型(不要选 gpt-image / dall-e / flux 这类纯生图模型)")
val model = providerRepository.getModel(defaultRowId)
?: error("默认对话模型不存在")
if (com.omnichat.app.domain.model.isImagesApiOnlyModel(model.modelId) ||
!model.isSuitableForChat()
) {
error(
"当前默认对话模型「${model.modelId}」不能用于聊天。" +
"请到设置改选聊天模型(如 gpt-4o、claude、gemini、deepseek 等)。",
)
}
chatRepository.updateConversationModel(conversationId, model.providerId, model.modelId)
return model.providerId to model.modelId
}
private data class SessionSlice(
val conversations: List<Conversation>,
val messages: List<ChatMessage>,
val providers: List<Provider>,
val models: List<AiModel>,
val local: ChatLocalState,
)
companion object {
fun factory(
application: Application,
chatRepository: ChatRepository,
providerRepository: ProviderRepository,
settingsRepository: SettingsRepository,
streamingInteractor: ChatStreamingInteractor,
imageCompressor: ImageCompressor,
smartImageRouter: SmartImageRouter,
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ChatViewModel(
application,
chatRepository,
providerRepository,
settingsRepository,
streamingInteractor,
imageCompressor,
smartImageRouter,
) as T
}
}
}
}
@@ -0,0 +1,324 @@
package com.omnichat.app.presentation.image
import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.omnichat.app.data.local.media.GallerySaver
import com.omnichat.app.data.local.media.GeneratedImageStore
import com.omnichat.app.data.local.media.ImageCompressor
import com.omnichat.app.data.repository.ProviderRepository
import com.omnichat.app.data.repository.SettingsRepository
import com.omnichat.app.data.repository.SmartImageRouter
import com.omnichat.app.domain.image.ImageRouteResolver
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.GeneratedImage
import com.omnichat.app.domain.model.ImageGenerateRequest
import com.omnichat.app.domain.model.ImageRouteKind
import com.omnichat.app.domain.model.ImageUploadMode
import com.omnichat.app.domain.model.ModelCapability
import com.omnichat.app.service.ImageGenerationForegroundService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
data class ImageGenUiState(
val prompt: String = "",
val referenceUris: List<String> = emptyList(),
val smartCompress: Boolean = true,
val isGenerating: Boolean = false,
val results: List<GeneratedImage> = emptyList(),
val recentFiles: List<String> = emptyList(),
val models: List<AiModel> = emptyList(),
val selectedModelRowId: Long? = null,
val resolvedRoute: ImageRouteKind? = null,
val statusText: String? = null,
val error: String? = null,
val message: String? = null,
)
private data class ImageLocalState(
val prompt: String = "",
val referenceUris: List<String> = emptyList(),
val isGenerating: Boolean = false,
val results: List<GeneratedImage> = emptyList(),
val selectedModelRowId: Long? = null,
val statusText: String? = null,
val error: String? = null,
val message: String? = null,
)
class ImageGenViewModel(
application: Application,
private val smartImageRouter: SmartImageRouter,
private val providerRepository: ProviderRepository,
private val settingsRepository: SettingsRepository,
private val imageCompressor: ImageCompressor,
private val imageStore: GeneratedImageStore,
private val gallerySaver: GallerySaver,
) : AndroidViewModel(application) {
private val local = MutableStateFlow(ImageLocalState())
val uiState: StateFlow<ImageGenUiState> = combine(
local,
providerRepository.models,
settingsRepository.defaultModels,
settingsRepository.chatPrefs,
) { localState, models, defaults, prefs ->
val imageModels = models.filter {
ModelCapability.IMAGE_GEN in it.capabilities ||
ModelCapability.IMAGE_EDIT in it.capabilities ||
it.modelId.contains("image", ignoreCase = true) ||
it.modelId.contains("dall-e", ignoreCase = true) ||
it.modelId.contains("flux", ignoreCase = true)
}
val selectedId = localState.selectedModelRowId
?: defaults.imageEditModelRowId?.takeIf { localState.referenceUris.isNotEmpty() }
?: defaults.imageGenModelRowId
?: imageModels.firstOrNull()?.id
val selectedModel = imageModels.firstOrNull { it.id == selectedId }
ImageGenUiState(
prompt = localState.prompt,
referenceUris = localState.referenceUris,
smartCompress = prefs.imageUploadMode == ImageUploadMode.SMART_COMPRESS,
isGenerating = localState.isGenerating,
results = localState.results,
recentFiles = imageStore.listRecent().map { it.absolutePath },
models = imageModels,
selectedModelRowId = selectedId,
resolvedRoute = selectedModel?.let { ImageRouteResolver.resolve(it) },
statusText = localState.statusText,
error = localState.error,
message = localState.message,
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ImageGenUiState())
fun onPromptChange(value: String) {
local.update { it.copy(prompt = value) }
}
/**
* Import Photo Picker URIs immediately with the Activity [resolver],
* so temporary read grants are not lost before generate().
*/
fun importReferences(
uris: List<Uri>,
resolver: android.content.ContentResolver,
) {
viewModelScope.launch {
runCatching {
val mode = if (uiState.value.smartCompress) {
ImageUploadMode.SMART_COMPRESS
} else {
ImageUploadMode.ORIGINAL
}
uris.map { uri ->
imageCompressor.materialize(
uri = uri,
mode = mode,
subDir = "image_refs",
resolver = resolver,
).absolutePath
}
}.onSuccess { paths ->
local.update {
it.copy(referenceUris = (it.referenceUris + paths).distinct())
}
}.onFailure { e ->
local.update { it.copy(error = e.message ?: "导入参考图失败") }
}
}
}
fun removeReference(uri: String) {
local.update { it.copy(referenceUris = it.referenceUris - uri) }
// Only delete imported ref copies — never wipe generated_images gallery files.
val file = File(uri.removePrefix("file://"))
val refsDir = File(getApplication<Application>().filesDir, "image_refs").absolutePath
if (file.absolutePath.startsWith(refsDir)) {
runCatching { file.delete() }
}
}
/**
* Copy a generated / gallery result into the reference strip for further edits.
* Always copies into `image_refs/` so removing a ref cannot delete gallery originals.
*/
fun addResultAsReference(path: String) {
viewModelScope.launch {
val source = File(path.removePrefix("file://"))
if (!source.exists()) {
local.update { it.copy(error = "图片文件不存在") }
return@launch
}
val current = local.value.referenceUris
if (current.any { File(it.removePrefix("file://")).absolutePath == source.absolutePath }) {
local.update { it.copy(message = "该图已在参考图中") }
return@launch
}
// Also detect if an existing ref is already a copy of the same bytes path name
if (current.size >= 4) {
local.update { it.copy(error = "参考图最多 4 张,请先移除再添加") }
return@launch
}
runCatching {
// Keep original fidelity for iterative edits.
imageCompressor.materializeFile(
source = source,
mode = ImageUploadMode.ORIGINAL,
subDir = "image_refs",
).let { refFile ->
// materializeFile ORIGINAL returns the source itself — force a real copy.
if (refFile.absolutePath == source.absolutePath) {
val dir = File(getApplication<Application>().filesDir, "image_refs").apply { mkdirs() }
val copy = File(dir, "ref_${System.currentTimeMillis()}_${source.name}")
source.copyTo(copy, overwrite = true)
copy.absolutePath
} else {
refFile.absolutePath
}
}
}.onSuccess { refPath ->
local.update {
it.copy(
referenceUris = (it.referenceUris + refPath).distinct(),
// Clear manual model pick so default 图生图 can take over when present.
selectedModelRowId = null,
message = "已加入参考图,改提示词后可继续编辑",
)
}
}.onFailure { e ->
local.update { it.copy(error = e.message ?: "加入参考图失败") }
}
}
}
fun selectModel(modelRowId: Long) {
local.update { it.copy(selectedModelRowId = modelRowId) }
}
fun setSmartCompress(enabled: Boolean) {
viewModelScope.launch { settingsRepository.setSmartCompress(enabled) }
}
fun generate() {
val prompt = local.value.prompt.trim()
if (prompt.isEmpty() || local.value.isGenerating) return
viewModelScope.launch {
local.update {
it.copy(isGenerating = true, error = null, statusText = "正在生成图像…", message = null)
}
val appCtx = getApplication<Application>()
ImageGenerationForegroundService.start(appCtx)
runCatching {
val refs = local.value.referenceUris.map { path ->
val file = File(path.removePrefix("file://"))
require(file.exists()) {
"参考图已失效,请重新选择: ${file.name}"
}
file
}
smartImageRouter.generate(
ImageGenerateRequest(
prompt = prompt,
referenceImageFiles = refs,
// Image tab lets ImageRouteResolver choose Path A/B;
// Path A still auto-switches to /edits when refs exist.
forceImageEdit = false,
preferredModelRowId = local.value.selectedModelRowId
?: uiState.value.selectedModelRowId,
),
)
}.onSuccess { result ->
local.update {
it.copy(
isGenerating = false,
results = result.images + it.results,
statusText = "完成 · ${result.routeKind.name} · ${result.modelId}",
message = "已生成 ${result.images.size} 张并落盘",
)
}
}.onFailure { e ->
local.update {
it.copy(
isGenerating = false,
statusText = null,
error = e.message ?: "生图失败",
)
}
}
ImageGenerationForegroundService.stop(appCtx)
}
}
fun saveToGallery(path: String) {
viewModelScope.launch {
gallerySaver.saveImage(File(path))
.onSuccess {
local.update { it.copy(message = "已保存到系统相册") }
}
.onFailure { e ->
local.update { it.copy(error = e.message ?: "保存失败") }
}
}
}
fun deleteResult(path: String) {
val file = File(path.removePrefix("file://"))
val abs = file.absolutePath
runCatching { if (file.exists()) file.delete() }
local.update { state ->
state.copy(
results = state.results.filterNot {
File(it.localPath.removePrefix("file://")).absolutePath == abs
},
// Drop if it was also staged as a reference copy of the same path
referenceUris = state.referenceUris.filterNot {
File(it.removePrefix("file://")).absolutePath == abs
},
message = "已删除该记录",
)
}
}
fun consumeMessage() {
local.update { it.copy(message = null) }
}
fun consumeError() {
local.update { it.copy(error = null) }
}
companion object {
fun factory(
application: Application,
smartImageRouter: SmartImageRouter,
providerRepository: ProviderRepository,
settingsRepository: SettingsRepository,
imageCompressor: ImageCompressor,
imageStore: GeneratedImageStore,
gallerySaver: GallerySaver,
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ImageGenViewModel(
application,
smartImageRouter,
providerRepository,
settingsRepository,
imageCompressor,
imageStore,
gallerySaver,
) as T
}
}
}
}
@@ -0,0 +1,316 @@
package com.omnichat.app.presentation.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.omnichat.app.data.local.datastore.DefaultModelRefs
import com.omnichat.app.data.remote.NetworkModule
import com.omnichat.app.data.repository.ChatStreamingInteractor
import com.omnichat.app.data.repository.ProviderRepository
import com.omnichat.app.data.repository.SettingsRepository
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ModelCapability
import com.omnichat.app.domain.model.Provider
import com.omnichat.app.domain.model.ProviderDraft
import com.omnichat.app.domain.model.isSuitableForChat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class SettingsUiState(
val providers: List<Pair<Provider, List<AiModel>>> = emptyList(),
val defaults: DefaultModelRefs = DefaultModelRefs(),
val searchQuery: String = "",
val expandedProviderIds: Set<Long> = emptySet(),
val editor: ProviderDraft? = null,
val manualModelProviderId: Long? = null,
val manualModelIdInput: String = "",
val isSaving: Boolean = false,
val fetchingProviderId: Long? = null,
val probingProviderId: Long? = null,
val probeResult: String? = null,
val message: String? = null,
val error: String? = null,
)
private data class SettingsLocalState(
val searchQuery: String = "",
val expandedProviderIds: Set<Long> = emptySet(),
val editor: ProviderDraft? = null,
val manualModelProviderId: Long? = null,
val manualModelIdInput: String = "",
val isSaving: Boolean = false,
val fetchingProviderId: Long? = null,
val probingProviderId: Long? = null,
val probeResult: String? = null,
val message: String? = null,
val error: String? = null,
)
class SettingsViewModel(
private val providerRepository: ProviderRepository,
private val settingsRepository: SettingsRepository,
private val chatStreamingInteractor: ChatStreamingInteractor,
) : ViewModel() {
private val local = MutableStateFlow(SettingsLocalState())
val uiState: StateFlow<SettingsUiState> = combine(
providerRepository.observeProvidersWithModels(),
settingsRepository.defaultModels,
local,
) { providers, defaults, localState ->
SettingsUiState(
providers = providers,
defaults = defaults,
searchQuery = localState.searchQuery,
expandedProviderIds = localState.expandedProviderIds,
editor = localState.editor,
manualModelProviderId = localState.manualModelProviderId,
manualModelIdInput = localState.manualModelIdInput,
isSaving = localState.isSaving,
fetchingProviderId = localState.fetchingProviderId,
probingProviderId = localState.probingProviderId,
probeResult = localState.probeResult,
message = localState.message,
error = localState.error,
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState())
fun onSearchQueryChange(value: String) {
local.update { it.copy(searchQuery = value) }
}
fun toggleProviderExpanded(providerId: Long) {
local.update { state ->
val next = if (providerId in state.expandedProviderIds) {
state.expandedProviderIds - providerId
} else {
state.expandedProviderIds + providerId
}
state.copy(expandedProviderIds = next)
}
}
fun openCreateProvider() {
local.update {
it.copy(editor = ProviderDraft(), error = null)
}
}
fun openEditProvider(provider: Provider) {
local.update {
it.copy(
editor = ProviderDraft(
id = provider.id,
name = provider.name,
baseUrl = provider.baseUrl,
apiKey = "",
isEnabled = provider.isEnabled,
),
error = null,
)
}
}
fun updateEditor(transform: (ProviderDraft) -> ProviderDraft) {
local.update { state ->
val editor = state.editor ?: return@update state
state.copy(editor = transform(editor))
}
}
fun dismissEditor() {
local.update { it.copy(editor = null) }
}
fun saveProvider() {
val draft = local.value.editor ?: return
viewModelScope.launch {
local.update { it.copy(isSaving = true, error = null) }
runCatching {
val normalizedDraft = draft.copy(
baseUrl = runCatching {
NetworkModule.normalizeBaseUrl(draft.baseUrl).trimEnd('/')
}.getOrElse { draft.baseUrl },
)
providerRepository.saveProvider(normalizedDraft)
}.onSuccess {
local.update {
it.copy(editor = null, isSaving = false, message = "服务商已保存")
}
}.onFailure { e ->
local.update {
it.copy(isSaving = false, error = e.message ?: "保存失败")
}
}
}
}
fun deleteProvider(providerId: Long) {
viewModelScope.launch {
runCatching { providerRepository.deleteProvider(providerId) }
.onSuccess {
local.update { it.copy(message = "服务商已删除") }
}
.onFailure { e ->
local.update { it.copy(error = e.message ?: "删除失败") }
}
}
}
fun setProviderEnabled(providerId: Long, enabled: Boolean) {
viewModelScope.launch {
providerRepository.setProviderEnabled(providerId, enabled)
}
}
fun fetchModels(providerId: Long) {
viewModelScope.launch {
local.update { it.copy(fetchingProviderId = providerId, error = null) }
providerRepository.fetchModels(providerId)
.onSuccess { count ->
local.update { state ->
state.copy(
fetchingProviderId = null,
message = "已同步 $count 个模型",
expandedProviderIds = state.expandedProviderIds + providerId,
)
}
}
.onFailure { e ->
local.update {
it.copy(
fetchingProviderId = null,
error = e.message ?: "拉取模型失败",
)
}
}
}
}
fun probeChat(providerId: Long) {
viewModelScope.launch {
local.update { it.copy(probingProviderId = providerId, error = null, probeResult = null) }
val snapshot = uiState.value
val models = snapshot.providers.firstOrNull { it.first.id == providerId }?.second.orEmpty()
val defaultChatId = snapshot.defaults.chatModelRowId
val model = models.firstOrNull { it.id == defaultChatId && it.isSuitableForChat() }
?: models.firstOrNull { it.isSuitableForChat() }
if (model == null) {
local.update {
it.copy(
probingProviderId = null,
probeResult = "没有可用的对话模型。请先拉取模型,并把默认对话设为聊天模型(非纯生图)。",
)
}
return@launch
}
val report = runCatching {
chatStreamingInteractor.probeChat(providerId, model.modelId)
}.getOrElse { e ->
"❌ 诊断异常: ${e.message}"
}
local.update {
it.copy(probingProviderId = null, probeResult = report)
}
}
}
fun dismissProbeResult() {
local.update { it.copy(probeResult = null) }
}
fun openManualModelDialog(providerId: Long) {
local.update {
it.copy(manualModelProviderId = providerId, manualModelIdInput = "")
}
}
fun onManualModelIdChange(value: String) {
local.update { it.copy(manualModelIdInput = value) }
}
fun dismissManualModelDialog() {
local.update {
it.copy(manualModelProviderId = null, manualModelIdInput = "")
}
}
fun confirmManualModel() {
val providerId = local.value.manualModelProviderId ?: return
val modelId = local.value.manualModelIdInput
viewModelScope.launch {
runCatching { providerRepository.addManualModel(providerId, modelId) }
.onSuccess {
local.update { state ->
state.copy(
manualModelProviderId = null,
manualModelIdInput = "",
message = "已添加模型",
expandedProviderIds = state.expandedProviderIds + providerId,
)
}
}
.onFailure { e ->
local.update { it.copy(error = e.message ?: "添加失败") }
}
}
}
fun toggleCapability(model: AiModel, capability: ModelCapability) {
val next = model.capabilities.toMutableSet().apply {
if (!add(capability)) remove(capability)
}
viewModelScope.launch {
providerRepository.updateModelCapabilities(model.id, next)
}
}
fun deleteModel(modelId: Long) {
viewModelScope.launch {
providerRepository.deleteModel(modelId)
}
}
fun setDefaultChatModel(modelRowId: Long?) {
viewModelScope.launch { settingsRepository.setDefaultChatModel(modelRowId) }
}
fun setDefaultImageGenModel(modelRowId: Long?) {
viewModelScope.launch { settingsRepository.setDefaultImageGenModel(modelRowId) }
}
fun setDefaultImageEditModel(modelRowId: Long?) {
viewModelScope.launch { settingsRepository.setDefaultImageEditModel(modelRowId) }
}
fun consumeMessage() {
local.update { it.copy(message = null) }
}
fun consumeError() {
local.update { it.copy(error = null) }
}
companion object {
fun factory(
providerRepository: ProviderRepository,
settingsRepository: SettingsRepository,
chatStreamingInteractor: ChatStreamingInteractor,
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return SettingsViewModel(
providerRepository,
settingsRepository,
chatStreamingInteractor,
) as T
}
}
}
}
@@ -0,0 +1,103 @@
package com.omnichat.app.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.omnichat.app.MainActivity
import com.omnichat.app.R
/**
* Keeps the process alive while a long image generation request is in flight.
*/
class ImageGenerationForegroundService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_STOP -> {
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
return START_NOT_STICKY
}
else -> {
ensureChannel()
val notification = buildNotification(
intent?.getStringExtra(EXTRA_STATUS)
?: getString(R.string.image_generating_notification),
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,
)
} else {
startForeground(NOTIFICATION_ID, notification)
}
}
}
return START_STICKY
}
private fun ensureChannel() {
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
CHANNEL_ID,
getString(R.string.image_fg_channel_name),
NotificationManager.IMPORTANCE_LOW,
).apply {
description = getString(R.string.image_fg_channel_desc)
}
manager.createNotificationChannel(channel)
}
private fun buildNotification(status: String): Notification {
val launch = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
return NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(status)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(launch)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
}
companion object {
const val CHANNEL_ID = "omnichat_image_gen"
const val NOTIFICATION_ID = 42
const val ACTION_START = "com.omnichat.app.action.IMAGE_GEN_START"
const val ACTION_STOP = "com.omnichat.app.action.IMAGE_GEN_STOP"
const val EXTRA_STATUS = "status"
fun start(context: Context, status: String? = null) {
val intent = Intent(context, ImageGenerationForegroundService::class.java).apply {
action = ACTION_START
putExtra(EXTRA_STATUS, status)
}
ContextCompat.startForegroundService(context, intent)
}
fun stop(context: Context) {
val intent = Intent(context, ImageGenerationForegroundService::class.java).apply {
action = ACTION_STOP
}
context.startService(intent)
}
}
}
@@ -0,0 +1,86 @@
package com.omnichat.app.ui.navigation
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Chat
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.omnichat.app.R
import com.omnichat.app.ui.screens.chat.ChatScreen
import com.omnichat.app.ui.screens.image.ImageGenScreen
import com.omnichat.app.ui.screens.settings.SettingsScreen
enum class TopLevelDestination(
val route: String,
val labelRes: Int,
val icon: ImageVector,
) {
Chat("chat", R.string.tab_chat, Icons.AutoMirrored.Outlined.Chat),
Image("image", R.string.tab_image, Icons.Outlined.Image),
Settings("settings", R.string.tab_settings, Icons.Outlined.Settings),
}
@Composable
fun OmniChatNavHost(modifier: Modifier = Modifier) {
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
Scaffold(
modifier = modifier,
bottomBar = {
NavigationBar {
TopLevelDestination.entries.forEach { destination ->
val selected = currentDestination
?.hierarchy
?.any { it.route == destination.route } == true
NavigationBarItem(
selected = selected,
onClick = {
navController.navigate(destination.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
},
icon = {
Icon(
imageVector = destination.icon,
contentDescription = stringResource(destination.labelRes),
)
},
label = { Text(stringResource(destination.labelRes)) },
)
}
}
},
) { innerPadding ->
NavHost(
navController = navController,
startDestination = TopLevelDestination.Chat.route,
modifier = Modifier.padding(innerPadding),
) {
composable(TopLevelDestination.Chat.route) { ChatScreen() }
composable(TopLevelDestination.Image.route) { ImageGenScreen() }
composable(TopLevelDestination.Settings.route) { SettingsScreen() }
}
}
}
@@ -0,0 +1,428 @@
package com.omnichat.app.ui.screens.chat
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.AsyncImage
import com.omnichat.app.OmniChatApp
import com.omnichat.app.R
import com.omnichat.app.domain.model.ImageUploadMode
import com.omnichat.app.domain.model.MessageStatus
import com.omnichat.app.presentation.chat.ChatViewModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatScreen(modifier: Modifier = Modifier) {
val app = LocalContext.current.applicationContext as OmniChatApp
val viewModel: ChatViewModel = viewModel(
factory = ChatViewModel.factory(
application = app,
chatRepository = app.container.chatRepository,
providerRepository = app.container.providerRepository,
settingsRepository = app.container.settingsRepository,
streamingInteractor = app.container.chatStreamingInteractor,
imageCompressor = app.container.imageCompressor,
smartImageRouter = app.container.smartImageRouter,
),
)
val state by viewModel.uiState.collectAsStateWithLifecycle()
val drawerState = rememberDrawerState(DrawerValue.Closed)
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val listState = rememberLazyListState()
val context = LocalContext.current
val photoPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickMultipleVisualMedia(maxItems = 6),
) { uris ->
if (uris.isNotEmpty()) viewModel.importImages(uris, context.contentResolver)
}
LaunchedEffect(state.error) {
state.error?.let {
snackbarHostState.showSnackbar(it)
viewModel.consumeError()
}
}
LaunchedEffect(state.messages.size, state.streamingPreview, state.isStreaming) {
val last = state.messages.lastIndex
if (last >= 0) {
listState.animateScrollToItem(last)
}
}
val currentTitle = state.conversations
.firstOrNull { it.id == state.currentConversationId }
?.title
?: stringResource(R.string.chat_title)
ModalNavigationDrawer(
modifier = modifier,
drawerState = drawerState,
drawerContent = {
ModalDrawerSheet {
ConversationDrawer(
conversations = state.conversations,
selectedId = state.currentConversationId,
contextRounds = state.chatPrefs.contextWindowRounds,
onNewChat = {
viewModel.newConversation()
scope.launch { drawerState.close() }
},
onSelect = {
viewModel.selectConversation(it)
scope.launch { drawerState.close() }
},
onDelete = viewModel::deleteConversation,
onContextRoundsChange = viewModel::setContextWindowRounds,
)
}
},
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Column {
Text(
text = currentTitle,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
state.currentModelLabel?.let { model ->
Text(
text = model,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
},
navigationIcon = {
IconButton(onClick = { scope.launch { drawerState.open() } }) {
Icon(Icons.Default.Menu, contentDescription = stringResource(R.string.chat_sessions))
}
},
actions = {
IconButton(onClick = viewModel::newConversation) {
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.chat_new))
}
},
)
},
snackbarHost = { SnackbarHost(snackbarHostState) },
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
if (state.defaults.chatModelRowId == null) {
Text(
text = stringResource(R.string.chat_need_default_model),
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
LazyColumn(
state = listState,
modifier = Modifier
.weight(1f)
.fillMaxWidth(),
contentPadding = PaddingValues(vertical = 8.dp),
) {
items(state.messages, key = { it.id }) { message ->
val isLastAssistant = message.id == state.messages.lastOrNull { it.role == "assistant" }?.id
val usePreview = state.isStreaming &&
isLastAssistant &&
message.status == MessageStatus.STREAMING &&
state.streamingPreview != null
MessageBubble(
message = message,
isStreamingPreview = usePreview,
streamingContent = state.streamingPreview?.first,
streamingReasoning = state.streamingPreview?.second,
showRegenerate = isLastAssistant && !state.isStreaming,
onRegenerate = viewModel::regenerateLast,
)
}
}
HorizontalDivider()
ComposerBar(
input = state.input,
pendingUris = state.pendingImageUris,
smartCompress = state.chatPrefs.imageUploadMode == ImageUploadMode.SMART_COMPRESS,
imageGenMode = state.imageGenMode,
isStreaming = state.isStreaming,
onInputChange = viewModel::onInputChange,
onPickImages = {
photoPicker.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
)
},
onRemoveImage = viewModel::removePendingImage,
onToggleCompress = { enabled -> viewModel.setSmartCompress(enabled) },
onToggleImageGenMode = viewModel::setImageGenMode,
onSend = viewModel::send,
onStop = viewModel::stopStreaming,
)
}
}
}
}
@Composable
private fun ConversationDrawer(
conversations: List<com.omnichat.app.domain.model.Conversation>,
selectedId: Long?,
contextRounds: Int,
onNewChat: () -> Unit,
onSelect: (Long) -> Unit,
onDelete: (Long) -> Unit,
onContextRoundsChange: (Int) -> Unit,
) {
val formatter = remember {
SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
}
Column(modifier = Modifier.fillMaxSize()) {
Text(
text = stringResource(R.string.chat_sessions),
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(16.dp),
)
TextButton(
onClick = onNewChat,
modifier = Modifier.padding(horizontal = 12.dp),
) {
Icon(Icons.Default.Add, contentDescription = null)
Text(
text = stringResource(R.string.chat_new),
modifier = Modifier.padding(start = 8.dp),
)
}
HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))
LazyColumn(modifier = Modifier.weight(1f)) {
items(conversations, key = { it.id }) { conversation ->
NavigationDrawerItem(
label = {
Column {
Text(
text = conversation.title,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = formatter.format(Date(conversation.updatedAt)),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
selected = conversation.id == selectedId,
onClick = { onSelect(conversation.id) },
badge = {
IconButton(onClick = { onDelete(conversation.id) }) {
Icon(
Icons.Default.Close,
contentDescription = stringResource(R.string.settings_delete),
modifier = Modifier.size(18.dp),
)
}
},
modifier = Modifier.padding(horizontal = 8.dp),
)
}
}
HorizontalDivider()
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = stringResource(R.string.chat_context_window, contextRounds),
style = MaterialTheme.typography.labelLarge,
)
Slider(
value = contextRounds.toFloat(),
onValueChange = { onContextRoundsChange(it.toInt()) },
valueRange = 2f..40f,
steps = 37,
)
}
}
}
@Composable
private fun ComposerBar(
input: String,
pendingUris: List<String>,
smartCompress: Boolean,
imageGenMode: Boolean,
isStreaming: Boolean,
onInputChange: (String) -> Unit,
onPickImages: () -> Unit,
onRemoveImage: (String) -> Unit,
onToggleCompress: (Boolean) -> Unit,
onToggleImageGenMode: (Boolean) -> Unit,
onSend: () -> Unit,
onStop: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (pendingUris.isNotEmpty()) {
Row(
modifier = Modifier.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
pendingUris.forEach { path ->
Box {
AsyncImage(
model = java.io.File(path.removePrefix("file://")),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(72.dp)
.height(72.dp)
.clip(RoundedCornerShape(10.dp)),
)
IconButton(
onClick = { onRemoveImage(path) },
modifier = Modifier.align(Alignment.TopEnd),
) {
Icon(
Icons.Default.Close,
contentDescription = null,
modifier = Modifier.size(16.dp),
)
}
}
}
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FilterChip(
selected = smartCompress,
onClick = { onToggleCompress(!smartCompress) },
label = {
Text(
if (smartCompress) {
stringResource(R.string.chat_compress_on)
} else {
stringResource(R.string.chat_compress_off)
},
)
},
)
FilterChip(
selected = imageGenMode,
onClick = { onToggleImageGenMode(!imageGenMode) },
label = { Text(stringResource(R.string.chat_image_mode)) },
)
}
Row(verticalAlignment = Alignment.Bottom) {
IconButton(onClick = onPickImages, enabled = !isStreaming) {
Icon(Icons.Outlined.Image, contentDescription = stringResource(R.string.chat_attach_image))
}
OutlinedTextField(
value = input,
onValueChange = onInputChange,
modifier = Modifier.weight(1f),
placeholder = { Text(stringResource(R.string.chat_input_hint)) },
maxLines = 5,
enabled = !isStreaming,
)
if (isStreaming) {
IconButton(onClick = onStop) {
Icon(Icons.Default.Stop, contentDescription = stringResource(R.string.chat_stop))
}
} else {
IconButton(
onClick = onSend,
enabled = input.isNotBlank() || pendingUris.isNotEmpty(),
) {
Icon(
Icons.AutoMirrored.Outlined.Send,
contentDescription = stringResource(R.string.chat_send),
)
}
}
}
}
}
@@ -0,0 +1,42 @@
package com.omnichat.app.ui.screens.chat
import android.widget.TextView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.material3.MaterialTheme
import io.noties.markwon.Markwon
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin
import io.noties.markwon.linkify.LinkifyPlugin
@Composable
fun MarkdownText(
markdown: String,
modifier: Modifier = Modifier,
) {
val textColor = MaterialTheme.colorScheme.onSurface.toArgb()
val context = androidx.compose.ui.platform.LocalContext.current
val markwon = remember(context) {
Markwon.builder(context)
.usePlugin(StrikethroughPlugin.create())
.usePlugin(LinkifyPlugin.create())
.build()
}
AndroidView(
modifier = modifier,
factory = { ctx ->
TextView(ctx).apply {
setTextIsSelectable(true)
setTextColor(textColor)
textSize = 15f
}
},
update = { textView ->
textView.setTextColor(textColor)
markwon.setMarkdown(textView, markdown.ifBlank { " " })
},
)
}
@@ -0,0 +1,168 @@
package com.omnichat.app.ui.screens.chat
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.omnichat.app.domain.chat.ThinkParser
import com.omnichat.app.domain.model.ChatMessage
import com.omnichat.app.domain.model.MessageStatus
import java.io.File
@Composable
fun MessageBubble(
message: ChatMessage,
isStreamingPreview: Boolean = false,
streamingContent: String? = null,
streamingReasoning: String? = null,
showRegenerate: Boolean = false,
onRegenerate: () -> Unit = {},
modifier: Modifier = Modifier,
) {
val isUser = message.role == "user"
val rawContent = if (isStreamingPreview) streamingContent.orEmpty() else message.content
val parsed = remember(rawContent, message.reasoningContent, streamingReasoning, isStreamingPreview) {
if (isUser) {
ThinkParser.parse(rawContent, null)
} else if (isStreamingPreview) {
ThinkParser.parse(rawContent, streamingReasoning)
} else {
ThinkParser.parse(rawContent, message.reasoningContent)
}
}
Column(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp),
horizontalAlignment = if (isUser) Alignment.End else Alignment.Start,
) {
Surface(
shape = RoundedCornerShape(16.dp),
color = if (isUser) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant
},
modifier = Modifier.fillMaxWidth(if (isUser) 0.92f else 1f),
) {
Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (message.imagePaths.isNotEmpty()) {
Row(
modifier = Modifier.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
message.imagePaths.forEach { path ->
AsyncImage(
model = File(path),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(120.dp)
.height(120.dp)
.clip(RoundedCornerShape(10.dp)),
)
}
}
}
if (!isUser) {
val think = parsed.thinkBlocks
if (!think.isNullOrBlank()) {
ThinkBlock(text = think)
}
}
if (parsed.visibleMarkdown.isNotBlank()) {
if (isUser) {
Text(
text = parsed.visibleMarkdown,
style = MaterialTheme.typography.bodyLarge,
)
} else {
MarkdownText(markdown = parsed.visibleMarkdown)
}
} else if (!isUser && (message.status == MessageStatus.STREAMING || isStreamingPreview)) {
Text("…", style = MaterialTheme.typography.bodyLarge)
}
if (message.status == MessageStatus.ERROR) {
Text(
text = message.errorMessage ?: "生成失败",
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
if (showRegenerate && !isUser && message.status == MessageStatus.SUCCESS) {
TextButton(onClick = onRegenerate) {
Text("重新生成")
}
}
}
}
@Composable
private fun ThinkBlock(text: String) {
var expanded by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.55f))
.clickable { expanded = !expanded }
.padding(10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = "思考过程",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.weight(1f),
)
Icon(
imageVector = if (expanded) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
}
AnimatedVisibility(visible = expanded) {
Text(
text = text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
}
}
}
@@ -0,0 +1,552 @@
package com.omnichat.app.ui.screens.image
import android.Manifest
import android.app.Application
import android.net.Uri
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.outlined.AddPhotoAlternate
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.AsyncImage
import com.omnichat.app.OmniChatApp
import com.omnichat.app.R
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ImageRouteKind
import com.omnichat.app.presentation.image.ImageGenViewModel
import java.io.File
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageGenScreen(modifier: Modifier = Modifier) {
val context = LocalContext.current
val app = context.applicationContext as OmniChatApp
val viewModel: ImageGenViewModel = viewModel(
factory = ImageGenViewModel.factory(
application = context.applicationContext as Application,
smartImageRouter = app.container.smartImageRouter,
providerRepository = app.container.providerRepository,
settingsRepository = app.container.settingsRepository,
imageCompressor = app.container.imageCompressor,
imageStore = app.container.generatedImageStore,
gallerySaver = app.container.gallerySaver,
),
)
val state by viewModel.uiState.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
var previewPath by remember { mutableStateOf<String?>(null) }
val picker = rememberLauncherForActivityResult(
ActivityResultContracts.PickMultipleVisualMedia(maxItems = 4),
) { uris ->
if (uris.isNotEmpty()) {
// Must import with Activity ContentResolver while the temporary grant is valid.
viewModel.importReferences(uris, context.contentResolver)
}
}
val notificationPermission = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) {
viewModel.generate()
}
LaunchedEffect(state.message, state.error) {
state.message?.let {
snackbarHostState.showSnackbar(it)
viewModel.consumeMessage()
}
state.error?.let {
snackbarHostState.showSnackbar(it)
viewModel.consumeError()
}
}
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = {
TopAppBar(title = { Text(stringResource(R.string.image_title)) })
},
snackbarHost = { SnackbarHost(snackbarHostState) },
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
ModelPicker(
models = state.models,
selectedId = state.selectedModelRowId,
route = state.resolvedRoute,
onSelect = viewModel::selectModel,
)
OutlinedTextField(
value = state.prompt,
onValueChange = viewModel::onPromptChange,
modifier = Modifier.fillMaxWidth(),
minLines = 3,
label = { Text(stringResource(R.string.image_prompt)) },
placeholder = { Text(stringResource(R.string.image_prompt_hint)) },
)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FilterChip(
selected = state.smartCompress,
onClick = { viewModel.setSmartCompress(!state.smartCompress) },
label = {
Text(
if (state.smartCompress) {
stringResource(R.string.chat_compress_on)
} else {
stringResource(R.string.chat_compress_off)
},
)
},
)
FilterChip(
selected = state.referenceUris.isNotEmpty(),
onClick = {
picker.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
)
},
label = { Text(stringResource(R.string.image_add_ref)) },
leadingIcon = {
Icon(
Icons.Outlined.Image,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
},
)
}
if (state.referenceUris.isNotEmpty()) {
Row(
modifier = Modifier.horizontalScroll(rememberScrollState()),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
state.referenceUris.forEach { path ->
Box {
AsyncImage(
model = File(path.removePrefix("file://")),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(88.dp)
.height(88.dp)
.clip(RoundedCornerShape(10.dp)),
)
IconButton(
onClick = { viewModel.removeReference(path) },
modifier = Modifier.align(Alignment.TopEnd),
) {
Icon(
Icons.Default.Close,
contentDescription = null,
modifier = Modifier.size(16.dp),
)
}
}
}
}
Text(
text = stringResource(R.string.image_ref_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Button(
onClick = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
viewModel.generate()
}
},
enabled = !state.isGenerating && state.prompt.isNotBlank(),
modifier = Modifier.fillMaxWidth(),
) {
if (state.isGenerating) {
CircularProgressIndicator(
modifier = Modifier
.padding(end = 8.dp)
.size(18.dp),
strokeWidth = 2.dp,
)
}
Text(
if (state.isGenerating) {
stringResource(R.string.image_generating)
} else {
stringResource(R.string.image_generate)
},
)
}
state.statusText?.let {
Text(
text = it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
}
val gallery = (state.results.map { it.localPath } + state.recentFiles).distinct()
if (gallery.isNotEmpty()) {
Text(
text = stringResource(R.string.image_gallery),
style = MaterialTheme.typography.titleMedium,
)
LazyVerticalGrid(
columns = GridCells.Fixed(2),
modifier = Modifier
.fillMaxWidth()
.height((((gallery.size + 1) / 2) * 200).coerceAtMost(600).dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
userScrollEnabled = false,
contentPadding = PaddingValues(bottom = 24.dp),
) {
items(gallery, key = { it }) { path ->
ResultCard(
path = path,
onPreview = { previewPath = path },
onUseAsRef = { viewModel.addResultAsReference(path) },
onSave = { viewModel.saveToGallery(path) },
onDelete = {
if (previewPath == path) previewPath = null
viewModel.deleteResult(path)
},
)
}
}
}
}
}
previewPath?.let { path ->
ImagePreviewDialog(
path = path,
onDismiss = { previewPath = null },
onUseAsRef = {
viewModel.addResultAsReference(path)
previewPath = null
},
onSave = {
viewModel.saveToGallery(path)
},
)
}
}
@Composable
private fun ModelPicker(
models: List<AiModel>,
selectedId: Long?,
route: ImageRouteKind?,
onSelect: (Long) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val selected = models.firstOrNull { it.id == selectedId }
val label = selected?.let { "${it.displayName} (${it.modelId})" }
?: stringResource(R.string.settings_none)
val routeLabel = when (route) {
ImageRouteKind.IMAGES_API -> stringResource(R.string.image_route_a)
ImageRouteKind.CHAT_MULTIMODAL -> stringResource(R.string.image_route_b)
null -> ""
}
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Box(modifier = Modifier.fillMaxWidth()) {
OutlinedTextField(
value = label,
onValueChange = {},
readOnly = true,
enabled = false,
label = { Text(stringResource(R.string.image_model)) },
modifier = Modifier.fillMaxWidth(),
colors = OutlinedTextFieldDefaults.colors(
disabledTextColor = MaterialTheme.colorScheme.onSurface,
disabledBorderColor = MaterialTheme.colorScheme.outline,
disabledLabelColor = MaterialTheme.colorScheme.onSurfaceVariant,
),
)
Box(
modifier = Modifier
.matchParentSize()
.clickable { expanded = true },
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
models.forEach { model ->
DropdownMenuItem(
text = {
Text(
"${model.displayName} (${model.modelId})",
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
onClick = {
onSelect(model.id)
expanded = false
},
)
}
}
}
if (routeLabel.isNotBlank()) {
Text(
text = routeLabel,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.secondary,
)
}
}
}
@Composable
private fun ResultCard(
path: String,
onPreview: () -> Unit,
onUseAsRef: () -> Unit,
onSave: () -> Unit,
onDelete: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp)),
) {
Box {
AsyncImage(
model = File(path),
contentDescription = stringResource(R.string.image_preview),
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(12.dp))
.clickable(onClick = onPreview),
)
IconButton(
onClick = onDelete,
modifier = Modifier
.align(Alignment.TopEnd)
.padding(2.dp),
) {
Icon(
Icons.Default.Delete,
contentDescription = stringResource(R.string.image_delete_result),
tint = Color.White,
modifier = Modifier
.background(
color = Color.Black.copy(alpha = 0.45f),
shape = RoundedCornerShape(8.dp),
)
.padding(4.dp)
.size(18.dp),
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onUseAsRef) {
Text(stringResource(R.string.image_use_as_ref))
}
Row {
IconButton(onClick = onPreview) {
Icon(
Icons.Outlined.Image,
contentDescription = stringResource(R.string.image_preview),
)
}
IconButton(onClick = onSave) {
Icon(
Icons.Outlined.Download,
contentDescription = stringResource(R.string.image_save_gallery),
)
}
}
}
}
}
@Composable
private fun ImagePreviewDialog(
path: String,
onDismiss: () -> Unit,
onUseAsRef: () -> Unit,
onSave: () -> Unit,
) {
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnBackPress = true,
dismissOnClickOutside = true,
),
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black.copy(alpha = 0.94f)),
) {
AsyncImage(
model = File(path),
contentDescription = stringResource(R.string.image_preview),
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxSize()
.padding(bottom = 72.dp)
.graphicsLayer {
scaleX = scale
scaleY = scale
translationX = offset.x
translationY = offset.y
}
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, 5f)
if (scale > 1f) {
offset += pan
} else {
offset = Offset.Zero
}
}
}
.clickable {
// Double-purpose: single tap resets when zoomed, else closes.
if (scale > 1.05f) {
scale = 1f
offset = Offset.Zero
} else {
onDismiss()
}
},
)
Row(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(8.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
IconButton(onClick = onUseAsRef) {
Icon(
Icons.Outlined.AddPhotoAlternate,
contentDescription = stringResource(R.string.image_use_as_ref),
tint = Color.White,
)
}
IconButton(onClick = onSave) {
Icon(
Icons.Outlined.Download,
contentDescription = stringResource(R.string.image_save_gallery),
tint = Color.White,
)
}
IconButton(onClick = onDismiss) {
Icon(
Icons.Default.Close,
contentDescription = stringResource(R.string.settings_cancel),
tint = Color.White,
)
}
}
Text(
text = stringResource(R.string.image_preview_hint),
color = Color.White.copy(alpha = 0.7f),
style = MaterialTheme.typography.labelMedium,
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(16.dp),
)
}
}
}
@@ -0,0 +1,11 @@
package com.omnichat.app.ui.screens.settings
import com.omnichat.app.domain.model.ModelCapability
fun ModelCapability.label(): String = when (this) {
ModelCapability.CHAT -> "对话"
ModelCapability.VISION -> "识图"
ModelCapability.IMAGE_GEN -> "文生图"
ModelCapability.IMAGE_EDIT -> "图生图"
ModelCapability.REASONING -> "推理"
}
@@ -0,0 +1,702 @@
package com.omnichat.app.ui.screens.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.omnichat.app.OmniChatApp
import com.omnichat.app.R
import com.omnichat.app.domain.model.AiModel
import com.omnichat.app.domain.model.ModelCapability
import com.omnichat.app.domain.model.Provider
import com.omnichat.app.domain.model.ProviderDraft
import com.omnichat.app.domain.model.isSuitableForChat
import com.omnichat.app.presentation.settings.SettingsUiState
import com.omnichat.app.presentation.settings.SettingsViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(modifier: Modifier = Modifier) {
val app = LocalContext.current.applicationContext as OmniChatApp
val viewModel: SettingsViewModel = viewModel(
factory = SettingsViewModel.factory(
app.container.providerRepository,
app.container.settingsRepository,
app.container.chatStreamingInteractor,
),
)
val state by viewModel.uiState.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
val clipboard = LocalClipboardManager.current
LaunchedEffect(state.message, state.error) {
state.message?.let {
snackbarHostState.showSnackbar(it)
viewModel.consumeMessage()
}
state.error?.let {
snackbarHostState.showSnackbar(it)
viewModel.consumeError()
}
}
Scaffold(
modifier = modifier.fillMaxSize(),
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.settings_title)) },
actions = {
IconButton(onClick = viewModel::openCreateProvider) {
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.settings_add_provider))
}
},
)
},
snackbarHost = { SnackbarHost(snackbarHostState) },
) { padding ->
SettingsContent(
state = state,
contentPadding = padding,
onSearchChange = viewModel::onSearchQueryChange,
onToggleExpand = viewModel::toggleProviderExpanded,
onEditProvider = viewModel::openEditProvider,
onDeleteProvider = viewModel::deleteProvider,
onEnabledChange = viewModel::setProviderEnabled,
onFetchModels = viewModel::fetchModels,
onProbeChat = viewModel::probeChat,
onAddManualModel = viewModel::openManualModelDialog,
onToggleCapability = viewModel::toggleCapability,
onDeleteModel = viewModel::deleteModel,
onDefaultChat = viewModel::setDefaultChatModel,
onDefaultImageGen = viewModel::setDefaultImageGenModel,
onDefaultImageEdit = viewModel::setDefaultImageEditModel,
)
}
state.probeResult?.let { report ->
AlertDialog(
onDismissRequest = viewModel::dismissProbeResult,
title = { Text(stringResource(R.string.settings_probe_chat_title)) },
text = {
Text(
text = report,
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 420.dp)
.verticalScroll(rememberScrollState()),
style = MaterialTheme.typography.bodySmall,
)
},
confirmButton = {
TextButton(
onClick = {
clipboard.setText(AnnotatedString(report))
viewModel.dismissProbeResult()
},
) {
Text("复制并关闭")
}
},
dismissButton = {
TextButton(onClick = viewModel::dismissProbeResult) {
Text(stringResource(R.string.settings_probe_chat_close))
}
},
)
}
state.editor?.let { draft ->
ProviderEditorDialog(
draft = draft,
isSaving = state.isSaving,
onDismiss = viewModel::dismissEditor,
onChange = viewModel::updateEditor,
onSave = viewModel::saveProvider,
)
}
if (state.manualModelProviderId != null) {
ManualModelDialog(
modelId = state.manualModelIdInput,
onModelIdChange = viewModel::onManualModelIdChange,
onDismiss = viewModel::dismissManualModelDialog,
onConfirm = viewModel::confirmManualModel,
)
}
}
@Composable
private fun SettingsContent(
state: SettingsUiState,
contentPadding: PaddingValues,
onSearchChange: (String) -> Unit,
onToggleExpand: (Long) -> Unit,
onEditProvider: (Provider) -> Unit,
onDeleteProvider: (Long) -> Unit,
onEnabledChange: (Long, Boolean) -> Unit,
onFetchModels: (Long) -> Unit,
onProbeChat: (Long) -> Unit,
onAddManualModel: (Long) -> Unit,
onToggleCapability: (AiModel, ModelCapability) -> Unit,
onDeleteModel: (Long) -> Unit,
onDefaultChat: (Long?) -> Unit,
onDefaultImageGen: (Long?) -> Unit,
onDefaultImageEdit: (Long?) -> Unit,
) {
val allModels = state.providers.flatMap { it.second }
val query = state.searchQuery.trim()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(
start = 16.dp,
end = 16.dp,
top = contentPadding.calculateTopPadding() + 8.dp,
bottom = contentPadding.calculateBottomPadding() + 24.dp,
),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item {
DefaultModelsSection(
models = allModels,
defaultsChat = state.defaults.chatModelRowId,
defaultsImageGen = state.defaults.imageGenModelRowId,
defaultsImageEdit = state.defaults.imageEditModelRowId,
onDefaultChat = onDefaultChat,
onDefaultImageGen = onDefaultImageGen,
onDefaultImageEdit = onDefaultImageEdit,
)
}
item {
OutlinedTextField(
value = state.searchQuery,
onValueChange = onSearchChange,
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text(stringResource(R.string.settings_search_models)) },
)
}
if (state.providers.isEmpty()) {
item {
Text(
text = stringResource(R.string.settings_empty_providers),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 24.dp),
)
}
}
items(state.providers, key = { it.first.id }) { (provider, models) ->
val filtered = if (query.isEmpty()) {
models
} else {
models.filter {
it.modelId.contains(query, ignoreCase = true) ||
it.displayName.contains(query, ignoreCase = true)
}
}
ProviderCard(
provider = provider,
models = filtered,
expanded = provider.id in state.expandedProviderIds || query.isNotEmpty(),
fetching = state.fetchingProviderId == provider.id,
probing = state.probingProviderId == provider.id,
defaults = state.defaults,
onToggleExpand = { onToggleExpand(provider.id) },
onEdit = { onEditProvider(provider) },
onDelete = { onDeleteProvider(provider.id) },
onEnabledChange = { onEnabledChange(provider.id, it) },
onFetchModels = { onFetchModels(provider.id) },
onProbeChat = { onProbeChat(provider.id) },
onAddManualModel = { onAddManualModel(provider.id) },
onToggleCapability = onToggleCapability,
onDeleteModel = onDeleteModel,
)
}
}
}
@Composable
private fun DefaultModelsSection(
models: List<AiModel>,
defaultsChat: Long?,
defaultsImageGen: Long?,
defaultsImageEdit: Long?,
onDefaultChat: (Long?) -> Unit,
onDefaultImageGen: (Long?) -> Unit,
onDefaultImageEdit: (Long?) -> Unit,
) {
// Prefer capability-matched models, but always fall back so dropdowns stay usable.
val chatModels = models
.filter { it.isSuitableForChat() }
.ifEmpty { models.filterNot { com.omnichat.app.domain.model.isImagesApiOnlyModel(it.modelId) } }
.ifEmpty { models }
val imageGenModels = models
.filter {
ModelCapability.IMAGE_GEN in it.capabilities ||
com.omnichat.app.domain.model.isImagesApiOnlyModel(it.modelId)
}
.ifEmpty { models }
val imageEditModels = models
.filter {
ModelCapability.IMAGE_EDIT in it.capabilities ||
ModelCapability.IMAGE_GEN in it.capabilities ||
com.omnichat.app.domain.model.isImagesApiOnlyModel(it.modelId)
}
.ifEmpty { models }
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(R.string.settings_defaults_title),
style = MaterialTheme.typography.titleMedium,
)
if (models.isEmpty()) {
Text(
text = stringResource(R.string.settings_defaults_need_models),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
ModelDropdown(
label = stringResource(R.string.settings_default_chat),
models = chatModels,
allModels = models,
selectedId = defaultsChat,
onSelect = onDefaultChat,
)
ModelDropdown(
label = stringResource(R.string.settings_default_image_gen),
models = imageGenModels,
allModels = models,
selectedId = defaultsImageGen,
onSelect = onDefaultImageGen,
)
ModelDropdown(
label = stringResource(R.string.settings_default_image_edit),
models = imageEditModels,
allModels = models,
selectedId = defaultsImageEdit,
onSelect = onDefaultImageEdit,
)
}
}
@Composable
private fun ModelDropdown(
label: String,
models: List<AiModel>,
allModels: List<AiModel>,
selectedId: Long?,
onSelect: (Long?) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val selectedLabel = allModels.firstOrNull { it.id == selectedId }?.let {
"${it.displayName} (${it.modelId})"
} ?: stringResource(R.string.settings_none)
Box(modifier = Modifier.fillMaxWidth()) {
OutlinedTextField(
value = selectedLabel,
onValueChange = {},
readOnly = true,
label = { Text(label) },
modifier = Modifier.fillMaxWidth(),
enabled = false,
colors = OutlinedTextFieldDefaults.colors(
disabledTextColor = MaterialTheme.colorScheme.onSurface,
disabledBorderColor = MaterialTheme.colorScheme.outline,
disabledLabelColor = MaterialTheme.colorScheme.onSurfaceVariant,
),
)
// matchParentSize keeps the hit target aligned to the field (fillMaxSize breaks in LazyColumn).
Box(
modifier = Modifier
.matchParentSize()
.clickable { expanded = true },
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.settings_none)) },
onClick = {
onSelect(null)
expanded = false
},
)
if (models.isEmpty()) {
DropdownMenuItem(
text = {
Text(
stringResource(R.string.settings_defaults_need_models),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
onClick = { expanded = false },
enabled = false,
)
}
models.forEach { model ->
DropdownMenuItem(
text = {
Text(
text = "${model.displayName} (${model.modelId})",
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
onClick = {
onSelect(model.id)
expanded = false
},
)
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ProviderCard(
provider: Provider,
models: List<AiModel>,
expanded: Boolean,
fetching: Boolean,
probing: Boolean,
defaults: com.omnichat.app.data.local.datastore.DefaultModelRefs,
onToggleExpand: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit,
onEnabledChange: (Boolean) -> Unit,
onFetchModels: () -> Unit,
onProbeChat: () -> Unit,
onAddManualModel: () -> Unit,
onToggleCapability: (AiModel, ModelCapability) -> Unit,
onDeleteModel: (Long) -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onToggleExpand),
) {
Icon(
imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
contentDescription = null,
)
Column(
modifier = Modifier
.weight(1f)
.padding(start = 8.dp),
) {
Text(provider.name, style = MaterialTheme.typography.titleMedium)
Text(
text = provider.baseUrl,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "Key: ${provider.apiKeyMasked}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(checked = provider.isEnabled, onCheckedChange = onEnabledChange)
}
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onEdit) {
Text(stringResource(R.string.settings_edit))
}
TextButton(onClick = onFetchModels, enabled = !fetching && provider.isEnabled) {
if (fetching) {
CircularProgressIndicator(
modifier = Modifier
.padding(end = 8.dp)
.size(16.dp),
strokeWidth = 2.dp,
)
}
Text(stringResource(R.string.settings_fetch_models))
}
TextButton(
onClick = onProbeChat,
enabled = !probing && !fetching && provider.isEnabled,
) {
if (probing) {
CircularProgressIndicator(
modifier = Modifier
.padding(end = 8.dp)
.size(16.dp),
strokeWidth = 2.dp,
)
}
Text(stringResource(R.string.settings_probe_chat))
}
TextButton(onClick = onAddManualModel) {
Text(stringResource(R.string.settings_add_manual_model))
}
IconButton(onClick = onDelete) {
Icon(Icons.Default.Delete, contentDescription = stringResource(R.string.settings_delete))
}
}
if (expanded) {
if (models.isEmpty()) {
Text(
text = stringResource(R.string.settings_no_models),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 32.dp, bottom = 8.dp),
)
} else {
models.forEach { model ->
ModelRow(
model = model,
isDefaultChat = defaults.chatModelRowId == model.id,
isDefaultImageGen = defaults.imageGenModelRowId == model.id,
isDefaultImageEdit = defaults.imageEditModelRowId == model.id,
onToggleCapability = { onToggleCapability(model, it) },
onDelete = { onDeleteModel(model.id) },
)
HorizontalDivider()
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ModelRow(
model: AiModel,
isDefaultChat: Boolean,
isDefaultImageGen: Boolean,
isDefaultImageEdit: Boolean,
onToggleCapability: (ModelCapability) -> Unit,
onDelete: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(start = 24.dp, top = 8.dp, bottom = 8.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(model.displayName, style = MaterialTheme.typography.bodyLarge)
Text(
text = model.modelId,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (model.isManual) {
AssistChip(
onClick = {},
label = { Text(stringResource(R.string.settings_manual_tag)) },
enabled = false,
)
}
IconButton(onClick = onDelete) {
Icon(Icons.Default.Delete, contentDescription = stringResource(R.string.settings_delete))
}
}
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
ModelCapability.entries.forEach { capability ->
FilterChip(
selected = capability in model.capabilities,
onClick = { onToggleCapability(capability) },
label = { Text(capability.label()) },
)
}
}
val defaultTags = buildList {
if (isDefaultChat) add("默认对话")
if (isDefaultImageGen) add("默认文生图")
if (isDefaultImageEdit) add("默认图生图")
}
if (defaultTags.isNotEmpty()) {
Text(
text = defaultTags.joinToString(" · "),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
@Composable
private fun ProviderEditorDialog(
draft: ProviderDraft,
isSaving: Boolean,
onDismiss: () -> Unit,
onChange: ((ProviderDraft) -> ProviderDraft) -> Unit,
onSave: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = {
Text(
if (draft.id == null) stringResource(R.string.settings_add_provider)
else stringResource(R.string.settings_edit),
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = draft.name,
onValueChange = { value -> onChange { it.copy(name = value) } },
label = { Text(stringResource(R.string.settings_provider_name)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = draft.baseUrl,
onValueChange = { value -> onChange { it.copy(baseUrl = value) } },
label = { Text(stringResource(R.string.settings_base_url)) },
supportingText = { Text(stringResource(R.string.settings_base_url_hint)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = draft.apiKey,
onValueChange = { value -> onChange { it.copy(apiKey = value) } },
label = { Text(stringResource(R.string.settings_api_key)) },
supportingText = {
if (draft.id != null) {
Text(stringResource(R.string.settings_api_key_keep))
}
},
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier.fillMaxWidth(),
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(stringResource(R.string.settings_enabled))
Switch(
checked = draft.isEnabled,
onCheckedChange = { checked -> onChange { it.copy(isEnabled = checked) } },
)
}
}
},
confirmButton = {
TextButton(onClick = onSave, enabled = !isSaving) {
Text(stringResource(R.string.settings_save))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.settings_cancel))
}
},
)
}
@Composable
private fun ManualModelDialog(
modelId: String,
onModelIdChange: (String) -> Unit,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.settings_manual_model_title)) },
text = {
OutlinedTextField(
value = modelId,
onValueChange = onModelIdChange,
label = { Text(stringResource(R.string.settings_model_id)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
},
confirmButton = {
TextButton(onClick = onConfirm, enabled = modelId.isNotBlank()) {
Text(stringResource(R.string.settings_save))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.settings_cancel))
}
},
)
}
@@ -0,0 +1,27 @@
package com.omnichat.app.ui.theme
import androidx.compose.ui.graphics.Color
val TealPrimary = Color(0xFF1B6B5A)
val TealOnPrimary = Color(0xFFFFFFFF)
val TealPrimaryContainer = Color(0xFFC8EDE3)
val TealOnPrimaryContainer = Color(0xFF00201A)
val TealSecondary = Color(0xFF4A635C)
val TealOnSecondary = Color(0xFFFFFFFF)
val TealSecondaryContainer = Color(0xFFCCE8E0)
val TealOnSecondaryContainer = Color(0xFF06201A)
val LightBackground = Color(0xFFF5FBF8)
val LightOnBackground = Color(0xFF171D1B)
val LightSurface = Color(0xFFF5FBF8)
val LightOnSurface = Color(0xFF171D1B)
val DarkBackground = Color(0xFF0F1412)
val DarkOnBackground = Color(0xFFDEE4E1)
val DarkSurface = Color(0xFF0F1412)
val DarkOnSurface = Color(0xFFDEE4E1)
val DarkPrimary = Color(0xFFA8D0C4)
val DarkOnPrimary = Color(0xFF00382E)
val DarkPrimaryContainer = Color(0xFF005144)
val DarkOnPrimaryContainer = Color(0xFFC8EDE3)
@@ -0,0 +1,61 @@
package com.omnichat.app.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val LightColorScheme = lightColorScheme(
primary = TealPrimary,
onPrimary = TealOnPrimary,
primaryContainer = TealPrimaryContainer,
onPrimaryContainer = TealOnPrimaryContainer,
secondary = TealSecondary,
onSecondary = TealOnSecondary,
secondaryContainer = TealSecondaryContainer,
onSecondaryContainer = TealOnSecondaryContainer,
background = LightBackground,
onBackground = LightOnBackground,
surface = LightSurface,
onSurface = LightOnSurface,
)
private val DarkColorScheme = darkColorScheme(
primary = DarkPrimary,
onPrimary = DarkOnPrimary,
primaryContainer = DarkPrimaryContainer,
onPrimaryContainer = DarkOnPrimaryContainer,
secondary = TealSecondaryContainer,
onSecondary = TealOnSecondaryContainer,
background = DarkBackground,
onBackground = DarkOnBackground,
surface = DarkSurface,
onSurface = DarkOnSurface,
)
@Composable
fun OmniChatTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content,
)
}
@@ -0,0 +1,40 @@
package com.omnichat.app.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
val Typography = Typography(
headlineMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
fontSize = 28.sp,
lineHeight = 36.sp,
),
titleLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
fontSize = 22.sp,
lineHeight = 28.sp,
),
bodyLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
),
bodyMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
),
labelLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
lineHeight = 20.sp,
),
)
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#1B6B5A"
android:pathData="M30,34h48a8,8 0 0 1 8,8v24a8,8 0 0 1 -8,8H54l-12,10v-10H30a8,8 0 0 1 -8,-8V42a8,8 0 0 1 8,-8z" />
<path
android:fillColor="#E8F5F1"
android:pathData="M40,48h28v4H40zM40,58h20v4H40z" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#0F2E28</color>
</resources>
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OmniChat</string>
<string name="tab_chat">对话</string>
<string name="tab_image">生图</string>
<string name="tab_settings">设置</string>
<string name="image_title">智能生图</string>
<string name="image_prompt">提示词</string>
<string name="image_prompt_hint">描述你想生成或编辑的图像(原文直传,不会被二次改写)</string>
<string name="image_model">生图模型</string>
<string name="image_add_ref">添加参考图</string>
<string name="image_use_as_ref">用作参考</string>
<string name="image_use_as_ref_done">已加入参考图,改提示词后可继续编辑</string>
<string name="image_ref_already">该图已在参考图中</string>
<string name="image_ref_limit">参考图最多 4 张,请先移除再添加</string>
<string name="image_ref_hint">有参考图时:Images API 走 /images/edits;多模态模型走 chat completions</string>
<string name="image_generate">开始生成</string>
<string name="image_generating">正在生成…</string>
<string name="image_gallery">生成结果</string>
<string name="image_delete_result">删除</string>
<string name="image_deleted">已删除该记录</string>
<string name="image_save_gallery">保存到相册</string>
<string name="image_preview">预览</string>
<string name="image_preview_hint">双指缩放 · 单击关闭 / 复位</string>
<string name="image_route_a">路由 A:Images API(generations / edits)</string>
<string name="image_route_b">路由 B:多模态 Chat Completions</string>
<string name="image_generating_notification">正在生成图像…</string>
<string name="image_fg_channel_name">图像生成</string>
<string name="image_fg_channel_desc">生图任务进行中时保持连接</string>
<string name="chat_image_mode">生图模式</string>
<string name="settings_title">服务商与模型</string>
<string name="settings_add_provider">添加服务商</string>
<string name="settings_search_models">搜索模型</string>
<string name="settings_defaults_title">默认模型</string>
<string name="settings_defaults_need_models">请先展开服务商并拉取模型,再来指定默认项</string>
<string name="settings_default_chat">默认对话</string>
<string name="settings_default_image_gen">默认文生图</string>
<string name="settings_default_image_edit">默认图生图</string>
<string name="settings_none">未指定</string>
<string name="settings_fetch_models">拉取模型</string>
<string name="settings_probe_chat">测试对话</string>
<string name="settings_probe_chat_title">对话诊断</string>
<string name="settings_probe_chat_close">关闭</string>
<string name="settings_add_manual_model">手动添加</string>
<string name="settings_edit">编辑</string>
<string name="settings_delete">删除</string>
<string name="settings_enabled">启用</string>
<string name="settings_provider_name">名称</string>
<string name="settings_base_url">Base URL</string>
<string name="settings_base_url_hint">例如 https://api.example.com 或 …/v1</string>
<string name="settings_api_key">API Key</string>
<string name="settings_api_key_keep">留空则保留原 Key</string>
<string name="settings_save">保存</string>
<string name="settings_cancel">取消</string>
<string name="settings_manual_model_title">手动添加模型</string>
<string name="settings_model_id">模型 ID</string>
<string name="settings_empty_providers">还没有服务商,点右上角添加</string>
<string name="settings_no_models">暂无模型,可拉取或手动添加</string>
<string name="settings_manual_tag">手动</string>
<string name="chat_title">对话</string>
<string name="chat_sessions">会话</string>
<string name="chat_new">新对话</string>
<string name="chat_input_hint">输入消息…</string>
<string name="chat_send">发送</string>
<string name="chat_stop">停止</string>
<string name="chat_attach_image">添加图片</string>
<string name="chat_compress_on">智能压缩</string>
<string name="chat_compress_off">原图上传</string>
<string name="chat_context_window">上下文轮数:%1$d</string>
<string name="chat_need_default_model">请先到「设置」配置服务商并指定默认对话模型</string>
</resources>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.OmniChat" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- Allow cleartext for local / custom OpenAI-compatible gateways during development. -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
+7
View File
@@ -0,0 +1,7 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.ksp) apply false
}
+8
View File
@@ -0,0 +1,8 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.parallel=true
android.useAndroidX=true
kotlin.code.style=official
android.nonTransitiveRClass=true
# Enabled parallel sync for Gradle 9.4+
org.gradle.tooling.parallel=true
+60
View File
@@ -0,0 +1,60 @@
[versions]
agp = "8.7.3"
kotlin = "2.0.21"
ksp = "2.0.21-1.0.28"
coreKtx = "1.15.0"
lifecycle = "2.8.7"
activityCompose = "1.9.3"
composeBom = "2024.12.01"
navigationCompose = "2.8.5"
okhttp = "4.12.0"
retrofit = "2.11.0"
retrofitSerialization = "1.0.0"
kotlinxSerialization = "1.7.3"
room = "2.6.1"
datastore = "1.1.1"
securityCrypto = "1.0.0"
coil = "3.0.4"
coroutines = "1.9.0"
markwon = "4.6.2"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-material-icons = { group = "androidx.compose.material", name = "material-icons-extended" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
okhttp-sse = { group = "com.squareup.okhttp3", name = "okhttp-sse", version.ref = "okhttp" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-kotlinx-serialization = { group = "com.jakewharton.retrofit", name = "retrofit2-kotlinx-serialization-converter", version.ref = "retrofitSerialization" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }
androidx-security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCrypto" }
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
coil-network-okhttp = { group = "io.coil-kt.coil3", name = "coil-network-okhttp", version.ref = "coil" }
markwon-core = { group = "io.noties.markwon", name = "core", version.ref = "markwon" }
markwon-ext-strikethrough = { group = "io.noties.markwon", name = "ext-strikethrough", version.ref = "markwon" }
markwon-linkify = { group = "io.noties.markwon", name = "linkify", version.ref = "markwon" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.11.1-bin.zip
networkTimeout=120000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+37
View File
@@ -0,0 +1,37 @@
@rem Gradle start-up script for Windows
@if "%DEBUG%"=="" @echo off
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
exit /b 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
exit /b 1
:execute
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@endlocal & exit /b %ERRORLEVEL%
+24
View File
@@ -0,0 +1,24 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "OmniChat"
include(":app")