feat(iOS): 更新MNN后端模型配置优化性能 将MNN主模型从Qwen3.5-4B(~2.64GiB)降级为Qwen3.5-2B(~1.1GiB),因为4B版本 实测运行过慢,影响用户体验。iPhone17+/SME2设备使用2B模型,保留MLX 兜底方案用于模拟器和备用场景,确保AI推理性能和存储效率的平衡。 ```
112 lines
5.4 KiB
Swift
112 lines
5.4 KiB
Swift
import SwiftUI
|
||
import SwiftData
|
||
|
||
@main
|
||
struct KangkangApp: App {
|
||
@State private var lang = LanguageManager.shared
|
||
@State private var fontScale = FontScaleManager.shared
|
||
|
||
init() {
|
||
// 启动即给 MLX 显存缓存设上限,配合 entitlement + LLM/VL 互斥卸载防 jetsam OOM。
|
||
AIRuntime.configureMLXMemory()
|
||
}
|
||
|
||
var sharedModelContainer: ModelContainer = {
|
||
let schema = Schema([
|
||
Indicator.self,
|
||
Report.self,
|
||
DiaryEntry.self,
|
||
Asset.self,
|
||
ChatTurn.self,
|
||
Symptom.self,
|
||
UserProfile.self,
|
||
MetricReminder.self,
|
||
CustomMonitorMetric.self,
|
||
HealthExport.self,
|
||
CustomReminder.self,
|
||
])
|
||
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
|
||
// 建库后给 store 文件补 .completeUnlessOpen 保护(§6),两条创建路径共用。
|
||
func makeContainer() throws -> ModelContainer {
|
||
let container = try ModelContainer(for: schema, configurations: [config])
|
||
KangkangApp.protectStore(at: config.url)
|
||
return container
|
||
}
|
||
do {
|
||
return try makeContainer()
|
||
} catch {
|
||
// Demo 阶段 schema 仍在演进:某次改动若超出 SwiftData 自动轻量迁移能力
|
||
// (最常见:给已存在的 @Model 新增「非可选且无内联默认值」的属性),自动迁移会抛错。
|
||
// 这里不再静默删库,而是把旧 store 连同 -wal/-shm 整体挪到带时间戳的备份目录后重建——
|
||
// 既保证 App 能启动,又让旧数据可手动恢复(挪不动才降级为删除)。
|
||
// ⚠️ 正式发布前仍应改为 VersionedSchema + SchemaMigrationPlan 的正式迁移。
|
||
// 注:新增 @Model 属性请一律给「可选」或「内联默认值」,即可走轻量迁移、不触发本兜底。
|
||
print("⚠️ ModelContainer 创建失败,备份旧 store 后重建: \(error)")
|
||
KangkangApp.backupIncompatibleStore(at: config.url)
|
||
do {
|
||
return try makeContainer()
|
||
} catch {
|
||
fatalError("Could not create ModelContainer even after store reset: \(error)")
|
||
}
|
||
}
|
||
}()
|
||
|
||
/// 给 SwiftData store(含 `-wal`/`-shm`)补 `.completeUnlessOpen` 文件保护:
|
||
/// 设备锁屏时静态加密,但已打开的库仍可读写——对运行中的 SQLite 安全,
|
||
/// 不用 `.complete` 以免锁屏时后台/Live Activity 访问 store 崩溃。对应 CLAUDE.md §6。
|
||
/// (默认未指定保护类时 iOS 仅给 CompleteUntilFirstUserAuthentication,这里升级一档。)
|
||
private static func protectStore(at storeURL: URL) {
|
||
let fm = FileManager.default
|
||
for suffix in ["", "-wal", "-shm"] {
|
||
let path = storeURL.path + suffix
|
||
guard fm.fileExists(atPath: path) else { continue }
|
||
try? fm.setAttributes([.protectionKey: FileProtectionType.completeUnlessOpen],
|
||
ofItemAtPath: path)
|
||
}
|
||
}
|
||
|
||
/// 把与新 schema 不兼容的旧 store(含 `-wal` / `-shm`)挪到
|
||
/// `Application Support/StoreBackups/<时间戳>/`,而不是直接删除。
|
||
/// 既清出路径让新库能建起来,又把旧数据留作可手动恢复的备份;挪不动时才降级为删除。
|
||
private static func backupIncompatibleStore(at storeURL: URL) {
|
||
let fm = FileManager.default
|
||
let fmt = DateFormatter()
|
||
fmt.locale = Locale(identifier: "en_US_POSIX")
|
||
fmt.dateFormat = "yyyyMMdd-HHmmss"
|
||
let stamp = fmt.string(from: Date())
|
||
let backupDir = storeURL.deletingLastPathComponent()
|
||
.appendingPathComponent("StoreBackups/\(stamp)", isDirectory: true)
|
||
try? fm.createDirectory(at: backupDir, withIntermediateDirectories: true)
|
||
// 备份副本同样要加密(否则等于把全量健康数据明文留在低保护目录)。
|
||
try? fm.setAttributes([.protectionKey: FileProtectionType.completeUnlessOpen],
|
||
ofItemAtPath: backupDir.path)
|
||
for suffix in ["", "-wal", "-shm"] {
|
||
let src = URL(fileURLWithPath: storeURL.path + suffix)
|
||
guard fm.fileExists(atPath: src.path) else { continue }
|
||
let dst = backupDir.appendingPathComponent(src.lastPathComponent)
|
||
do {
|
||
try fm.moveItem(at: src, to: dst)
|
||
try? fm.setAttributes([.protectionKey: FileProtectionType.completeUnlessOpen],
|
||
ofItemAtPath: dst.path)
|
||
} catch {
|
||
try? fm.removeItem(at: src) // 挪不动就删,至少保证能启动
|
||
}
|
||
}
|
||
}
|
||
|
||
var body: some Scene {
|
||
WindowGroup {
|
||
AppLockContainer {
|
||
RootView()
|
||
.environment(\.locale, lang.locale)
|
||
// 语言 / 字体档位切换 → 整树重建,即时生效(固定字号经 tjScaled 读新倍率)。
|
||
.id("\(lang.current.rawValue)-\(fontScale.scale.rawValue)")
|
||
}
|
||
// 设计系统是纯浅色(背景恒为 sand)。锁定 light:否则系统深色模式下,
|
||
// 未显式设色的 Text/TextField 走 .primary 变白,在浅背景上看不见(如日记输入框)。
|
||
.preferredColorScheme(.light)
|
||
}
|
||
.modelContainer(sharedModelContainer)
|
||
}
|
||
}
|