SPB Git

Repository Public

SettingsInsightPanes.swift 29.3 KB 460 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Settings/SettingsInsightPanes.swift3// Description: Settings panes of 2.0 that report what the server recorded: Usage & Cost (totals, per day, per model and role — an unpriced cost is said to be unpriced), Audit Log (paged, CSV export), Data Providers (health per capability), Sync (state, queue, conflicts), and the research sandbox section.4import Charts5import SwiftUI6import UniformTypeIdentifiers7import VQuantCore8import VQuantKit9import VQuantUI1011private let hair = VQTokens.Palette.line1213/// A figure of a pane: label above, tabular value, an optional sentence under it.14private struct Figure: View {15    let label: String16    let value: String17    var note: String?18    var dim = false19    var body: some View {20        VStack(alignment: .leading, spacing: 3) {21            Text(label).font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)22            Text(value).font(dim ? VQTokens.Typography.title.font : VQTokens.Typography.numLg.font).foregroundStyle(dim ? VQTokens.Palette.text2 : VQTokens.Palette.text1).lineLimit(1).minimumScaleFactor(0.7)23            if let note { Text(note).font(.caption).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true) }24        }25        .frame(maxWidth: .infinity, alignment: .leading)26        .accessibilityElement(children: .combine)27    }28}2930// MARK: - Usage & Cost3132struct UsagePane: View {33    let app: AppEnvironment34    @State private var days = 3035    @State private var report: VQUsageReport?36    @State private var error: String?37    @State private var loading = false38    @State private var measure = Measure.cost3940    enum Measure: Hashable { case cost, tokens, calls }4142    var body: some View {43        VStack(alignment: .leading, spacing: 18) {44            HStack {45                VQSegmentedControl("Period", selection: $days, options: [.init(7, "7 days"), .init(30, "30 days"), .init(90, "90 days"), .init(365, "1 year")]).accessibilityIdentifier("settings.usage.period").focusEffectDisabled()46                if loading { ProgressView().controlSize(.small) }47                Spacer()48                if let since = report?.since { Text("since \(Fmt.dateTime(since))").font(.caption).foregroundStyle(VQTokens.Palette.text3) }49            }50            if let error { PaneFailure(message: error) { Task { await load() } } }51            if let r = report {52                SettingsCard(padding: 16) {53                    VStack(alignment: .leading, spacing: 10) {54                        HStack(alignment: .top, spacing: 20) {55                            Figure(label: "Cost", value: UsageText.cost(r.totals), note: r.totals.costUsd == nil ? nil : "sum of the calls, at published prices", dim: r.totals.costUsd == nil)56                                .accessibilityIdentifier("settings.usage.cost")57                            Figure(label: "Model calls", value: (r.totals.calls ?? 0).formatted())58                            Figure(label: "Tokens read", value: UsageText.tokens(r.totals.inputTokens))59                            Figure(label: "Tokens written", value: UsageText.tokens(r.totals.outputTokens))60                        }61                        if let note = UsageText.unpricedNote(r.totals) {62                            Label(note.prefix(1).uppercased() + note.dropFirst(), systemImage: "info.circle").font(.callout).foregroundStyle(VQTokens.Palette.warn).accessibilityIdentifier("settings.usage.unpriced")63                        }64                    }65                }66                byDay(r)67                byModel(r)68                SettingsNote("Every figure here was recorded by the server when a model was called (lead, sub-analysts, auditor, reviewer, router). Costs are computed from published prices; a call to a model without one is reported as not priced and nothing is estimated in its place. Days are UTC days.")69            } else if error == nil { VQSkeletonChart(height: 180) }70        }71        .task(id: days) { await load() }72    }7374    private func value(_ c: VQUsageCounters) -> Double? {75        switch measure {76        case .cost: c.costUsd ?? c.knownCostUsd77        case .tokens: Double(c.inputTokens + c.outputTokens)78        case .calls: c.calls.map(Double.init)79        }80    }8182    @ViewBuilder private func byDay(_ r: VQUsageReport) -> some View {83        SettingsBlock("By day") {84            VQSegmentedControl("Measure", selection: $measure, options: [.init(.cost, "Cost"), .init(.tokens, "Tokens"), .init(.calls, "Calls")]).focusEffectDisabled()85        } content: {86            if r.byDay.isEmpty { Text("No model call in this period.").font(.callout).foregroundStyle(VQTokens.Palette.text3) }87            else {88                let partial = measure == .cost && r.byDay.contains { $0.counters.costUsd == nil }89                Chart(r.byDay) { d in90                    if let v = value(d.counters), let date = VQISODate.parse(d.date) {91                        BarMark(x: .value("Day", date, unit: .day), y: .value(measureName, v), width: .fixed(barWidth(r)))92                            // a day whose total is unpriced shows its known part, drawn lighter and said in the note below93                            .foregroundStyle(measure == .cost && d.counters.costUsd == nil ? VQTokens.Palette.text3 : VQTokens.Palette.text1)94                            .cornerRadius(2)95                            .accessibilityLabel(d.date).accessibilityValue(measure == .cost ? UsageText.cost(d.counters) : String(Int(v)))96                    }97                }98                .chartXScale(domain: xDomain(r))99                .chartXAxis { AxisMarks(values: .automatic(desiredCount: 6)) { _ in AxisGridLine().foregroundStyle(hair); AxisValueLabel(format: .dateTime.month(.abbreviated).day(), centered: true).font(.system(size: 10)) } }100                .chartYAxis { AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { v in101                    AxisGridLine().foregroundStyle(hair)102                    AxisValueLabel { if let d = v.as(Double.self) { Text(measure == .cost ? UsageText.usd(d) : measure == .tokens ? UsageText.tokens(Int(d)) : String(Int(d))).font(.system(size: 10, design: .monospaced)) } }103                } }104                .frame(height: 170)105                .accessibilityIdentifier("settings.usage.chart")106                if partial { Text("Lighter bars are days with at least one unpriced call: the bar is the priced part only.").font(.caption).foregroundStyle(VQTokens.Palette.text3) }107            }108        }109    }110111    private var measureName: String { switch measure { case .cost: "USD"; case .tokens: "Tokens"; case .calls: "Calls" } }112    private func xDomain(_ r: VQUsageReport) -> ClosedRange<Date> {113        let end = Calendar.current.startOfDay(for: Date()).addingTimeInterval(86400)114        return end.addingTimeInterval(-Double(max(1, r.days)) * 86400)...end115    }116    private func barWidth(_ r: VQUsageReport) -> CGFloat { r.days <= 7 ? 40 : r.days <= 30 ? 14 : r.days <= 90 ? 5 : 2 }117118    @ViewBuilder private func byModel(_ r: VQUsageReport) -> some View {119        SettingsBlock("By model and role") {120            if r.byModel.isEmpty { Text("No model call in this period.").font(.callout).foregroundStyle(VQTokens.Palette.text3) }121            else {122                Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 7) {123                    GridRow {124                        Text("Model").gridColumnAlignment(.leading); Text("Role"); Text("Calls").gridColumnAlignment(.trailing); Text("Read").gridColumnAlignment(.trailing)125                        Text("Written").gridColumnAlignment(.trailing); Text("Cost").gridColumnAlignment(.trailing)126                    }127                    .font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)128                    ForEach(Array(r.byModel.enumerated()), id: \.offset) { _, m in129                        GridRow {130                            HStack(spacing: 6) { VQProviderLogo(provider: m.provider, size: 13).foregroundStyle(VQTokens.Palette.text2); Text(ResearchModel.name(m.model)) }131                            Text(m.role?.rawValue.capitalized ?? "—").foregroundStyle(VQTokens.Palette.text2)132                            Text((m.counters.calls ?? 0).formatted()).font(VQTokens.Typography.numSm.font)133                            Text(UsageText.tokens(m.counters.inputTokens)).font(VQTokens.Typography.numSm.font)134                            Text(UsageText.tokens(m.counters.outputTokens)).font(VQTokens.Typography.numSm.font)135                            Text(UsageText.cost(m.counters)).font(VQTokens.Typography.numSm.font).foregroundStyle(m.counters.costUsd == nil ? VQTokens.Palette.warn : VQTokens.Palette.text1)136                                .help(UsageText.unpricedNote(m.counters) ?? "")137                        }138                        .font(.callout)139                    }140                }141            }142        }143    }144145    private func load() async {146        loading = true; defer { loading = false }147        do { let r = try await app.vq.models.usage(days: days); guard !Task.isCancelled else { return }; report = r; error = nil }148        catch is CancellationError {} catch { self.error = paneError(error) }149    }150}151152// MARK: - Audit log153154struct AuditPane: View {155    let app: AppEnvironment156    @State private var events: [VQAuditEvent] = []157    @State private var loaded = false158    @State private var exhausted = false159    @State private var loading = false160    @State private var error: String?161    private static let page = 50162163    var body: some View {164        VStack(alignment: .leading, spacing: 12) {165            HStack {166                Text(loaded ? "\(events.count) event\(events.count == 1 ? "" : "s") shown, newest first" : "Loading…").font(.callout).foregroundStyle(VQTokens.Palette.text2).accessibilityIdentifier("settings.audit.count")167                if loading { ProgressView().controlSize(.small) }168                Spacer()169                Button { export() } label: { Label("Export CSV…", systemImage: "square.and.arrow.up") }.disabled(events.isEmpty).accessibilityIdentifier("settings.audit.export")170            }171            if let error { PaneFailure(message: error) { Task { await more(reset: true) } } }172            if loaded, events.isEmpty, error == nil { Text("Nothing has been recorded for your account yet.").font(.callout).foregroundStyle(VQTokens.Palette.text3) }173            if !events.isEmpty {174                SettingsCard(padding: 0) {175                    VStack(spacing: 0) {176                        HStack(spacing: 12) {177                            Text("When").frame(width: 196, alignment: .leading); Text("Action").frame(width: 176, alignment: .leading)178                            Text("Target").frame(maxWidth: .infinity, alignment: .leading); Text("Device").frame(width: 104, alignment: .leading)179                        }180                        .font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3).padding(.horizontal, 12).padding(.vertical, 7)181                        ForEach(events) { e in182                            Rectangle().fill(hair).frame(height: 1)183                            HStack(alignment: .firstTextBaseline, spacing: 12) {184                                Text(e.at.map { Fmt.dateTime($0) } ?? "—").font(VQTokens.Typography.numSm.font).lineLimit(1).frame(width: 196, alignment: .leading)185                                HStack(spacing: 5) { Image(systemName: symbol(e.action)).font(.system(size: 10)).foregroundStyle(VQTokens.Palette.text3); Text(action(e.action)).lineLimit(1) }.frame(width: 176, alignment: .leading)186                                VStack(alignment: .leading, spacing: 1) {187                                    Text(e.target ?? "—").lineLimit(1).truncationMode(.middle)188                                    if let d = detail(e) { Text(d).font(.caption).foregroundStyle(VQTokens.Palette.text3).lineLimit(1) }189                                }190                                .frame(maxWidth: .infinity, alignment: .leading)191                                VStack(alignment: .leading, spacing: 1) {192                                    Text(device(e)).font(.caption).foregroundStyle(VQTokens.Palette.text2).lineLimit(1).truncationMode(.middle)193                                    if let ip = e.ip { Text(ip).font(.system(size: 10, design: .monospaced)).foregroundStyle(VQTokens.Palette.text3).lineLimit(1) }194                                }195                                .frame(width: 104, alignment: .leading).help(e.device.map { "Device \($0)" } ?? "")196                            }197                            .font(.callout).padding(.horizontal, 12).padding(.vertical, 6)198                            .accessibilityElement(children: .combine).accessibilityIdentifier("settings.audit.row.\(e.id)")199                        }200                    }201                }202                HStack {203                    if !exhausted { Button("Load \(Self.page) Older Events") { Task { await more(reset: false) } }.disabled(loading).accessibilityIdentifier("settings.audit.more") }204                    else { Text("This is the beginning of the log.").font(.caption).foregroundStyle(VQTokens.Palette.text3).accessibilityIdentifier("settings.audit.end") }205                    Spacer()206                }207            }208            SettingsNote("The server records these events for your account only; they cannot be edited from any client. The CSV contains the events loaded here. Details never carry a secret or the name of a downloaded file.")209        }210        .task { if !loaded { await more(reset: true) } }211    }212213    private func more(reset: Bool) async {214        loading = true; defer { loading = false }215        do {216            let batch = try await app.vq.research.audit(limit: Self.page, before: reset ? nil : events.last?.id)217            if reset { events = batch } else { events += batch.filter { b in !events.contains { $0.id == b.id } } }218            exhausted = batch.count < Self.page; loaded = true; error = nil219        } catch is CancellationError {} catch { self.error = paneError(error); loaded = true }220    }221222    private func export() {223        let name = "vquant-audit-\(Date().formatted(.iso8601.year().month().day())).csv"224        if let url = SavePanel.save(Data(AuditCSV.export(events).utf8), name: name, types: [.commaSeparatedText]) { app.toasts.show("\(events.count) events exported to \(url.lastPathComponent).") }225    }226227    private func action(_ a: String) -> String {228        switch a {229        case "signin.web": "Sign-in (web)"; case "signin.native": "Sign-in (app)"; case "signout.native": "Sign-out (app)"230        case "passkey.register.web": "Passkey added (web)"; case "passkey.register.native": "Passkey added (app)"231        case "device.revoke": "Device revoked"; case "passkey.delete": "Passkey removed"; case "object.delete": "Object deleted"; case "session.delete": "Conversation deleted"232        case "project.export": "Project exported"; case "memory.export": "Memories exported"; case "memory.bulk_delete": "Memories deleted in bulk"; case "report.share": "Report shared"233        default: a      // an action added later is shown by its own name234        }235    }236    private func symbol(_ a: String) -> String {237        if a.hasPrefix("signin") { return "person.badge.key" }; if a.hasPrefix("signout") { return "rectangle.portrait.and.arrow.right" }238        if a.contains("delete") || a.contains("revoke") { return "trash" }; if a.contains("export") || a.contains("share") { return "square.and.arrow.up" }239        if a.hasPrefix("passkey") { return "key" }240        return "circle"241    }242    private func detail(_ e: VQAuditEvent) -> String? {243        guard let o = e.detail?.objectValue, !o.isEmpty else { return nil }244        return o.keys.sorted().map { "\($0) \(o[$0]?.displayString ?? "")" }.joined(separator: " · ")245    }246    private func device(_ e: VQAuditEvent) -> String {247        guard let d = e.device, !d.isEmpty else { return "—" }248        if d == app.session.device?.id { return "This Mac" }249        return d.count > 14 ? String(d.prefix(8)) + "…" : d250    }251}252253// MARK: - Data providers254255struct DataProvidersPane: View {256    let app: AppEnvironment257    @State private var health: VQDataHealth?258    @State private var error: String?259    @State private var loading = false260261    var body: some View {262        VStack(alignment: .leading, spacing: 14) {263            HStack {264                Button { Task { await load() } } label: { Label("Check Again", systemImage: "arrow.clockwise") }.disabled(loading).accessibilityIdentifier("settings.providers.reload")265                if loading { ProgressView().controlSize(.small) }266                Spacer()267                if let t = health?.checkedAt { Text("checked by the server \(Fmt.relative(t))").font(.caption).foregroundStyle(VQTokens.Palette.text3) }268            }269            if let error { PaneFailure(message: error) { Task { await load() } } }270            if let h = health {271                ForEach(h.providers) { p in card(p) }272                SettingsNote("The server probes each capability with a real request to the provider. “Not in the plan” means the provider refused the request for the subscription the server holds: VQuant then asks the next source, or says the data is unavailable. Counters run since the server started. No key reaches this Mac.")273            } else if error == nil { VQSkeletonRows(rows: 6, columns: 4) }274        }275        .task { if health == nil { await load() } }276    }277278    private func card(_ p: VQDataHealth.Provider) -> some View {279        SettingsCard(padding: 0) {280            VStack(alignment: .leading, spacing: 0) {281                VStack(alignment: .leading, spacing: 5) {282                    HStack(spacing: 8) {283                        Text(p.name).font(VQTokens.Typography.heading.font)284                        if !p.configured { StatePill(text: "No key on the server", tone: .neutral) }285                        else if p.ok { StatePill(text: "Answering", tone: .good) }286                        else { StatePill(text: "Not answering", tone: .bad) }287                        Spacer()288                        if let ms = p.latencyMs { Text("\(Int(ms)) ms").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text2) }289                        if let c = p.calls { Text("\(c.formatted()) call\(c == 1 ? "" : "s") · \((p.errors ?? 0).formatted()) error\(p.errors == 1 ? "" : "s")").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3) }290                    }291                    if let n = p.notes { Text(n).font(.caption).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true) }292                    if let e = p.error { Text(e).font(.caption).foregroundStyle(VQTokens.Palette.critical).fixedSize(horizontal: false, vertical: true) }293                    if let e = p.lastError { Text("Last error\(p.lastErrorAt.map { " (\(Fmt.relative($0)))" } ?? ""): \(e)").font(.caption).foregroundStyle(VQTokens.Palette.warn).lineLimit(2) }294                }295                .padding(.horizontal, 12).padding(.vertical, 10)296                .accessibilityElement(children: .combine).accessibilityIdentifier("settings.providers.row.\(p.id)")297                if !p.capabilities.isEmpty {298                    Rectangle().fill(hair).frame(height: 1)299                    LazyVGrid(columns: [GridItem(.flexible(), spacing: 18, alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)], alignment: .leading, spacing: 6) {300                        ForEach(p.capabilities) { c in capability(c) }301                    }302                    .padding(.horizontal, 12).padding(.vertical, 10)303                }304            }305        }306    }307308    private func capability(_ c: VQDataHealth.Capability) -> some View {309        let (symbol, word, color): (String, String, Color) = {310            switch c.status.known {311            case .ok?: ("checkmark.circle", "", VQTokens.Palette.text2)312            case .plan?: ("lock", "not in the plan", VQTokens.Palette.text3)313            case .empty?: ("circle.dashed", "answered with no data", VQTokens.Palette.warn)314            case .notFound?: ("questionmark.circle", "not found", VQTokens.Palette.warn)315            case .rateLimit?: ("hourglass", "rate limited", VQTokens.Palette.warn)316            case .timeout?: ("clock.badge.exclamationmark", "timed out", VQTokens.Palette.critical)317            case .network?: ("wifi.slash", "unreachable", VQTokens.Palette.critical)318            case .error?: ("xmark.circle", "error", VQTokens.Palette.critical)319            case nil: ("circle", c.status.rawValue, VQTokens.Palette.text3)320            }321        }()322        return HStack(alignment: .firstTextBaseline, spacing: 6) {323            Image(systemName: symbol).font(.system(size: 11)).foregroundStyle(color).frame(width: 14)324            VStack(alignment: .leading, spacing: 1) {325                Text(c.label.prefix(1).uppercased() + c.label.dropFirst()).font(.callout).foregroundStyle(c.ok ? VQTokens.Palette.text1 : VQTokens.Palette.text2)326                if !word.isEmpty || c.detail != nil {327                    Text([word.isEmpty ? nil : word, c.detail].compactMap { $0 }.joined(separator: " — ")).font(.caption).foregroundStyle(color).lineLimit(2)328                }329            }330            Spacer(minLength: 4)331            if let ms = c.latencyMs, c.ok { Text("\(Int(ms)) ms").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3) }332        }333        .accessibilityElement(children: .combine)334    }335336    private func load() async {337        loading = true; defer { loading = false }338        do { health = try await app.vq.data.health(); error = nil } catch is CancellationError {} catch { self.error = paneError(error) }339    }340}341342// MARK: - Sync343344struct SyncPane: View {345    let app: AppEnvironment346    var body: some View {347        VStack(alignment: .leading, spacing: 14) {348            SettingsCard(padding: 4) {349                // the same panel as the toolbar's sync indicator: state, queue, cursor, last pull, notices with keep mine / keep theirs350                SyncPanel(app: app)351            }352            .accessibilityIdentifier("settings.sync.panel")353            if let s = app.sync.active {354                SettingsBlock("What is synced") {355                    Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 18, verticalSpacing: 6) {356                        count("Watchlists", s.watchlists.items.count, s.watchlists.pendingIDs.count)357                        count("Portfolios", s.portfolios.items.count, s.portfolios.pendingIDs.count)358                        count("Saved charts", s.charts.items.count, s.charts.pendingIDs.count)359                        count("Workspaces and window layouts", s.workspaces.items.count, s.workspaces.pendingIDs.count)360                        count("Research projects", s.projects.items.count, s.projects.pendingIDs.count)361                        count("Notes", s.notes.items.count, s.notes.pendingIDs.count)362                        count("Reviews", s.reviews.items.count, s.reviews.pendingIDs.count)363                        count("Preferences", s.preferences.items.count, s.preferences.pendingIDs.count)364                    }365                }366            }367            SettingsBlock("Coming from VQuant 1") {368                SettingsNote(app.sync.migrationNote ?? "The watchlists and window layouts that VQuant 1 kept on this Mac are moved to your account the first time this Mac signs in with VQuant 2: once, without duplicates, and the local file is kept as a backup. Nothing was waiting to be moved in this session.")369                    .accessibilityIdentifier("settings.sync.migration")370            }371            SettingsNote("Changes made while the server is unreachable are kept on this Mac, in order, and sent when the connection returns. When two devices edited the same object, the changes are merged per field (lists element by element); a workspace is kept whole, and a notice above lets you choose the other version. The copy of your account on this Mac is encrypted with a key in the Keychain and erased at sign-out. Conversations, analyses and computations are not copied: they stay on the server and are listed from it.")372        }373    }374375    private func count(_ name: String, _ n: Int, _ pending: Int) -> some View {376        GridRow {377            Text(name)378            Text("\(n)").font(VQTokens.Typography.numSm.font).gridColumnAlignment(.trailing)379            Text(pending == 0 ? "" : "\(pending) waiting to be sent").font(.caption).foregroundStyle(VQTokens.Palette.warn)380        }381        .font(.callout)382    }383}384385// MARK: - Research sandbox (a section of the Research pane)386387struct SandboxSection: View {388    let app: AppEnvironment389    @State private var status: VQSandboxStatus?390    @State private var error: String?391392    var body: some View {393        SettingsBlock("Sandbox of the agent's code", overline: "Autonomous research") {394            if let s = status { StatePill(text: s.enforced ? "Enforced" : "NOT enforced on this server", tone: s.enforced ? .good : .bad).accessibilityIdentifier("settings.research.sandbox") }395        } content: {396            if let s = status {397                if !s.enforced {398                    Label("This server cannot isolate the code the research agent writes: a run executes with the server account's own access.", systemImage: "exclamationmark.triangle")399                        .font(.callout).foregroundStyle(VQTokens.Palette.critical).fixedSize(horizontal: false, vertical: true)400                }401                if s.mechanism != nil || s.note != nil {402                    Text([s.mechanism.map { "Mechanism: \($0)." }, s.note].compactMap { $0 }.joined(separator: " ")).font(.callout).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true)403                }404                SettingsCard {405                    VStack(alignment: .leading, spacing: 12) {406                        Text("Limits of one run").font(VQTokens.Typography.overline.font).textCase(.uppercase).foregroundStyle(VQTokens.Palette.text3)407                        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), alignment: .topLeading), count: 3), alignment: .leading, spacing: 10) {408                            ForEach(limits(s), id: \.0) { name, value in409                                VStack(alignment: .leading, spacing: 1) {410                                    Text(value).font(VQTokens.Typography.numMd.font)411                                    Text(name).font(.caption).foregroundStyle(VQTokens.Palette.text3)412                                }413                                .accessibilityElement(children: .combine)414                            }415                        }416                        Rectangle().fill(hair).frame(height: 1)417                        Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 6) {418                            GridRow {419                                Text("Reached without asking").foregroundStyle(VQTokens.Palette.text2)420                                Text(s.defaultNetwork.isEmpty ? "nothing" : s.defaultNetwork.joined(separator: " · ")).fixedSize(horizontal: false, vertical: true)421                            }422                            if let o = s.openNetwork { GridRow { Text("After your approval").foregroundStyle(VQTokens.Palette.text2); Text(o).fixedSize(horizontal: false, vertical: true) } }423                            GridRow { Text("Largest dataset upload").foregroundStyle(VQTokens.Palette.text2); Text(ByteCountFormatter.string(fromByteCount: Int64(s.uploadMaxBytes), countStyle: .file)).font(VQTokens.Typography.numSm.font) }424                        }425                        .font(.callout)426                    }427                }428            } else if let error {429                PaneFailure(message: error) { Task { await load() } }430            } else { VQSkeletonText(lines: 3) }431        }432        .task { await load() }433    }434435    private func load() async {436        do { status = try await VQResearchAgentClient(client: app.vq.client).sandbox(); error = nil } catch is CancellationError {} catch { self.error = paneError(error) }437    }438439    /// The limits the server states, in words; a limit of 0 means the server sets none.440    private func limits(_ s: VQSandboxStatus) -> [(String, String)] {441        func v(_ key: String) -> Double? { s.limits[key].flatMap { $0 > 0 ? $0 : nil } }442        func span(_ seconds: Double) -> String {443            if seconds >= 3600 { let h = seconds / 3600; return (h == h.rounded() ? String(Int(h)) : String(format: "%.1f", h)) + " h" }444            if seconds >= 60 { return "\(Int((seconds / 60).rounded())) min" }445            return "\(Int(seconds)) s"446        }447        func size(_ mb: Double) -> String { mb >= 1024 ? (mb.truncatingRemainder(dividingBy: 1024) == 0 ? "\(Int(mb / 1024)) GB" : String(format: "%.1f GB", mb / 1024)) : "\(Int(mb)) MB" }448        var out: [(String, String)] = []449        out.append(("processor time", v("cpuSeconds").map(span) ?? "no limit"))450        out.append(("memory", v("memoryMb").map(size) ?? "no limit"))451        out.append(("wall clock", v("wallMs").map { span($0 / 1000) } ?? "no limit"))452        out.append(("processes", v("maxProcesses").map { String(Int($0)) } ?? "no limit"))453        out.append(("largest file", v("fileMb").map(size) ?? "no limit"))454        out.append(("workspace on disk", v("diskMb").map(size) ?? "no limit"))455        let known: Set<String> = ["cpuSeconds", "memoryMb", "wallMs", "maxProcesses", "fileMb", "diskMb"]456        for k in s.limits.keys.sorted() where !known.contains(k) { out.append((k, Fmt.number(s.limits[k]))) }457        return out458    }459}460
Files main
Menu

Theme