feat(AI): 添加MLX内存管理和AI模型互斥卸载机制 为防止应用因内存溢出被系统终止,在项目中添加了MLX框架依赖, 并在应用启动时配置GPU缓存限制,设置256MB缓存上限以避免内存过度使用。 同时实现了LLM和VL模型的互斥卸载机制,确保大模型不会同时常驻内存, 通过在加载一个模型前先卸载另一个模型来控制内存使用,防止jetsam OOM。 chore(project): 配置代码签名授权文件 refactor(localization): 调整本地化字符串并清理冗余条目 修正了提醒任务和建议相关的本地化文本,调整了多个UI字符串, 清理了过时和重复的本地化条目,更新了AI识别相关的新字符串资源。 ```
107 lines
4.9 KiB
Swift
107 lines
4.9 KiB
Swift
import SwiftUI
|
||
import SwiftData
|
||
|
||
@main
|
||
struct KangkangApp: App {
|
||
@State private var lang = LanguageManager.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)
|
||
.id(lang.current) // 语言切换 → 整树重建,即时生效
|
||
}
|
||
}
|
||
.modelContainer(sharedModelContainer)
|
||
}
|
||
}
|