SPB Git

Repository Public MIT

DiagnosticsLab.swift 16.5 KB 321 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/DiagnosticsLab.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 AstraCore90import AstraDesign91import AstraPersistence9293/// The sanitized request log: status, request id, latency and retries. Headers, keys, prompts and answers are never recorded.94struct DiagnosticsLabView: View {95    @Environment(AppModel.self) private var app96    @State private var items: [RequestDiagnostic]?97    @State private var error: String?98    @State private var filter: ProviderKind?99    @State private var confirmClear = false100101    private var providers: [ProviderKind] {102        let present = Set((items ?? []).map(\.provider))103        return ProviderKind.allCases.filter(present.contains)104    }105    private var shown: [RequestDiagnostic] { (items ?? []).filter { filter == nil || $0.provider == filter } }106107    var body: some View {108        LabPage(title: "Diagnostics") {109            NoticeCard(.info, title: "What is recorded",110                       message: "One line per request to a provider: HTTP status, the provider's request id, time to response headers and retries. Never headers, API keys, prompts or answers. The log keeps the most recent \(app.store.options.diagnosticsCapacity) requests on this iPhone.")111            if let error { NoticeCard(.error, title: "The log could not be read", message: error) }112            if let items {113                if items.isEmpty {114                    EmptyStateView(symbol: "stethoscope", title: "No request logged", message: "Requests to cloud providers appear here as they happen. On-device generations make no network request.")115                        .frame(maxWidth: .infinity)116                } else {117                    filterBar118                    if shown.isEmpty {119                        Text("No request for this provider.").font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)120                    }121                    ForEach(shown) { row($0) }122                }123            } else if error == nil { LabLoading() }124        }125        .toolbar {126            ToolbarItem(placement: .topBarTrailing) {127                Button(role: .destructive) { confirmClear = true } label: { Label("Clear", systemImage: "trash") }128                    .disabled(items?.isEmpty ?? true).accessibilityIdentifier("diagnostics-clear")129            }130        }131        .task { for await _ in app.store.changes(in: [.diagnostic]) { await load() } }132        .confirmationDialog("Clear the diagnostics log?", isPresented: $confirmClear, titleVisibility: .visible) {133            Button("Clear log", role: .destructive) { clear() }134            Button("Cancel", role: .cancel) {}135        }136    }137138    private var filterBar: some View {139        ScrollView(.horizontal) {140            HStack(spacing: AstraSpace.sm) {141                chip("All", count: items?.count ?? 0, selected: filter == nil) { filter = nil }142                ForEach(providers) { kind in143                    chip(kind.displayName, count: (items ?? []).filter { $0.provider == kind }.count, selected: filter == kind) { filter = kind }144                }145            }146        }147        .scrollIndicators(.hidden)148        .accessibilityIdentifier("diagnostics-filter")149    }150151    private func chip(_ title: String, count: Int, selected: Bool, action: @escaping () -> Void) -> some View {152        Button(action: action) {153            HStack(spacing: AstraSpace.xs) {154                Text(title).font(AstraFont.subheadline.weight(.semibold))155                Text("\(count)").font(AstraFont.micro).foregroundStyle(selected ? AstraColor.violet : AstraColor.textTertiary)156            }157            .foregroundStyle(selected ? AstraColor.violet : AstraColor.textPrimary)158            .padding(.horizontal, AstraSpace.md).frame(minHeight: AstraSpace.hit)159            .background(selected ? AstraColor.accentSoft : AstraColor.surface, in: Capsule())160            .overlay(Capsule().strokeBorder(selected ? AstraColor.violet : AstraColor.stroke, lineWidth: 1))161            .contentShape(Rectangle())162        }163        .buttonStyle(.plain)164        .accessibilityLabel("\(title), \(count) request\(count == 1 ? "" : "s")")165        .accessibilityAddTraits(selected ? .isSelected : [])166    }167168    private func tone(_ status: Int?) -> AstraBadge.Tone {169        guard let status else { return .neutral }170        if (200..<300).contains(status) { return .success }171        return status == 429 || (500..<600).contains(status) ? .warning : .danger172    }173174    private func row(_ d: RequestDiagnostic) -> some View {175        AstraCard {176            VStack(alignment: .leading, spacing: AstraSpace.sm) {177                HStack(alignment: .center, spacing: AstraSpace.sm) {178                    ProviderLogo(provider: d.provider, size: 28)179                    VStack(alignment: .leading, spacing: AstraSpace.xxs) {180                        Text(d.modelID).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary).lineLimit(1).truncationMode(.middle)181                        Text("\(d.provider.displayName) · \(d.startedAt.formatted(date: .abbreviated, time: .standard))").font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)182                    }183                    Spacer(minLength: AstraSpace.sm)184                    AstraBadge(d.httpStatus.map { "HTTP \($0)" } ?? "No status", symbol: tone(d.httpStatus) == .success ? "checkmark" : "exclamationmark", tone: tone(d.httpStatus))185                }186                LazyVGrid(columns: [GridItem(.adaptive(minimum: 96), spacing: AstraSpace.md, alignment: .topLeading)], alignment: .leading, spacing: AstraSpace.sm) {187                    MetricTile("Headers", value: LabFormat.seconds(d.timeToHeaders), unit: "s", symbol: "arrow.down.left.and.arrow.up.right")188                    MetricTile("Retries", value: "\(d.retryCount)", symbol: "arrow.clockwise")189                    if d.timeToFirstToken != nil { MetricTile("First token", value: LabFormat.seconds(d.timeToFirstToken), unit: "s", symbol: "bolt") }190                    if d.totalTime != nil { MetricTile("Total", value: LabFormat.seconds(d.totalTime), unit: "s", symbol: "clock") }191                }192                FactRow(label: "Request id", value: d.requestID, mono: true)193                if let title = d.errorTitle { Label(title, systemImage: "xmark.octagon.fill").font(AstraFont.caption).foregroundStyle(AstraColor.danger) }194            }195        }196        .accessibilityElement(children: .contain)197    }198199    private func load() async {200        do { items = try await app.store.diagnostics(); error = nil } catch { self.error = AstraError.wrap(error).message }201    }202203    private func clear() {204        let store = app.store205        Task {206            do { let r = try await store.deleteAllDiagnostics(); filter = nil; app.show("\(r.rowsDeleted) entr\(r.rowsDeleted == 1 ? "y" : "ies") cleared", .success) }207            catch { app.show(AstraError.wrap(error).message, .error) }208        }209    }210}211212// MARK: - Memory213214/// The memories the person asked Astra to keep. They are plain text, stored on this iPhone, and entirely under the person's control.215struct MemoryLabView: View {216    @Environment(AppModel.self) private var app217    @State private var memories: [MemoryRecord]?218    @State private var error: String?219    @State private var draft = ""220    @State private var editing: MemoryRecord?221    @State private var editText = ""222    @State private var deleting: MemoryRecord?223    @FocusState private var focused: Bool224225    var body: some View {226        LabPage(title: "Memory") {227            NoticeCard(.info, title: "When memories are used",228                       message: "Enabled memories are added to the instructions of a chat when “Use saved memories” is on in that conversation's settings (up to the 40 most recent). With a cloud model they are sent to that provider along with your message; with an on-device model they never leave this iPhone. Nothing is remembered automatically: only what you write here.")229            AstraCard {230                VStack(alignment: .leading, spacing: AstraSpace.md) {231                    LabTextArea(label: "New memory", text: $draft, placeholder: "Something worth remembering, such as “I write in Canadian French”.", minHeight: 64)232                        .focused($focused).accessibilityIdentifier("memory-field")233                    Button { add() } label: { Label("Add memory", systemImage: "plus") }234                        .buttonStyle(AstraPrimaryButtonStyle())235                        .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)236                        .accessibilityIdentifier("memory-add")237                }238            }239            if let error { NoticeCard(.error, title: "Memories could not be read", message: error) }240            if let memories {241                if memories.isEmpty {242                    Text("No memory saved.").font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary).frame(maxWidth: .infinity, alignment: .center)243                } else {244                    SectionTitle("Saved", detail: "\(memories.filter(\.enabled).count) of \(memories.count) enabled")245                    ForEach(memories) { memory in row(memory) }246                }247            } else if error == nil { LabLoading() }248        }249        .keyboardDoneButton()250        .task { for await _ in app.store.changes(in: [.memory]) { await load() } }251        .sheet(item: $editing) { memory in252            NavigationStack {253                ScrollView { LabTextArea(label: "Memory", text: $editText, minHeight: 160).padding(AstraSpace.page) }254                    .background(AstraColor.background)255                    .navigationTitle("Edit memory").navigationBarTitleDisplayMode(.inline)256                    .toolbar {257                        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { editing = nil } }258                        ToolbarItem(placement: .confirmationAction) {259                            Button("Save") { update(memory, text: editText); editing = nil }260                                .disabled(editText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityIdentifier("memory-save")261                        }262                    }263            }264            .presentationDetents([.medium, .large])265        }266        .confirmationDialog("Delete this memory?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {267            Button("Delete", role: .destructive) { if let m = deleting { delete(m) } }268            Button("Cancel", role: .cancel) {}269        }270    }271272    private func row(_ memory: MemoryRecord) -> some View {273        AstraCard {274            VStack(alignment: .leading, spacing: AstraSpace.sm) {275                Text(memory.text).font(AstraFont.callout).foregroundStyle(memory.enabled ? AstraColor.textPrimary : AstraColor.textTertiary)276                    .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)277                Text("Saved \(LabFormat.dateTime(memory.createdAt))" + (memory.sourceConversationID != nil ? " · from a conversation" : ""))278                    .font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)279                HStack(spacing: AstraSpace.sm) {280                    Toggle(memory.enabled ? "Enabled" : "Disabled", isOn: Binding(get: { memory.enabled }, set: { setEnabled(memory, $0) }))281                        .font(AstraFont.subheadline).tint(AstraColor.accentFill)282                        .accessibilityLabel("Use this memory").accessibilityIdentifier("memory-toggle")283                    IconButton("pencil", label: "Edit memory") { editText = memory.text; editing = memory }284                    IconButton("trash", label: "Delete memory", tint: AstraColor.danger) { deleting = memory }285                }286            }287        }288    }289290    private func load() async {291        do { memories = try await app.store.memories(); error = nil } catch { self.error = AstraError.wrap(error).message }292    }293294    private func add() {295        let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)296        guard !text.isEmpty else { return }297        let store = app.store298        draft = ""; focused = false299        Task {300            do { try await store.addMemory(text: text); AstraHaptics.success() }301            catch { draft = text; app.show(AstraError.wrap(error).message, .error) }302        }303    }304305    private func update(_ memory: MemoryRecord, text: String) {306        let store = app.store, clean = text.trimmingCharacters(in: .whitespacesAndNewlines)307        Task { do { try await store.updateMemory(id: memory.id, text: clean) } catch { app.show(AstraError.wrap(error).message, .error) } }308    }309310    private func setEnabled(_ memory: MemoryRecord, _ enabled: Bool) {311        if let i = memories?.firstIndex(where: { $0.id == memory.id }) { memories?[i].enabled = enabled }312        let store = app.store313        Task { do { try await store.updateMemory(id: memory.id, enabled: enabled) } catch { app.show(AstraError.wrap(error).message, .error) } }314    }315316    private func delete(_ memory: MemoryRecord) {317        let store = app.store318        Task { do { try await store.deleteMemory(id: memory.id); app.show("Memory deleted", .success) } catch { app.show(AstraError.wrap(error).message, .error) } }319    }320}321
Files main
Menu

Theme