Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/SettingsScreen.swift3// Description: Settings root (sidebar on wide layouts, pushed list on iPhone) with the General, Privacy & Security, Storage and About panes.4import SwiftUI5import LocalChatCore6import LocalChatSecurity78enum SettingsPane: String, CaseIterable, Identifiable, Hashable {9 case general, privacy, nodes, server, sync, storage, about10 var id: String { rawValue }11 var title: String {12 switch self {13 case .general: "General"; case .privacy: "Privacy & Security"; case .nodes: "Remote nodes"; case .server: "Local API server"14 case .sync: "Sync"; case .storage: "Storage"; case .about: "About"15 }16 }17 var subtitle: String {18 switch self {19 case .general: "Appearance, defaults and chat behaviour"20 case .privacy: "App lock and what leaves this device"21 case .nodes: "Trusted Macs and OpenAI-compatible servers"22 case .server: "Serve your models to other apps and devices"23 case .sync: "End-to-end encrypted, optional"24 case .storage: "Disk usage and clean-up"25 case .about: "Version, engines and limitations"26 }27 }28 var symbol: String {29 switch self {30 case .general: "slider.horizontal.3"; case .privacy: "lock.shield"; case .nodes: "network"; case .server: "server.rack"31 case .sync: "arrow.triangle.2.circlepath"; case .storage: "internaldrive"; case .about: "info.circle"32 }33 }34}3536public struct SettingsScreen: View {37 @Environment(AppModel.self) private var app38 @Environment(\.horizontalSizeClass) private var sizeClass39 @State private var selection: SettingsPane = .general40 public init() {}4142 private var isWide: Bool { Platform.isMac || sizeClass == .regular }4344 public var body: some View {45 Group {46 if isWide {47 HStack(spacing: 0) {48 ScrollView {49 VStack(alignment: .leading, spacing: 4) {50 Text("Settings").font(DS.F.title).foregroundStyle(DS.C.text).padding(.horizontal, 10).padding(.bottom, 8)51 ForEach(SettingsPane.allCases) { pane in52 Button { selection = pane } label: { row(pane, selected: selection == pane, compact: true) }.buttonStyle(.plain)53 .accessibilityAddTraits(selection == pane ? .isSelected : [])54 }55 }56 .padding(DS.S.md)57 }58 .frame(width: 232).background(DS.C.surface)59 Rectangle().fill(DS.C.border).frame(width: 1)60 paneScroll(selection)61 }62 } else {63 NavigationStack {64 ScrollView {65 VStack(spacing: 8) {66 ForEach(SettingsPane.allCases) { pane in67 NavigationLink(value: pane) { row(pane, selected: false, compact: false) }.buttonStyle(.plain)68 }69 }70 .padding(DS.S.lg)71 }72 .screenBackground()73 .navigationTitle("Settings")74 .navigationDestination(for: SettingsPane.self) { pane in75 paneScroll(pane).navigationTitle(pane.title)76 #if os(iOS)77 .navigationBarTitleDisplayMode(.inline)78 #endif79 }80 }81 }82 }83 .screenBackground()84 }8586 private func row(_ pane: SettingsPane, selected: Bool, compact: Bool) -> some View {87 HStack(spacing: 10) {88 Image(systemName: pane.symbol).font(.system(size: compact ? 13 : 16, weight: .medium))89 .foregroundStyle(selected ? AnyShapeStyle(.white) : AnyShapeStyle(DS.G.accent)).frame(width: compact ? 22 : 30)90 VStack(alignment: .leading, spacing: 1) {91 Text(pane.title).font(compact ? DS.F.callout : DS.F.headline).foregroundStyle(selected ? .white : DS.C.text)92 if !compact { Text(pane.subtitle).font(DS.F.caption).foregroundStyle(DS.C.muted) }93 }94 Spacer(minLength: 0)95 if !compact { Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(DS.C.muted) }96 }97 .padding(.horizontal, compact ? 10 : 14).padding(.vertical, compact ? 7 : 12)98 .background {99 if compact { RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).fill(selected ? AnyShapeStyle(DS.G.accent) : AnyShapeStyle(Color.clear)) }100 else { RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).fill(DS.C.surface).overlay(RoundedRectangle(cornerRadius: DS.R.card, style: .continuous).strokeBorder(DS.C.border)) }101 }102 .contentShape(Rectangle())103 }104105 private func paneScroll(_ pane: SettingsPane) -> some View {106 ScrollView {107 VStack(alignment: .leading, spacing: DS.S.lg) {108 if isWide { ScreenTitle(pane.title, subtitle: pane.subtitle) }109 switch pane {110 case .general: GeneralPane()111 case .privacy: PrivacyPane()112 case .nodes: NodesPane()113 case .server: ServerPane()114 case .sync: SyncPane()115 case .storage: StoragePane()116 case .about: AboutPane()117 }118 }119 .padding(isWide ? DS.S.xl : DS.S.lg)120 .frame(maxWidth: 860, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)121 }122 .screenBackground()123 }124}125126/// A titled card grouping setting rows.127struct SettingsGroup<Content: View>: View {128 let title: String; var symbol: String?; var footer: String?; @ViewBuilder var content: Content129 init(_ title: String, symbol: String? = nil, footer: String? = nil, @ViewBuilder content: () -> Content) { self.title = title; self.symbol = symbol; self.footer = footer; self.content = content() }130 var body: some View {131 VStack(alignment: .leading, spacing: 10) {132 SectionHeader(title, symbol: symbol)133 VStack(alignment: .leading, spacing: 8) { content }134 if let footer { Text(footer).font(DS.F.caption).foregroundStyle(DS.C.muted).fixedSize(horizontal: false, vertical: true) }135 }136 .frame(maxWidth: .infinity, alignment: .leading).card()137 }138}139140struct RowDivider: View { var body: some View { Rectangle().fill(DS.C.border).frame(height: 1) } }141142// MARK: General143144struct GeneralPane: View {145 @Environment(AppModel.self) private var app146 @State private var systemPrompt = ""147 @State private var loaded = false148 static let accents = ["indigo", "violet", "teal", "orange", "pink", "green"]149150 private func binding<T: Equatable>(_ keyPath: WritableKeyPath<AppPreferences, T>) -> Binding<T> {151 Binding(get: { app.preferences[keyPath: keyPath] }, set: { v in app.updatePreferences { $0[keyPath: keyPath] = v } })152 }153 private var keepMode: Binding<Int> {154 Binding(get: { let m = app.preferences.keepModelLoadedMinutes; return m < 0 ? -1 : (m == 0 ? 0 : 1) },155 set: { v in app.updatePreferences { $0.keepModelLoadedMinutes = v == 1 ? max(5, $0.keepModelLoadedMinutes) : v } })156 }157158 var body: some View {159 SettingsGroup("Appearance", symbol: "paintbrush") {160 SettingRow("Theme") {161 Picker("Theme", selection: binding(\.appearance)) { Text("System").tag("system"); Text("Light").tag("light"); Text("Dark").tag("dark") }162 .pickerStyle(.segmented).labelsHidden().frame(maxWidth: 240)163 }164 RowDivider()165 SettingRow("Accent") {166 Picker("Accent", selection: binding(\.accent)) { ForEach(Self.accents, id: \.self) { Text($0.capitalized).tag($0) } }.labelsHidden().frame(maxWidth: 160)167 }168 }169 SettingsGroup("New conversations", symbol: "bubble.left.and.text.bubble.right") {170 SettingRow("Default preset", detail: app.preferences.defaultPreset.summary) {171 Picker("Default preset", selection: binding(\.defaultPreset)) { ForEach(InferencePreset.allCases) { Text($0.title).tag($0) } }.labelsHidden().frame(maxWidth: 190)172 }173 RowDivider()174 VStack(alignment: .leading, spacing: 6) {175 Text("Default system prompt").font(DS.F.body).foregroundStyle(DS.C.text)176 TextEditor(text: $systemPrompt).font(DS.F.callout).frame(minHeight: 84).scrollContentBackground(.hidden).padding(6)177 .background(DS.C.surface2, in: RoundedRectangle(cornerRadius: DS.R.control, style: .continuous))178 .overlay(RoundedRectangle(cornerRadius: DS.R.control, style: .continuous).strokeBorder(DS.C.border))179 .accessibilityLabel("Default system prompt")180 .onChange(of: systemPrompt) { _, new in if loaded { app.updatePreferences { $0.defaultSystemPrompt = new } } }181 Text("Used by new conversations. Existing conversations keep their own prompt.").font(DS.F.caption).foregroundStyle(DS.C.muted)182 }183 }184 SettingsGroup("Chat", symbol: "text.bubble") {185 SettingRow("Name conversations automatically", detail: "Titles are written by on-device models only.") { Toggle("", isOn: binding(\.autoTitle)).labelsHidden() }186 RowDivider()187 SettingRow("Send with Return", detail: "Shift-Return inserts a new line.") { Toggle("", isOn: binding(\.sendWithReturn)).labelsHidden() }188 RowDivider()189 SettingRow("Show measured metrics under answers", detail: "Tokens per second, time to first token, memory.") { Toggle("", isOn: binding(\.showMetricsInChat)).labelsHidden() }190 #if os(iOS)191 RowDivider()192 SettingRow("Haptics") { Toggle("", isOn: binding(\.hapticsEnabled)).labelsHidden() }193 #endif194 }195 SettingsGroup("Memory", symbol: "memorychip", footer: "Keeping a model loaded makes the next answer start at once; unloading frees memory for other apps.") {196 SettingRow("Keep the model loaded") {197 Picker("Keep the model loaded", selection: keepMode) {198 Text("Until quit").tag(-1); Text("For a while").tag(1); Text("Unload after each answer").tag(0)199 }.labelsHidden().frame(maxWidth: 230)200 }201 if app.preferences.keepModelLoadedMinutes > 0 {202 RowDivider()203 SettingRow("Unload after", detail: "\(app.preferences.keepModelLoadedMinutes) minutes without use") {204 Stepper("", value: binding(\.keepModelLoadedMinutes), in: 1...240, step: 5).labelsHidden()205 }206 }207 }208 .onAppear { systemPrompt = app.preferences.defaultSystemPrompt; loaded = true }209 }210}211212// MARK: Privacy & Security213214struct PrivacyPane: View {215 @Environment(AppModel.self) private var app216 @State private var working = false217 @State private var message: String?218219 var body: some View {220 let availability = app.lock.availability221 SettingsGroup("App lock", symbol: availability.biometry.symbol) {222 SettingRow("Require \(availability.biometry.label) to open Local Chat",223 detail: availability.available ? "Locks at launch and after a minute in the background." : (availability.reason ?? "No passcode or biometrics are set up on this device.")) {224 Toggle("", isOn: Binding(get: { app.preferences.appLockEnabled }, set: { setLock($0) })).labelsHidden().disabled(working || (!availability.available && !app.preferences.appLockEnabled))225 }226 if let message { InlineNotice(.warning, message) }227 }228 SettingsGroup("What leaves this device", symbol: "lock.shield") {229 InlineNotice(.privacy, "By default, nothing. Conversations, documents, embeddings and models stay on this device, and inference runs locally.")230 fact("shippingbox", "Hugging Face", "Contacted only when you browse or download models. Your conversations are never sent there.")231 fact("network", "Remote nodes", app.nodeStatuses.isEmpty ? "None configured. A prompt goes to a remote node only when you pick one of its models, and the answer is labelled as remote."232 : "\(app.nodeStatuses.count) configured. A prompt goes to a node only when you pick one of its models (or allow the router to); the answer is labelled as remote.")233 fact("arrow.triangle.2.circlepath", "Sync", app.sync.isEnabled ? "On. Records are encrypted on this device before they leave it; the destination cannot read them." : "Off. Nothing is synchronized.")234 fact("server.rack", "Local API server", app.server.isRunning ? "Running. Other programs can use your models through it." : "Stopped.")235 fact("key", "Secrets", "API keys, tokens and the sync key are stored in the system Keychain, never in files or logs.")236 }237 }238239 private func fact(_ symbol: String, _ title: String, _ text: String) -> some View {240 HStack(alignment: .top, spacing: 10) {241 Image(systemName: symbol).foregroundStyle(DS.C.accent).frame(width: 20)242 VStack(alignment: .leading, spacing: 2) {243 Text(title).font(DS.F.body.weight(.medium)).foregroundStyle(DS.C.text)244 Text(text).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)245 }246 }247 .padding(.vertical, 3)248 }249250 private func setLock(_ on: Bool) {251 message = nil252 guard on else { app.lock.isEnabled = false; app.updatePreferences { $0.appLockEnabled = false }; return }253 working = true254 Task {255 let ok = await app.lock.enable()256 working = false257 if ok { app.updatePreferences { $0.appLockEnabled = true } } else { message = "The lock was not turned on: authentication did not succeed." }258 }259 }260}261262// MARK: Storage263264struct StoragePane: View {265 @Environment(AppModel.self) private var app266 @State private var models: Int64?267 @State private var conversations: Int64 = 0268 @State private var knowledge: Int64 = 0269 @State private var metrics: Int64 = 0270 @State private var attachments: Int64 = 0271 @State private var note: String?272 @State private var confirmReset = false273274 var body: some View {275 TileGrid(minimum: 150) {276 MetricTile("Models", value: MetricFormat.bytes(models), symbol: "shippingbox")277 MetricTile("Conversations", value: MetricFormat.bytes(conversations), symbol: "bubble.left.and.bubble.right", tint: DS.C.accent2)278 MetricTile("Knowledge", value: MetricFormat.bytes(knowledge), symbol: "books.vertical", tint: DS.C.accent3)279 MetricTile("Attachments", value: MetricFormat.bytes(attachments), symbol: "paperclip", tint: DS.C.ok)280 MetricTile("Metrics history", value: MetricFormat.bytes(metrics), symbol: "chart.xyaxis.line", tint: DS.C.warn)281 MetricTile("Free on device", value: MetricFormat.bytes(app.device.storageFreeBytes), symbol: "internaldrive", tint: DS.C.muted)282 }283 .task { await measure() }284 SettingsGroup("Clean up", symbol: "sparkles") {285 SettingRow("Remove orphan attachments", detail: "Files no message refers to any more.") {286 Button("Remove") { purgeAttachments() }.buttonStyle(.lcSecondaryCompact)287 }288 RowDivider()289 SettingRow("Purge deletion markers", detail: "Forgets items deleted more than 30 days ago. Devices that have not synchronized since then may bring them back.") {290 Button("Purge") { purgeTombstones() }.buttonStyle(.lcSecondaryCompact)291 }292 RowDivider()293 SettingRow("Reset metrics history", detail: "Deletes every measured run. Model recommendations lose their measured speeds.") {294 Button("Reset…") { confirmReset = true }.buttonStyle(.lcDestructive)295 }296 if let note { InlineNotice(.info, note) }297 }298 .confirmationDialog("Delete every measured run?", isPresented: $confirmReset, titleVisibility: .visible) {299 Button("Reset metrics history", role: .destructive) { resetMetrics() }300 }301 Text(app.paths.root.path).font(DS.F.mono(11)).foregroundStyle(DS.C.muted).textSelection(.enabled)302 }303304 private func measure() async {305 app.refreshDevice()306 models = await app.library.diskUsage()307 let paths = app.paths308 let sizes = await Task.detached { (StorageMeter.database(paths.database), StorageMeter.database(paths.knowledgeDatabase), StorageMeter.database(paths.metricsDatabase), StorageMeter.directory(paths.attachments)) }.value309 (conversations, knowledge, metrics, attachments) = sizes310 }311 private func purgeAttachments() {312 guard let names = try? app.store.referencedAttachmentNames() else { note = "The attachment references could not be read; nothing was removed."; return }313 let n = app.attachments.removeOrphans(referenced: names)314 note = n == 0 ? "No orphan attachment was found." : "\(n) orphan attachment\(n == 1 ? "" : "s") removed."315 Task { await measure() }316 }317 private func purgeTombstones() {318 let n = (try? app.store.purgeTombstones(olderThan: Date().addingTimeInterval(-30 * 86_400))) ?? 0319 note = "\(n) deletion marker\(n == 1 ? "" : "s") purged."320 Task { await measure() }321 }322 private func resetMetrics() {323 let n = (try? app.metrics.prune(olderThan: .distantFuture)) ?? 0324 app.refreshMeasuredSpeed()325 note = "\(n) measured run\(n == 1 ? "" : "s") deleted."326 Task { await measure() }327 }328}329330enum StorageMeter {331 static func file(_ url: URL) -> Int64 { Int64((try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) }332 /// SQLite file plus its write-ahead log and shared-memory files.333 static func database(_ url: URL) -> Int64 { file(url) + file(URL(fileURLWithPath: url.path + "-wal")) + file(URL(fileURLWithPath: url.path + "-shm")) }334 static func directory(_ url: URL) -> Int64 {335 guard let walker = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey]) else { return 0 }336 var total: Int64 = 0337 while let item = walker.nextObject() as? URL {338 if let v = try? item.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]), v.isRegularFile == true { total += Int64(v.fileSize ?? 0) }339 }340 return total341 }342}343344// MARK: About345346struct AboutPane: View {347 @Environment(AppModel.self) private var app348 @State private var showLimitations = false349350 private var version: String {351 let info = Bundle.main.infoDictionary352 let v = info?["CFBundleShortVersionString"] as? String, b = info?["CFBundleVersion"] as? String353 return v.map { "\($0)" + (b.map { " (\($0))" } ?? "") } ?? "Development build"354 }355356 var body: some View {357 SettingsGroup("Local Chat", symbol: "bubble.left.and.bubble.right.fill") {358 line("Version", version)359 line("Device", [app.device.chip ?? app.device.machine, ByteFormat.memory(app.device.physicalMemoryBytes)].joined(separator: " · "))360 line("System", "\(Platform.isMac ? "macOS" : "iOS") \(app.device.osVersion)")361 }362 SettingsGroup("Inference engines", symbol: "cpu") {363 line("MLX", "MLX Swift LM 3.33 (MLX Swift 0.33)" + (app.backendIssues[.mlx].map { _ in " — unavailable here" } ?? ""))364 #if os(macOS)365 line("GGUF", "llama.cpp b12359 (Metal)")366 #else367 line("GGUF", "Not included on iOS in this version")368 #endif369 line("System model", app.systemModel == nil ? (app.backendIssues[.appleFoundation] ?? "Unavailable") : "Apple Intelligence (FoundationModels)")370 ForEach(app.backendIssues.sorted { $0.key.rawValue < $1.key.rawValue }, id: \.key) { kind, reason in371 if kind == .mlx || kind == .gguf { InlineNotice(.info, "\(kind.displayName): \(reason)") }372 }373 }374 SettingsGroup("Acknowledgements", symbol: "heart") {375 ForEach(Self.acknowledgements, id: \.0) { name, detail in line(name, detail) }376 }377 Button { showLimitations.toggle() } label: { Label(showLimitations ? "Hide known limitations" : "Known limitations", systemImage: "exclamationmark.bubble") }378 .buttonStyle(.lcSecondaryCompact)379 if showLimitations {380 Text(Self.limitations).font(DS.F.callout).foregroundStyle(DS.C.text2).textSelection(.enabled).fixedSize(horizontal: false, vertical: true).card()381 }382 }383384 private func line(_ title: String, _ value: String) -> some View {385 HStack(alignment: .firstTextBaseline) {386 Text(title).font(DS.F.callout).foregroundStyle(DS.C.muted).frame(width: 110, alignment: .leading)387 Text(value).font(DS.F.callout).foregroundStyle(DS.C.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)388 Spacer(minLength: 0)389 }390 }391392 static let acknowledgements: [(String, String)] = [393 ("MLX Swift", "Apple — MIT"), ("MLX Swift LM", "Apple — MIT"), ("llama.cpp", "ggml-org — MIT"), ("llama.swift", "Mattt — MIT"),394 ("swift-transformers", "Hugging Face — Apache 2.0"), ("swift-jinja", "Hugging Face — Apache 2.0"), ("GRDB.swift", "Gwendal Roué — MIT"),395 ("SwiftMath", "Mike Griebling — MIT"), ("swift-markdown", "Apple — Apache 2.0"),396 ]397398 static let limitations = """399 • MLX does not run in the iOS Simulator; on-device inference on iPhone and iPad needs a real device.400 • GGUF models (llama.cpp) run on the Mac only in this version. On iPhone and iPad use MLX models, or route to a Mac.401 • Not every architecture published on Hugging Face is implemented in MLX Swift; the Model Library says so before you download.402 • Memory needs shown before a download are estimates; the Observatory shows measured values once a model is loaded.403 • GGUF models have no vision or embedding support here; tool calls are recovered from text when the template allows it.404 • The Apple system model reports no token counts or throughput; only wall-clock times are measured for it.405 • The Local API server speaks plain HTTP. Keep it on this Mac or on a private network, with an API key.406 • Sync resolves conflicts with "last writer wins" per record. Documents of knowledge collections and model weights are not synchronized.407 • Titles and summaries are generated only by on-device models.408 """409}410