SPB Git

Repository Public

SettingsNextPanes.swift 41.0 KB 665 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Settings/SettingsNextPanes.swift3// Description: Settings panes of 2.0 about the agent: Models & Routing (server registry, default model, strategy, live preview of the router), Budgets, Memory (scopes, retention, pin, edit, expiry, bulk deletion, export), and the small building blocks the 2.0 panes share.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910// MARK: - building blocks1112/// A block of a pane: the editorial header (rule, serif title, actions) and its content.13struct SettingsBlock<Actions: View, Content: View>: View {14    let title: String15    var overline: String?16    @ViewBuilder var actions: Actions17    @ViewBuilder var content: Content1819    init(_ title: String, overline: String? = nil, @ViewBuilder actions: () -> Actions = { EmptyView() }, @ViewBuilder content: () -> Content) {20        self.title = title; self.overline = overline; self.actions = actions(); self.content = content()21    }22    var body: some View {23        VStack(alignment: .leading, spacing: 10) {24            VQSectionHeader(title, overline: overline) { actions }25            content26        }27        .padding(.top, 6)28    }29}3031/// A raised surface inside a pane (ink1 on the ink0 canvas, hairline border).32struct SettingsCard<Content: View>: View {33    var padding: CGFloat = 1234    @ViewBuilder var content: Content35    var body: some View {36        content37            .padding(padding)38            .frame(maxWidth: .infinity, alignment: .leading)39            .background(VQTokens.Palette.ink1, in: RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous))40            .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.md, style: .continuous).strokeBorder(VQTokens.Palette.line, lineWidth: 1))41    }42}4344struct SettingsNote: View {45    let text: String46    init(_ text: String) { self.text = text }47    var body: some View { Text(text).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true) }48}4950/// The server could not answer: the sentence it gave, and a way to ask again. Never a placeholder value.51struct PaneFailure: View {52    let message: String53    let retry: () -> Void54    var body: some View {55        HStack(spacing: 8) {56            Image(systemName: "exclamationmark.triangle").foregroundStyle(VQTokens.Palette.warn)57            Text(message).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)58            Spacer()59            Button("Retry", action: retry).controlSize(.small)60        }61        .padding(10).background(VQTokens.Palette.ink3.opacity(0.5), in: RoundedRectangle(cornerRadius: VQTokens.Radius.sm))62    }63}6465/// A small state word with its glyph: the state is never carried by colour alone.66struct StatePill: View {67    enum Tone { case good, neutral, warn, bad }68    let text: String69    let tone: Tone70    var body: some View {71        HStack(spacing: 4) {72            Image(systemName: symbol).font(.system(size: 9, weight: .semibold))73            Text(text).font(.system(size: 11, weight: .medium))74        }75        .foregroundStyle(color)76        .padding(.horizontal, 7).padding(.vertical, 2.5)77        .overlay(Capsule().strokeBorder(color.opacity(0.45), lineWidth: 1))78        .fixedSize()79    }80    private var symbol: String { switch tone { case .good: "checkmark"; case .neutral: "minus"; case .warn: "exclamationmark"; case .bad: "xmark" } }81    private var color: Color { switch tone { case .good: VQTokens.Palette.text1; case .neutral: VQTokens.Palette.text3; case .warn: VQTokens.Palette.warn; case .bad: VQTokens.Palette.critical } }82}8384func paneError(_ error: Error) -> String {85    // a network failure is said in one sentence; the system's own description is a page of diagnostics86    if let e = error as? VQError { return e.kind == .network ? "The VQuant server cannot be reached. Nothing is shown in its place; retry when the connection is back." : e.userMessage }87    return error.localizedDescription88}8990private let hair = VQTokens.Palette.line9192// MARK: - Models & Routing9394struct ModelsPane: View {95    let app: AppEnvironment96    @State private var catalog: VQModelCatalog?97    @State private var catalogError: String?98    @State private var localStrategy: VQPreference.RoutingStrategy?99    @State private var localProviders: [String]?100    @State private var previewMode: ResearchMode = .standard101    @State private var vision = false102    @State private var decision: VQRouteDecision?103    @State private var previewError: String?104    @State private var previewing = false105    @State private var saving = false106    @State private var tick = 0107    @State private var expanded: Set<String> = []108109    private struct PreviewKey: Hashable { var mode: ResearchMode; var vision: Bool; var tick: Int }110    private static let defaultProviders = ["anthropic", "openai", "google"]111112    private var routing: VQPreference.Routing? { app.sync.active?.preference.routing }113    private var strategy: VQPreference.RoutingStrategy { localStrategy ?? routing?.strategy?.known ?? .balanced }114    private var providers: [String] { localProviders ?? routing.map(\.providers).flatMap { $0.isEmpty ? nil : $0 } ?? Self.defaultProviders }115116    var body: some View {117        VStack(alignment: .leading, spacing: 18) {118            defaults119            preview120            registry121        }122        .task { await loadCatalog() }123        .task(id: PreviewKey(mode: previewMode, vision: vision, tick: tick)) { await loadPreview() }124    }125126    // default model, strategy, providers127128    private var defaults: some View {129        SettingsBlock("Default model and routing") {130            SettingsCard {131                Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 12) {132                    GridRow {133                        Text("Default model").foregroundStyle(VQTokens.Palette.text2).gridColumnAlignment(.trailing)134                        HStack(spacing: 8) {135                            Picker("Default model", selection: Binding(get: { app.settings.researchModel }, set: { app.settings.researchModel = $0; app.sync.pushSettings() })) {136                                Text("Auto — the server chooses for each request").tag("auto")137                                if let catalog {138                                    ForEach(catalog.providers.filter { !$0.models.filter(\.selectable).isEmpty }) { p in139                                        Section(p.name) { ForEach(p.models.filter(\.selectable)) { m in Text(m.label).tag(m.id) } }140                                    }141                                    // a stored id the registry no longer offers stays visible rather than silently changing142                                    if app.settings.researchModel != "auto", catalog.model(app.settings.researchModel)?.selectable != true {143                                        Text("\(ResearchModel.name(app.settings.researchModel)) (not selectable on this server)").tag(app.settings.researchModel)144                                    }145                                } else if app.settings.researchModel != "auto" { Text(ResearchModel.name(app.settings.researchModel)).tag(app.settings.researchModel) }146                            }147                            .labelsHidden().frame(maxWidth: 360).accessibilityIdentifier("settings.models.default")148                            if let c = catalog, app.settings.researchModel != "auto", c.model(app.settings.researchModel)?.selectable != true {149                                Text("The server will answer with \(c.model(c.defaultModel)?.label ?? c.defaultModel) instead.").font(.caption).foregroundStyle(VQTokens.Palette.warn)150                            }151                        }152                    }153                    GridRow {154                        Text("When “Auto”").foregroundStyle(VQTokens.Palette.text2)155                        VStack(alignment: .leading, spacing: 6) {156                            HStack(spacing: 10) {157                                VQSegmentedControl("Routing strategy", selection: Binding(get: { strategy }, set: { s in Task { await apply(strategy: s, providers: providers) } }),158                                                   options: [.init(.quality, "Quality"), .init(.balanced, "Balanced"), .init(.economy, "Economy")])159                                    .accessibilityIdentifier("settings.models.strategy").focusEffectDisabled()160                                if saving { ProgressView().controlSize(.small) }161                            }162                            Text(strategyDetail).font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)163                        }164                    }165                    GridRow {166                        Text("Route among").foregroundStyle(VQTokens.Palette.text2)167                        VStack(alignment: .leading, spacing: 6) {168                            HStack(spacing: 14) {169                                ForEach(catalog?.providers ?? []) { p in170                                    Toggle(isOn: Binding(get: { providers.contains(p.id) }, set: { on in171                                        var list = providers.filter { $0 != p.id }; if on { list.append(p.id) }172                                        Task { await apply(strategy: strategy, providers: list) }173                                    })) { HStack(spacing: 5) { VQProviderLogo(provider: p.id, size: 13); Text(p.name) } }174                                    .toggleStyle(.checkbox).disabled(!p.configured || (providers == [p.id]))175                                    .help(p.configured ? "Let “Auto” choose among the models of \(p.name)" : "No key for \(p.name) on the server")176                                    .accessibilityIdentifier("settings.models.provider.\(p.id)")177                                }178                            }179                            Text("The strategy and this list are part of your account (the synced preference); they apply on the web and on every device.")180                                .font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)181                        }182                    }183                }184            }185        }186    }187188    private var strategyDetail: String {189        switch strategy {190        case .quality: "Prefers the frontier tier whatever the price."191        case .balanced: "Prefers the balanced tier: a capable model at a moderate price."192        case .economy: "Prefers the fast tier and the lowest price that can still do the work."193        }194    }195196    // live preview of the router197198    private var preview: some View {199        SettingsBlock("What “Auto” would choose", overline: "Preview") {200            if previewing { ProgressView().controlSize(.small) }201            Button { tick += 1 } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless).help("Ask the server again").accessibilityIdentifier("settings.models.preview.reload")202        } content: {203            HStack(spacing: 14) {204                Text("For a request in").foregroundStyle(VQTokens.Palette.text2)205                VQSegmentedControl("Preview mode", selection: $previewMode, options: ResearchMode.allCases.map { .init($0, $0 == .deep ? "Deep" : $0 == .ultra ? "Ultra" : $0.title) })206                    .accessibilityIdentifier("settings.models.preview.mode").focusEffectDisabled()207                Toggle("with an image", isOn: $vision).toggleStyle(.checkbox)208                Spacer()209            }210            if let previewError { PaneFailure(message: previewError) { tick += 1 } }211            if let d = decision {212                SettingsCard {213                    VStack(alignment: .leading, spacing: 10) {214                        HStack(spacing: 8) {215                            VQProviderLogo(provider: d.provider, size: 18).foregroundStyle(VQTokens.Palette.text1)216                            Text(label(d.model)).font(VQTokens.Typography.title.font).accessibilityIdentifier("settings.models.preview.model")217                            Text(d.model).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3).textSelection(.enabled)218                            Spacer()219                            StatePill(text: d.strategy.capitalized, tone: .neutral)220                        }221                        Text(d.reason).font(.callout).foregroundStyle(VQTokens.Palette.text1).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)222                            .accessibilityIdentifier("settings.models.preview.reason")223                        if !d.candidates.isEmpty {224                            Rectangle().fill(hair).frame(height: 1)225                            Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 5) {226                                GridRow {227                                    Text("Candidate").gridColumnAlignment(.leading); Text("Score").gridColumnAlignment(.trailing); Text("Why")228                                }229                                .font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)230                                ForEach(Array(d.candidates.enumerated()), id: \.offset) { i, c in231                                    GridRow {232                                        HStack(spacing: 5) {233                                            VQProviderLogo(provider: catalog?.model(c.model)?.provider ?? "", size: 12).foregroundStyle(VQTokens.Palette.text2)234                                            Text(label(c.model)).fontWeight(i == 0 ? .semibold : .regular)235                                        }236                                        Text(c.score.map { String(format: "%.3f", $0) } ?? "—").font(VQTokens.Typography.numSm.font)237                                        Text(c.why).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)238                                    }239                                    .font(.callout)240                                }241                            }242                        }243                    }244                }245            } else if previewError == nil { VQSkeletonText(lines: 3) }246            SettingsNote("The preview asks the server's router for its decision; no model is run and nothing is billed. The score is the router's own, computed from tier, price, validation with this app and provider health.")247        }248    }249250    private func label(_ id: String) -> String { catalog?.model(id)?.label ?? ResearchModel.name(id) }251252    // the registry253254    private var registry: some View {255        SettingsBlock("Models the server reaches", overline: "Registry") {256            Button { Task { catalog = nil; await loadCatalog() } } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless).help("Read the registry again")257        } content: {258            if let catalogError { PaneFailure(message: catalogError) { Task { await loadCatalog() } } }259            if let catalog {260                ForEach(catalog.providers) { p in providerCard(p, defaultModel: catalog.defaultModel) }261                SettingsNote("Models are discovered from each provider's own listing and merged with what the VQuant repository states about them. A context size or a price that neither states is shown as “not stated”, never filled in. No key ever reaches this Mac: the server reports only whether one is present.")262            } else if catalogError == nil { VQSkeletonRows(rows: 5, columns: 5) }263        }264    }265266    @ViewBuilder private func providerCard(_ p: VQModelProvider, defaultModel: String) -> some View {267        let selectable = p.models.filter(\.selectable), others = p.models.filter { !$0.selectable }268        SettingsCard(padding: 0) {269            VStack(alignment: .leading, spacing: 0) {270                HStack(spacing: 8) {271                    VQProviderLogo(provider: p.id, size: 16).foregroundStyle(VQTokens.Palette.text1)272                    Text(p.name).font(VQTokens.Typography.heading.font)273                    if !p.configured { StatePill(text: "No key on the server", tone: .neutral) }274                    else if p.ok { StatePill(text: "Reachable", tone: .good) }275                    else { StatePill(text: "Listing failed", tone: .bad) }276                    if let e = p.error { Text(e).font(.caption).foregroundStyle(VQTokens.Palette.critical).lineLimit(2) }277                    Spacer()278                    Text(p.models.isEmpty ? "no model" : "\(selectable.count) selectable of \(p.models.count) listed").font(.caption).foregroundStyle(VQTokens.Palette.text3)279                    if let t = p.checkedAt { Text("· checked \(Fmt.relative(t))").font(.caption).foregroundStyle(VQTokens.Palette.text3) }280                }281                .padding(.horizontal, 12).padding(.vertical, 9)282                .accessibilityElement(children: .combine).accessibilityIdentifier("settings.models.provider.row.\(p.id)")283                if !p.models.isEmpty {284                    Rectangle().fill(hair).frame(height: 1)285                    Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 6) {286                        GridRow {287                            Text("Model").gridColumnAlignment(.leading); Text("Tier"); Text("Context").gridColumnAlignment(.trailing); Text("Per MTok").gridColumnAlignment(.trailing)288                            Text("Abilities"); Text("Choice")289                        }290                        .font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)291                        ForEach(selectable) { m in modelRow(m, p, defaultModel: defaultModel) }292                        if expanded.contains(p.id) { ForEach(others) { m in modelRow(m, p, defaultModel: defaultModel) } }293                    }294                    .padding(.horizontal, 12).padding(.vertical, 9)295                    if !others.isEmpty {296                        Rectangle().fill(hair).frame(height: 1)297                        Button {298                            if expanded.contains(p.id) { expanded.remove(p.id) } else { expanded.insert(p.id) }299                        } label: {300                            Label(expanded.contains(p.id) ? "Hide the \(others.count) models that cannot be selected" : "Show \(others.count) listed model\(others.count == 1 ? "" : "s") that cannot be selected, and why",301                                  systemImage: expanded.contains(p.id) ? "chevron.up" : "chevron.down").font(.caption)302                        }303                        .buttonStyle(.borderless).padding(.horizontal, 12).padding(.vertical, 7)304                        .accessibilityIdentifier("settings.models.others.\(p.id)")305                    }306                }307            }308        }309    }310311    @ViewBuilder private func modelRow(_ m: VQModelInfo, _ p: VQModelProvider, defaultModel: String) -> some View {312        GridRow {313            VStack(alignment: .leading, spacing: 1) {314                HStack(spacing: 6) {315                    Text(m.label).fontWeight(.medium)316                    if m.id == defaultModel { Text("server default").font(.system(size: 10, weight: .medium)).foregroundStyle(VQTokens.Palette.accentText) }317                }318                Text(m.id).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(VQTokens.Palette.text3).lineLimit(1).truncationMode(.middle)319            }320            Text(m.tier?.rawValue.capitalized ?? "—").foregroundStyle(VQTokens.Palette.text2)321            Text(UsageText.context(m.contextWindow)).font(VQTokens.Typography.numSm.font).foregroundStyle(m.contextWindow == nil ? VQTokens.Palette.text3 : VQTokens.Palette.text1)322            Text(UsageText.pricing(m.pricing)).font(VQTokens.Typography.numSm.font).foregroundStyle(m.pricing == nil ? VQTokens.Palette.text3 : VQTokens.Palette.text1)323            HStack(spacing: 6) {324                ability("wrench.and.screwdriver", m.capabilities.tools, "tools"); ability("eye", m.capabilities.vision, "images")325                ability("brain", m.capabilities.reasoning, "reasoning"); ability("dot.radiowaves.left.and.right", m.capabilities.streaming, "streaming")326            }327            if let why = UsageText.notSelectableReason(m, providerConfigured: p.configured) {328                Text("Not selectable: \(why)").font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)329            } else { StatePill(text: "Selectable", tone: .good) }330        }331        .font(.callout)332        .accessibilityElement(children: .combine)333    }334335    private func ability(_ symbol: String, _ on: Bool, _ name: String) -> some View {336        Image(systemName: symbol).font(.system(size: 11)).foregroundStyle(on ? VQTokens.Palette.text1 : VQTokens.Palette.text3.opacity(0.35))337            .help(on ? "Declares \(name)" : "Does not declare \(name)").accessibilityLabel(on ? name : "no \(name)")338    }339340    // loading and saving341342    private func loadCatalog() async {343        do { catalog = try await app.vq.models.catalog(); catalogError = nil } catch is CancellationError {} catch { catalogError = paneError(error) }344    }345346    private func loadPreview() async {347        previewing = true; defer { previewing = false }348        do {349            var d = try await app.vq.models.route(mode: previewMode.rawValue, vision: vision ? true : nil, query: nil)350            // the strategy just chosen may still be on its way to the server: ask again until the router has it351            var attempts = 0352            // (the strategy this Mac holds — pending writes included — is the reference, not only what this view just set)353            while app.sync.active != nil, d.strategy != strategy.rawValue, attempts < 14, !Task.isCancelled {354                attempts += 1355                try await Task.sleep(for: .milliseconds(600))356                d = try await app.vq.models.route(mode: previewMode.rawValue, vision: vision ? true : nil, query: nil)357            }358            guard !Task.isCancelled else { return }359            decision = d; previewError = nil360        } catch is CancellationError {} catch { previewError = paneError(error) }361    }362363    /// Stores the strategy and the provider list in the synced preference, sends it, then asks the router again: the364    /// preview always reflects what the server holds, not what this window assumes.365    private func apply(strategy s: VQPreference.RoutingStrategy, providers list: [String]) async {366        guard let session = app.sync.active else { app.toasts.show("Sign in to change the routing.", error: true); return }367        localStrategy = s; localProviders = list368        saving = true; defer { saving = false }369        await session.updatePreference { $0.routing = VQPreference.Routing(strategy: s, providers: list) }370        await session.engine.flush()371        for _ in 0..<20 where await !session.engine.pendingIDs(.preference).isEmpty { try? await Task.sleep(for: .milliseconds(150)) }372        if let e = session.preferences.lastError { app.toasts.show("The routing was not saved: \(e.userMessage)", error: true) }373        tick += 1374    }375}376377// MARK: - Budgets378379struct BudgetsPane: View {380    let app: AppEnvironment381    @State private var costOn = false382    @State private var cost = 2.0383    @State private var minutesOn = false384    @State private var minutes = 20.0385    @State private var loaded = false386    @State private var saving = false387    @State private var savedAt: Date?388389    private var stored: VQPreference.Budget? { app.sync.active?.preference.budget }390391    var body: some View {392        VStack(alignment: .leading, spacing: 18) {393            SettingsBlock("Limits of one analysis") {394                if saving { ProgressView().controlSize(.small) } else if savedAt != nil { Label("Saved to your account", systemImage: "checkmark").font(.caption).foregroundStyle(VQTokens.Palette.text3).accessibilityIdentifier("settings.budgets.saved") }395            } content: {396                SettingsCard {397                    Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 12) {398                        GridRow {399                            Toggle("Stop spending after", isOn: Binding(get: { costOn }, set: { costOn = $0; save() })).toggleStyle(.checkbox).accessibilityIdentifier("settings.budgets.cost.on")400                            HStack(spacing: 6) {401                                TextField("USD", value: $cost, format: .number.precision(.fractionLength(2))).textFieldStyle(.roundedBorder).frame(width: 84).multilineTextAlignment(.trailing)402                                    .font(VQTokens.Typography.numMd.font).disabled(!costOn).onSubmit(save).accessibilityIdentifier("settings.budgets.cost")403                                Text("USD of known model cost").foregroundStyle(VQTokens.Palette.text2)404                            }405                        }406                        GridRow {407                            Toggle("Stop working after", isOn: Binding(get: { minutesOn }, set: { minutesOn = $0; save() })).toggleStyle(.checkbox).accessibilityIdentifier("settings.budgets.minutes.on")408                            HStack(spacing: 6) {409                                TextField("minutes", value: $minutes, format: .number.precision(.fractionLength(0...1))).textFieldStyle(.roundedBorder).frame(width: 84).multilineTextAlignment(.trailing)410                                    .font(VQTokens.Typography.numMd.font).disabled(!minutesOn).onSubmit(save).accessibilityIdentifier("settings.budgets.minutes")411                                Text("minutes").foregroundStyle(VQTokens.Palette.text2)412                            }413                        }414                    }415                }416                Text(summary).font(.callout).foregroundStyle(VQTokens.Palette.text1).accessibilityIdentifier("settings.budgets.summary")417            }418            SettingsBlock("What happens when a limit is reached") {419                VStack(alignment: .leading, spacing: 8) {420                    step("1", "The lead analyst is told to conclude with what it has, and the sub-analysts to write up their findings.")421                    step("2", "One more round of tools may still run; after it, nothing further runs.")422                    step("3", "The conversation shows a budget notice — which limit (cost or minutes), its value and what had been spent — once per limit.")423                    step("4", "The answer you get is the one written from the work done so far. Nothing is discarded, and nothing is charged beyond that last round.")424                }425                SettingsNote("The cost limit counts known costs only: calls to a model with no published price cannot count toward it, so with such a model only the time limit protects you. A budget given with one request overrides these defaults for that request. The limits are part of your account and apply on the web and on every device.")426            }427        }428        .onAppear(perform: load)429        .onChange(of: stored) { _, _ in if !saving { loaded = false; load() } }430    }431432    private func step(_ n: String, _ text: String) -> some View {433        HStack(alignment: .firstTextBaseline, spacing: 10) {434            Text(n).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3).frame(width: 14, alignment: .trailing)435            Text(text).font(.callout).fixedSize(horizontal: false, vertical: true)436        }437    }438439    private var summary: String {440        switch (costOn, minutesOn) {441        case (false, false): "No limit: an analysis runs until it is done or you stop it."442        case (true, false): "An analysis is told to conclude once it has spent \(UsageText.usd(cost))."443        case (false, true): "An analysis is told to conclude after \(Fmt.number(minutes, digits: 1)) minutes."444        case (true, true): "An analysis is told to conclude once it has spent \(UsageText.usd(cost)) or worked \(Fmt.number(minutes, digits: 1)) minutes, whichever comes first."445        }446    }447448    private func load() {449        guard !loaded else { return }450        loaded = true451        if let c = stored?.maxCostUsd { costOn = true; cost = c } else { costOn = false }452        if let m = stored?.maxMinutes { minutesOn = true; minutes = m } else { minutesOn = false }453    }454455    private func save() {456        guard let session = app.sync.active else { app.toasts.show("Sign in to change the budgets.", error: true); return }457        let c: Double? = costOn && cost > 0 ? cost : nil, m: Double? = minutesOn && minutes > 0 ? minutes : nil458        saving = true459        Task {460            await session.updatePreference { p in p.budget = (c == nil && m == nil) ? nil : VQPreference.Budget(maxCostUsd: c, maxMinutes: m) }461            saving = false; savedAt = Date()462            if let e = session.preferences.lastError { app.toasts.show("The budget was not saved: \(e.userMessage)", error: true); savedAt = nil }463        }464    }465}466467// MARK: - Memory468469struct MemoryPane: View {470    let app: AppEnvironment471    @State private var overview: VQMemoryOverview?472    @State private var error: String?473    @State private var busy = false474    @State private var editing: MemoryDraft?475    @State private var deleting: VQMemory?476    @State private var bulk: VQMemoryOverview.Group?477478    private static let retentionChoices = [30, 90, 180, 365, 730]479480    var body: some View {481        VStack(alignment: .leading, spacing: 18) {482            if let error { PaneFailure(message: error) { Task { await load() } } }483            if let o = overview {484                SettingsBlock("How memory is used") {485                    if busy { ProgressView().controlSize(.small) }486                } content: {487                    SettingsCard {488                        VStack(alignment: .leading, spacing: 10) {489                            Toggle("Let the agent use and save memories", isOn: Binding(get: { o.settings.enabled }, set: { on in Task { await setSettings(enabled: on) } }))490                                .accessibilityIdentifier("settings.memory.enabled")491                            Text(o.settings.enabled ? "Your memories are given to the agent at the start of each conversation; a project's memories only inside that project. The agent may save new ones."492                                 : "Nothing is given to the agent and its attempts to save a memory are refused. You can still read, edit and delete what is stored.")493                                .font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)494                            Rectangle().fill(hair).frame(height: 1)495                            HStack {496                                Picker("Keep memories", selection: Binding(get: { o.settings.retentionDays ?? 0 }, set: { d in Task { await setSettings(retention: .some(d == 0 ? nil : d)) } })) {497                                    Text("until I delete them").tag(0)498                                    ForEach(Self.retentionChoices, id: \.self) { Text("for \($0) days").tag($0) }499                                    if let d = o.settings.retentionDays, !Self.retentionChoices.contains(d) { Text("for \(d) days").tag(d) }500                                }501                                .frame(maxWidth: 300).accessibilityIdentifier("settings.memory.retention")502                                Spacer()503                            }504                            Text("With a retention period, an unpinned memory older than it expires: it is no longer given to the agent and the server deletes it. Pinning exempts a memory; revising its text restarts its age.")505                                .font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)506                        }507                    }508                }509                ForEach(o.groups) { g in group(g) }510                HStack {511                    Button { Task { await export() } } label: { Label("Export All Memories…", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("settings.memory.export")512                    Text("\(o.count) memor\(o.count == 1 ? "y" : "ies") in your account · the export and bulk deletions are recorded in the audit log").font(.caption).foregroundStyle(VQTokens.Palette.text3)513                }514            } else if error == nil { VQSkeletonRows(rows: 4, columns: 3) }515        }516        .task { await load() }517        .sheet(item: $editing) { d in MemoryEditor(draft: d) { saved in Task { await commit(saved) } }.vqTheme(app.vqTheme) }518        .confirmationDialog("Delete this memory?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), presenting: deleting) { m in519            Button("Delete Memory", role: .destructive) { Task { await delete(m) } }520        } message: { m in Text("“\(String(m.content.prefix(120)))” will no longer be known to the agent. This cannot be undone.") }521        .confirmationDialog(bulk.map { "Delete all \($0.memories.count) memories of \(scopeName($0))?" } ?? "", isPresented: Binding(get: { bulk != nil }, set: { if !$0 { bulk = nil } }), presenting: bulk) { g in522            Button("Delete \(g.memories.count) Memor\(g.memories.count == 1 ? "y" : "ies")", role: .destructive) { Task { await deleteAll(g) } }523        } message: { _ in Text("Pinned memories are deleted too. The deletion is recorded in the audit log and cannot be undone. Export first if you may want them back.") }524    }525526    private func scopeName(_ g: VQMemoryOverview.Group) -> String {527        switch g.scope {528        case .user: "your account"529        case .project(let id): "the project “\(g.projectTitle ?? id)”"530        case .other(let s): s531        }532    }533534    @ViewBuilder private func group(_ g: VQMemoryOverview.Group) -> some View {535        let title: String = { switch g.scope { case .user: "About you"; case .project(let id): g.projectTitle ?? "Project \(id)"; case .other(let s): s } }()536        SettingsBlock(title, overline: g.scope == .user ? "Every conversation" : "Only inside this project") {537            Button { editing = MemoryDraft(scope: g.scope) } label: { Label("New", systemImage: "plus") }.controlSize(.small).accessibilityIdentifier("settings.memory.new.\(g.id)")538            Button(role: .destructive) { bulk = g } label: { Text("Delete All…") }.controlSize(.small).disabled(g.memories.isEmpty).accessibilityIdentifier("settings.memory.deleteAll.\(g.id)")539        } content: {540            if g.memories.isEmpty { Text("Nothing is remembered here.").font(.callout).foregroundStyle(VQTokens.Palette.text3) }541            VStack(spacing: 0) {542                ForEach(Array(g.memories.enumerated()), id: \.element.id) { i, m in543                    if i > 0 { Rectangle().fill(hair).frame(height: 1) }544                    row(m)545                }546            }547        }548    }549550    private func row(_ m: VQMemory) -> some View {551        HStack(alignment: .top, spacing: 10) {552            Button { Task { await change(m, VQMemoryChange(pinned: !m.pinned)) } } label: {553                Image(systemName: m.pinned ? "pin.fill" : "pin").foregroundStyle(m.pinned ? VQTokens.Palette.accentText : VQTokens.Palette.text3)554            }555            .buttonStyle(.borderless).help(m.pinned ? "Pinned: exempt from the retention period. Click to unpin." : "Pin: keep whatever the retention period")556            .accessibilityLabel(m.pinned ? "Unpin" : "Pin").accessibilityIdentifier("settings.memory.pin.\(m.id)")557            VStack(alignment: .leading, spacing: 3) {558                Text(m.content).font(.callout).fixedSize(horizontal: false, vertical: true).textSelection(.enabled).accessibilityIdentifier("settings.memory.content.\(m.id)")559                Text(meta(m)).font(.caption).foregroundStyle(VQTokens.Palette.text3)560            }561            Spacer(minLength: 8)562            Button("Edit") { editing = MemoryDraft(memory: m) }.controlSize(.small).accessibilityIdentifier("settings.memory.edit.\(m.id)")563            Button(role: .destructive) { deleting = m } label: { Image(systemName: "trash") }.controlSize(.small).help("Delete this memory").accessibilityLabel("Delete").accessibilityIdentifier("settings.memory.delete.\(m.id)")564        }565        .padding(.vertical, 8)566    }567568    private func meta(_ m: VQMemory) -> String {569        var parts: [String] = []570        if let k = m.kind { parts.append(k.rawValue.capitalized) }571        if let c = m.category, !c.isEmpty { parts.append(c) }572        parts.append(m.source == .user ? "written by you" : m.source == .agent ? "saved by the agent" : (m.source?.rawValue ?? "source not stated"))573        if let d = m.createdAt { parts.append("created \(Fmt.dateTime(d))") }574        if let e = m.expiresAt { parts.append("expires \(Fmt.dateTime(e))") } else if m.pinned { parts.append("pinned, never expires") }575        return parts.joined(separator: " · ")576    }577578    // server calls579580    private func load() async {581        do { overview = try await app.vq.research.memory(); error = nil } catch is CancellationError {} catch { self.error = paneError(error) }582    }583    private func perform(_ work: () async throws -> Void) async {584        busy = true; defer { busy = false }585        do { try await work() } catch { app.toasts.show(paneError(error), error: true) }586        await load()587    }588    private func setSettings(enabled: Bool? = nil, retention: Int?? = nil) async {589        await perform { _ = try await app.vq.research.setMemorySettings(enabled: enabled, retentionDays: retention) }590    }591    private func change(_ m: VQMemory, _ c: VQMemoryChange) async { await perform { _ = try await app.vq.research.updateMemory(m.id, c) } }592    private func delete(_ m: VQMemory) async { await perform { try await app.api.deleteMemory(m.id) } }593    private func deleteAll(_ g: VQMemoryOverview.Group) async {594        await perform { let n = try await app.vq.research.deleteMemories(scope: g.scope); app.toasts.show("\(n) memor\(n == 1 ? "y" : "ies") deleted.") }595    }596    private func commit(_ d: MemoryDraft) async {597        await perform {598            let text = d.content.trimmingCharacters(in: .whitespacesAndNewlines)599            if let id = d.memoryId {600                _ = try await app.vq.research.updateMemory(id, VQMemoryChange(content: text, category: d.category, kind: d.kind, expiresAt: .some(d.expires ? d.expiresAt : nil)))601            } else {602                _ = try await app.vq.research.addMemory(content: text, change: VQMemoryChange(category: d.category.isEmpty ? nil : d.category, kind: d.kind, scope: d.scope, expiresAt: d.expires ? .some(d.expiresAt) : nil))603            }604        }605    }606    private func export() async {607        do {608            let data = try await app.vq.research.exportMemories()609            let day = Date().formatted(.iso8601.year().month().day())610            if let url = SavePanel.save(data, name: "vquant-memories-\(day).json", types: [.json]) { app.toasts.show("Memories exported to \(url.lastPathComponent).") }611        } catch { app.toasts.show(paneError(error), error: true) }612    }613}614615struct MemoryDraft: Identifiable {616    /// The memory being edited; nil for a new one.617    let memoryId: String?618    var id: UUID { identity }619    var scope: VQMemoryScope620    var content = ""621    var category = ""622    var kind: VQMemory.Kind = .knowledge623    var expires = false624    var expiresAt = Date().addingTimeInterval(30 * 86400)625    var identity = UUID()626627    init(scope: VQMemoryScope) { memoryId = nil; self.scope = scope; if case .project = scope { kind = .project } }628    init(memory m: VQMemory) {629        memoryId = m.id; scope = m.scope; content = m.content; category = m.category ?? ""; kind = m.kind?.known ?? .knowledge630        if let e = m.expiresAt { expires = true; expiresAt = e }631    }632}633634private struct MemoryEditor: View {635    @State var draft: MemoryDraft636    let onSave: (MemoryDraft) -> Void637    @Environment(\.dismiss) private var dismiss638639    var body: some View {640        VStack(alignment: .leading, spacing: 12) {641            Text(draft.memoryId == nil ? "New memory" : "Edit memory").font(VQTokens.Typography.title.font)642            TextEditor(text: $draft.content).font(.body).frame(minHeight: 110).padding(4)643                .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(VQTokens.Palette.lineStrong)).accessibilityIdentifier("settings.memory.editor.content")644            HStack {645                Picker("Kind", selection: $draft.kind) { ForEach(VQMemory.Kind.allCases, id: \.self) { Text($0.rawValue.capitalized).tag($0) } }.frame(width: 220)646                TextField("Category (optional)", text: $draft.category).textFieldStyle(.roundedBorder)647            }648            HStack {649                Toggle("Expires on", isOn: $draft.expires).toggleStyle(.checkbox).accessibilityIdentifier("settings.memory.editor.expires")650                DatePicker("Expiry", selection: $draft.expiresAt, in: Date()..., displayedComponents: [.date]).labelsHidden().disabled(!draft.expires)651                Spacer()652            }653            Text("An expired memory is no longer given to the agent and is deleted by the server. Without a date, the retention period of your account applies unless the memory is pinned.")654                .font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)655            HStack {656                Spacer()657                Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)658                Button("Save") { onSave(draft); dismiss() }.keyboardShortcut(.defaultAction)659                    .disabled(draft.content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityIdentifier("settings.memory.editor.save")660            }661        }662        .padding(20).frame(width: 520)663    }664}665
Files main
Menu

Theme