SPB Git

Repository Public MIT

SettingsLab.swift 28.1 KB 506 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Lab/SettingsLab.swift10// Module           : Lab11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import LocalAuthentication90import AstraCore91import AstraDesign92import AstraLocal93import AstraPersistence9495/// Settings and privacy: appearance, app lock, default generation parameters, and the doors to data controls and About.96struct SettingsLabView: View {97    enum Appearance: String, CaseIterable, Identifiable {98        case system, light, dark99        var id: String { rawValue }100        var title: String { rawValue.capitalized }101        var scheme: ColorScheme? { self == .light ? .light : self == .dark ? .dark : nil }102    }103104    @Environment(AppModel.self) private var app105    @State private var defaults = GenerationParameters()106    @State private var defaultsLoaded = false107    @State private var lockBusy = false108    @State private var lockMessage: String?109110    private var appearance: Binding<Appearance> {111        Binding(get: { app.appearance == .dark ? .dark : app.appearance == .light ? .light : .system },112                set: { new in Task { await app.setAppearance(new.scheme) } })113    }114115    var body: some View {116        LabPage(title: "Settings and privacy") {117            VStack(alignment: .leading, spacing: AstraSpace.md) {118                SectionTitle("Appearance")119                AstraCard {120                    Picker("Appearance", selection: appearance) { ForEach(Appearance.allCases) { Text($0.title).tag($0) } }121                        .pickerStyle(.segmented).accessibilityIdentifier("settings-appearance")122                }123            }124            VStack(alignment: .leading, spacing: AstraSpace.md) {125                SectionTitle("App lock")126                AstraCard {127                    VStack(alignment: .leading, spacing: AstraSpace.sm) {128                        Toggle(isOn: Binding(get: { app.appLockEnabled }, set: { setLock($0) })) {129                            VStack(alignment: .leading, spacing: AstraSpace.xxs) {130                                Text("Require Face ID or passcode").font(AstraFont.subheadline).foregroundStyle(AstraColor.textPrimary)131                                Text("Astra locks when it leaves the foreground and hides its content in the app switcher. It uses this iPhone's own authentication; Astra never sees your face, fingerprint or passcode.")132                                    .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)133                            }134                        }135                        .tint(AstraColor.accentFill).disabled(lockBusy)136                        .accessibilityIdentifier("settings-app-lock")137                        if let lockMessage { Label(lockMessage, systemImage: "exclamationmark.triangle.fill").font(AstraFont.caption).foregroundStyle(AstraColor.warning).fixedSize(horizontal: false, vertical: true) }138                    }139                }140            }141            VStack(alignment: .leading, spacing: AstraSpace.md) {142                SectionTitle("Defaults for new chats")143                AstraCard {144                    VStack(alignment: .leading, spacing: AstraSpace.md) {145                        if defaultsLoaded { ParameterEditor(parameters: $defaults) } else { LabLoading().frame(minHeight: AstraSpace.hit) }146                        Text("Applied when a conversation is created. Switched-off values use each provider's default; a value a model cannot accept is dropped for that model and reported in the chat.")147                            .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)148                    }149                }150                .accessibilityIdentifier("settings-defaults")151            }152            VStack(alignment: .leading, spacing: AstraSpace.md) {153                SectionTitle("Privacy")154                AstraCard(padding: 0) {155                    VStack(spacing: 0) {156                        NavigationLink(value: LabRoute.data) {157                            LabActionRow(title: "Your data", detail: "Export everything, or delete by category", symbol: "externaldrive")158                                .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)159                        }160                        .buttonStyle(.plain).accessibilityIdentifier("settings-data")161                        LabDivider()162                        NavigationLink(value: LabRoute.about) {163                            LabActionRow(title: "About ORIX Astra", detail: "Version, privacy summary, acknowledgements", symbol: "info.circle")164                                .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)165                        }166                        .buttonStyle(.plain).accessibilityIdentifier("settings-about")167                    }168                }169            }170        }171        .task {172            guard !defaultsLoaded else { return }173            defaults = (try? await app.store.setting("chat.defaultParameters", default: GenerationParameters())) ?? .default174            defaultsLoaded = true175        }176        .onChange(of: defaults) { _, new in177            guard defaultsLoaded else { return }178            let store = app.store179            Task { do { try await store.setSetting("chat.defaultParameters", new) } catch { app.show(AstraError.wrap(error).message, .error) } }180        }181    }182183    /// Turning the lock on or off always asks the device owner to authenticate first.184    private func setLock(_ enabled: Bool) {185        guard !lockBusy, enabled != app.appLockEnabled else { return }186        lockBusy = true; lockMessage = nil187        Task {188            defer { lockBusy = false }189            let context = LAContext()190            var probe: NSError?191            guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &probe) else {192                lockMessage = "This iPhone has no passcode, so there is nothing to lock with. Set a passcode in Settings first."193                return194            }195            do {196                let reason = enabled ? "Turn on the app lock" : "Turn off the app lock"197                guard try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason) else { return }198                try await app.store.setSetting("privacy.appLock", enabled)199                app.appLockEnabled = enabled200                AstraHaptics.success()201            } catch let error as LAError where error.code == .userCancel || error.code == .appCancel || error.code == .systemCancel {202                // cancelled by the person: nothing changes203            } catch is LAError {204                lockMessage = "Authentication did not succeed, so the setting was left unchanged."205            } catch { app.show(AstraError.wrap(error).message, .error) }206        }207    }208}209210// MARK: - Data controls211212struct ShareBundle: Identifiable {213    let id = UUID()214    let urls: [URL]215}216217/// Export of everything, and deletion by category. Each deletion asks first and reports what it removed.218struct DataControlsView: View {219    enum Kind: String, CaseIterable, Identifiable {220        case conversations, attachments, documents, usage, diagnostics, memories, arena, agentRuns, models, keys, everything221        var id: String { rawValue }222        var title: String {223            switch self {224            case .conversations: "Conversations"225            case .attachments: "Attachments"226            case .documents: "Documents and index"227            case .usage: "Usage ledger"228            case .diagnostics: "Diagnostics log"229            case .memories: "Memories"230            case .arena: "Arena comparisons"231            case .agentRuns: "Agent runs"232            case .models: "Downloaded models"233            case .keys: "Provider keys"234            case .everything: "Everything"235            }236        }237        var detail: String {238            switch self {239            case .conversations: "Every chat with all its messages and branches"240            case .attachments: "Images and files attached to messages; the messages stay"241            case .documents: "Documents added for retrieval, their chunks and search index"242            case .usage: "The token and cost history shown in Lab"243            case .diagnostics: "The sanitized request log"244            case .memories: "Everything you asked Astra to remember"245            case .arena: "Saved comparisons with their answers"246            case .agentRuns: "Recorded agent runs and their steps; agent profiles stay"247            case .models: "Model weights stored on this iPhone"248            case .keys: "API keys in the Keychain, for providers and custom endpoints"249            case .everything: "All of the above, settings included. Astra returns to its first-launch state."250            }251        }252        var symbol: String {253            switch self {254            case .conversations: "bubble.left.and.bubble.right"255            case .attachments: "paperclip"256            case .documents: "doc.text.magnifyingglass"257            case .usage: "chart.bar"258            case .diagnostics: "stethoscope"259            case .memories: "brain.head.profile"260            case .arena: "rectangle.split.2x1"261            case .agentRuns: "point.3.connected.trianglepath.dotted"262            case .models: "cpu"263            case .keys: "key"264            case .everything: "trash.slash"265            }266        }267        var confirm: String { self == .everything ? "Erase everything" : "Delete \(title.lowercased())" }268    }269270    @Environment(AppModel.self) private var app271    @State private var pending: Kind?272    @State private var working: Kind?273    @State private var report: String?274    @State private var failure: String?275    @State private var isExporting = false276    @State private var shared: ShareBundle?277    @State private var storage: StorageUsage?278279    var body: some View {280        LabPage(title: "Your data") {281            NoticeCard(.info, title: "Stored on this iPhone only",282                       message: "Conversations, comparisons, usage and settings live in a local database. API keys live in the iOS Keychain and are never part of an export. There is no account and no server copy to delete elsewhere.")283            VStack(alignment: .leading, spacing: AstraSpace.md) {284                SectionTitle("Export", detail: storage.map { LabFormat.fileBytes($0.totalBytes) + " stored" })285                AstraCard {286                    VStack(alignment: .leading, spacing: AstraSpace.md) {287                        Text("Writes one JSON file with every record (conversations, comparisons, agents, templates, usage, memories, settings) and a folder with the attachment files, then opens the share sheet. The export is not encrypted: keep it somewhere you trust.")288                            .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)289                        Button { export() } label: {290                            HStack(spacing: AstraSpace.sm) {291                                if isExporting { ProgressView().tint(AstraColor.onAccent) } else { Image(systemName: "square.and.arrow.up").accessibilityHidden(true) }292                                Text(isExporting ? "Preparing…" : "Export all data")293                            }294                        }295                        .buttonStyle(AstraPrimaryButtonStyle()).disabled(isExporting).accessibilityIdentifier("data-export-all")296                    }297                }298            }299            VStack(alignment: .leading, spacing: AstraSpace.md) {300                SectionTitle("Delete")301                if let report { NoticeCard(.success, title: "Done", message: report).accessibilityIdentifier("data-report") }302                if let failure { NoticeCard(.error, title: "Nothing was deleted", message: failure) }303                AstraCard(padding: 0) {304                    VStack(spacing: 0) {305                        ForEach(Kind.allCases) { kind in306                            if kind != Kind.allCases.first { LabDivider() }307                            Button { pending = kind } label: {308                                HStack(spacing: AstraSpace.md) {309                                    LabActionRow(title: kind.title, detail: kind.detail, symbol: kind.symbol,310                                                 tint: kind == .everything ? AstraColor.danger : AstraColor.textSecondary, showsChevron: false)311                                    if working == kind { ProgressView() }312                                    else { Image(systemName: "trash").foregroundStyle(AstraColor.danger).accessibilityHidden(true) }313                                }314                                .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)315                            }316                            .buttonStyle(.plain).disabled(working != nil)317                            .accessibilityHint("Asks for confirmation before deleting")318                            .accessibilityIdentifier("data-delete-\(kind.rawValue)")319                        }320                    }321                }322                Text("Deletions cannot be undone. Space taken by deleted records is returned to the system right away.")323                    .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)324            }325        }326        .task { storage = try? await app.store.storageUsage() }327        .sheet(item: $shared) { ShareSheet(items: $0.urls) }328        .confirmationDialog(pending.map { $0 == .everything ? "Erase everything Astra stores?" : "Delete \($0.title.lowercased())?" } ?? "",329                            isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } }), titleVisibility: .visible) {330            if let kind = pending { Button(kind.confirm, role: .destructive) { run(kind) } }331            Button("Cancel", role: .cancel) {}332        } message: { Text((pending?.detail ?? "") + ". This cannot be undone.") }333    }334335    private func export() {336        isExporting = true337        let store = app.store338        Task {339            defer { isExporting = false }340            do {341                let directory = FileManager.default.temporaryDirectory.appendingPathComponent("astra-export-\(UUID().uuidString)", isDirectory: true)342                    .appendingPathComponent("ORIX Astra export", isDirectory: true)343                let summary = try await store.exportAll(to: directory)344                shared = ShareBundle(urls: summary.attachmentFileCount > 0 ? [summary.jsonURL, summary.attachmentsDirectory] : [summary.jsonURL])345                app.show("Export ready: \(LabFormat.fileBytes(summary.totalBytes))", .success)346            } catch { app.show(AstraError.wrap(error).message, .error) }347        }348    }349350    private func describe(_ result: DeletionResult, _ noun: String) -> String {351        "\(result.rowsDeleted.formatted(.number)) \(noun)\(result.rowsDeleted == 1 ? "" : "s") removed, \(LabFormat.fileBytes(result.bytesFreed)) freed."352    }353354    private func run(_ kind: Kind) {355        guard working == nil else { return }356        working = kind; report = nil; failure = nil357        Task {358            defer { working = nil }359            do {360                let store = app.store361                let text: String362                switch kind {363                case .conversations:364                    app.closeChat()365                    text = describe(try await store.deleteAllConversations(), "conversation and message record")366                    await app.reloadConversations()367                case .attachments: text = describe(try await store.deleteAllAttachments(), "attachment")368                case .documents: text = describe(try await store.deleteAllDocuments(), "document and chunk record")369                case .usage: text = describe(try await store.deleteAllUsage(), "usage line")370                case .diagnostics: text = describe(try await store.deleteAllDiagnostics(), "log entry")371                case .memories: text = describe(try await store.deleteAllMemory(), "memory record")372                case .arena: text = describe(try await store.deleteAllArenaSessions(), "comparison and answer record")373                case .agentRuns: text = describe(try await store.deleteAllAgentRuns(), "run and step record")374                case .models:375                    let (count, bytes) = await deleteModels()376                    text = "\(count) model\(count == 1 ? "" : "s") removed, \(LabFormat.fileBytes(bytes)) freed."377                case .keys:378                    let count = try await deleteKeys()379                    text = "\(count) key\(count == 1 ? "" : "s") removed from the Keychain."380                case .everything:381                    app.closeChat()382                    let result = try await store.deleteEverything()383                    let (models, bytes) = await deleteModels()384                    let keys = (try? await deleteKeys()) ?? 0385                    await app.library.load()386                    await app.reloadConversations()387                    app.appLockEnabled = false; app.appearance = nil388                    text = "Everything erased: \(result.rowsDeleted.formatted(.number)) records, \(models) model\(models == 1 ? "" : "s"), \(keys) key\(keys == 1 ? "" : "s"), \(LabFormat.fileBytes(result.bytesFreed + bytes)) freed."389                }390                if kind != .models, kind != .keys, kind != .everything { _ = try? await store.compact() }391                storage = try? await store.storageUsage()392                report = text393                AstraHaptics.success()394                app.show(text, .success)395                if kind == .everything { app.tab = .chat; app.onboardingDone = false }396            } catch {397                failure = AstraError.wrap(error).message398                AstraHaptics.error()399            }400        }401    }402403    /// Removes every model folder, unfinished downloads included. Returns how many and the bytes freed.404    private func deleteModels() async -> (Int, Int64) {405        let modelStore = app.local.modelStore406        let ids = await Task.detached { modelStore.models().map(\.id) }.value407        var bytes: Int64 = 0408        for id in ids { bytes += await app.local.remove(id) }409        return (ids.count, bytes)410    }411412    /// Removes every secret Astra stored: provider keys, custom endpoint keys and the model hub token.413    private func deleteKeys() async throws -> Int {414        let accounts = try app.credentials.accounts()415        for kind in ProviderKind.cloudKeyed where app.library.providers[kind]?.hasKey == true { await app.library.removeKey(for: kind) }416        for account in accounts { try app.credentials.removeSecret(for: account) }417        return accounts.count418    }419}420421// MARK: - About422423struct AboutView: View {424    private struct Acknowledgement: Identifiable {425        let name: String, license: String, url: String, role: String426        var id: String { name }427    }428    private let acknowledgements = [429        Acknowledgement(name: "MLX Swift", license: "MIT License", url: "https://github.com/ml-explore/mlx-swift", role: "Runs models on Apple silicon"),430        Acknowledgement(name: "MLX Swift LM", license: "MIT License", url: "https://github.com/ml-explore/mlx-swift-lm", role: "Language-model loading and generation"),431        Acknowledgement(name: "swift-transformers", license: "Apache License 2.0", url: "https://github.com/huggingface/swift-transformers", role: "Tokenizers"),432        Acknowledgement(name: "GRDB", license: "MIT License", url: "https://github.com/groue/GRDB.swift", role: "The local SQLite database"),433        Acknowledgement(name: "SwiftMath", license: "MIT License", url: "https://github.com/mgriebling/SwiftMath", role: "Typesetting of formulas"),434        Acknowledgement(name: "swift-markdown", license: "Apache License 2.0", url: "https://github.com/swiftlang/swift-markdown", role: "Markdown parsing"),435    ]436437    private var version: String? { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String }438    private var build: String? { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String }439440    var body: some View {441        LabPage(title: "About") {442            AstraCard {443                HStack(spacing: AstraSpace.lg) {444                    AstraGlyph().frame(width: 64, height: 64)445                    VStack(alignment: .leading, spacing: AstraSpace.xs) {446                        Text("ORIX Astra").font(AstraFont.title).foregroundStyle(AstraColor.textPrimary)447                        Text("Version \(version ?? "—") (\(build ?? "—"))").font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)448                            .accessibilityIdentifier("about-version")449                    }450                    Spacer(minLength: 0)451                }452                .accessibilityElement(children: .combine)453            }454            section("Privacy in short") {455                bullet("person.crop.circle.badge.xmark", "No account", "Astra has no sign-in and no server of its own.")456                bullet("chart.line.downtrend.xyaxis", "No analytics", "No usage tracking, no advertising identifiers, no crash reporting service.")457                bullet("iphone", "On-device models stay on device", "With an on-device model, prompts, attachments and answers never leave this iPhone.")458                bullet("arrow.up.right", "Cloud models receive what you send them", "With a cloud model, your messages, the instructions, attachments you add and enabled memories go directly from this iPhone to the provider you chose (OpenAI, Anthropic, Google, xAI, OpenRouter or your custom endpoint), under your own API key and that provider's terms. OpenRouter forwards the request to an upstream provider, named with each answer when reported.")459                bullet("key", "Keys stay in the Keychain", "API keys are stored in the iOS Keychain of this device, are never shown in full, logged or exported.")460                bullet("arrow.down.circle", "Where models come from", "Model weights are downloaded from the Hugging Face repository named on each model's page, or from the mirror listed there, and checked against the file hashes shipped with the app.")461            }462            section("Open-source acknowledgements") {463                ForEach(acknowledgements) { item in464                    if let url = URL(string: item.url) {465                        Link(destination: url) {466                            HStack(spacing: AstraSpace.md) {467                                VStack(alignment: .leading, spacing: AstraSpace.xxs) {468                                    Text(item.name).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)469                                    Text("\(item.role) · \(item.license)").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).multilineTextAlignment(.leading)470                                }471                                Spacer(minLength: AstraSpace.sm)472                                Image(systemName: "arrow.up.right").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)473                            }474                            .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())475                        }476                        .accessibilityHint("Opens the project page")477                    }478                }479                Text("Each library is used under its own license, available at the link.").font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)480            }481            section("Trademarks") {482                Text("OpenAI, Anthropic, Claude, Google, Gemini, xAI, Grok, OpenRouter, Hugging Face, Apple and the other names and logos shown in this app are trademarks of their respective owners. They are used only to identify the services and models you choose to connect to. ORIX Astra is an independent app and is not affiliated with, sponsored by or endorsed by any of them.")483                    .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)484            }485        }486    }487488    private func section<Content: View>(_ title: String, @ViewBuilder content: @escaping () -> Content) -> some View {489        VStack(alignment: .leading, spacing: AstraSpace.md) {490            SectionTitle(title)491            AstraCard { VStack(alignment: .leading, spacing: AstraSpace.md, content: content) }492        }493    }494495    private func bullet(_ symbol: String, _ title: String, _ text: String) -> some View {496        HStack(alignment: .top, spacing: AstraSpace.md) {497            Image(systemName: symbol).font(.body.weight(.semibold)).foregroundStyle(AstraColor.violet).frame(width: 26).accessibilityHidden(true)498            VStack(alignment: .leading, spacing: AstraSpace.xxs) {499                Text(title).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)500                Text(text).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)501            }502        }503        .accessibilityElement(children: .combine)504    }505}506
Files main
Menu

Theme