SPB Git

Repository Public

MacLogic.swift 11.7 KB 211 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Next/MacLogic.swift3// Description: Pure logic of the Mac shell, free of UI so that `swift test` covers it (SwiftPM target VQuantAppLogic): the table of keyboard shortcuts and its collision check, the payload that routes a clicked notification, the audit CSV, and how a cost that may be unpriced is worded.4import Foundation5import VQuantCore6import VQuantKit78// MARK: keyboard shortcuts910/// One keyboard shortcut of the menu bar. The menus are built from this table (`AppShortcuts`), and the unit tests11/// check the table for collisions, so a shortcut cannot be given twice or taken from the system by accident.12nonisolated struct AppShortcut: Sendable, Hashable, Identifiable {13    struct Modifiers: OptionSet, Sendable, Hashable {14        let rawValue: Int15        static let command = Modifiers(rawValue: 1), shift = Modifiers(rawValue: 2), option = Modifiers(rawValue: 4), control = Modifiers(rawValue: 8)16    }17    /// Stable name of the command (`research.stop`).18    var id: String19    var title: String20    /// The key, lowercased ("k", "1", "." or "return").21    var key: String22    var modifiers: Modifiers2324    /// `⌃⌥⇧⌘K`, in the order macOS writes modifiers.25    var display: String {26        var s = ""27        if modifiers.contains(.control) { s += "⌃" }28        if modifiers.contains(.option) { s += "⌥" }29        if modifiers.contains(.shift) { s += "⇧" }30        if modifiers.contains(.command) { s += "⌘" }31        return s + (key == "return" ? "↩" : key.uppercased())32    }33    /// What makes two shortcuts the same keystroke.34    var chord: String { "\(modifiers.rawValue):\(key.lowercased())" }35}3637nonisolated enum AppShortcuts {38    private static func s(_ id: String, _ title: String, _ key: String, _ m: AppShortcut.Modifiers) -> AppShortcut { AppShortcut(id: id, title: title, key: key, modifiers: m) }3940    // File41    static let newChartWindow = s("file.newChart", "New chart window", "n", [.command, .shift])42    static let saveLayout = s("file.saveLayout", "Save the window layout", "s", [.command, .shift])43    // View: the first nine sections44    static func section(_ index: Int) -> AppShortcut { s("view.section\(index + 1)", "Go to section \(index + 1)", String(index + 1), .command) }45    // Data46    static let palette = s("data.palette", "Command palette", "k", .command)47    static let findSymbol = s("data.findSymbol", "Find a symbol", "f", [.command, .option])48    static let syncNow = s("data.syncNow", "Sync now", "s", [.command, .option])49    static let refresh = s("data.refresh", "Refresh now", "r", .command)50    static let chartSymbol = s("data.chart", "Chart the current symbol", "g", .command)51    static let detachChart = s("data.detach", "Detach the chart into its own window", "d", [.command, .shift])52    // Research53    static let newConversation = s("research.newConversation", "New conversation", "n", [.command, .option])54    static let newStudy = s("research.newStudy", "New research study", "r", [.command, .shift])55    static let attachDataset = s("research.attach", "Attach a dataset", "a", [.command, .shift])56    static let stopAnalysis = s("research.stop", "Stop the analysis", ".", .command)57    // Lab58    static let labCatalogue = s("lab.catalogue", "Open the Quant Lab catalogue", "l", [.command, .shift])59    static let labRunAgain = s("lab.runAgain", "Run the computation again", "r", [.command, .option])60    // App61    static let lock = s("app.lock", "Lock VQuant", "l", [.command, .control])6263    /// Every shortcut the app's own menus define.64    static let all: [AppShortcut] = (0..<9).map(section) + [65        newChartWindow, saveLayout, palette, findSymbol, syncNow, refresh, chartSymbol, detachChart,66        newConversation, newStudy, attachDataset, stopAnalysis, labCatalogue, labRunAgain, lock,67    ]6869    /// Keystrokes macOS or the standard menus of a SwiftUI app already own in this app: the app menu, File, Edit,70    /// View (sidebar, full screen, toolbar), Window, and the system-wide ones that never reach an application.71    static let reserved: [AppShortcut] = [72        s("sys.settings", "Settings", ",", .command), s("sys.hide", "Hide VQuant", "h", .command), s("sys.hideOthers", "Hide Others", "h", [.command, .option]),73        s("sys.quit", "Quit", "q", .command), s("sys.quitKeep", "Quit and Keep Windows", "q", [.command, .option]),74        s("sys.lockScreen", "Lock Screen", "q", [.command, .control]), s("sys.logOut", "Log Out", "q", [.command, .shift]),75        s("sys.newWindow", "New Window", "n", .command), s("sys.close", "Close", "w", .command), s("sys.closeAll", "Close All", "w", [.command, .option]),76        s("sys.undo", "Undo", "z", .command), s("sys.redo", "Redo", "z", [.command, .shift]), s("sys.cut", "Cut", "x", .command), s("sys.copy", "Copy", "c", .command),77        s("sys.paste", "Paste", "v", .command), s("sys.pasteMatch", "Paste and Match Style", "v", [.command, .option, .shift]), s("sys.selectAll", "Select All", "a", .command),78        s("sys.emoji", "Emoji & Symbols", " ", [.command, .control]), s("sys.spotlight", "Spotlight", " ", .command),79        s("sys.sidebar", "Show or Hide Sidebar", "s", [.command, .control]), s("sys.fullScreen", "Enter Full Screen", "f", [.command, .control]),80        s("sys.toolbar", "Show or Hide Toolbar", "t", [.command, .option]), s("sys.minimize", "Minimize", "m", .command),81        s("sys.cycleWindows", "Cycle Through Windows", "`", .command), s("sys.forceQuit", "Force Quit", "escape", [.command, .option]),82        s("sys.screenshot3", "Screenshot", "3", [.command, .shift]), s("sys.screenshot4", "Screenshot", "4", [.command, .shift]), s("sys.screenshot5", "Screenshot", "5", [.command, .shift]),83        s("sys.dock", "Show or Hide the Dock", "d", [.command, .option]), s("sys.help", "Help", "?", [.command, .shift]),84    ]8586    /// Pairs of shortcuts that are the same keystroke, among the app's own and against the reserved ones.87    static func collisions(_ own: [AppShortcut] = all, reserved: [AppShortcut] = reserved) -> [(AppShortcut, AppShortcut)] {88        var out: [(AppShortcut, AppShortcut)] = []89        var seen: [String: AppShortcut] = [:]90        for r in reserved { seen[r.chord] = r }91        for o in own {92            if let other = seen[o.chord] { out.append((other, o)) } else { seen[o.chord] = o }93        }94        return out95    }96}9798// MARK: notification routing99100/// What a system notification of the app is about, so that clicking it opens the right place. Travels in the101/// notification's `userInfo` as two strings.102nonisolated enum NotificationRoute: Sendable, Equatable {103    /// An analysis finished: open that conversation (nil = the conversation is not known, open Research).104    case conversation(String?)105    /// The research agent waits for an approval in that conversation.106    case approval(sessionId: String)107    /// A quant job finished.108    case quantJob(String)109110    static let kindKey = "vq.kind", idKey = "vq.id"111112    var userInfo: [String: String] {113        switch self {114        case .conversation(let id): return id.map { [Self.kindKey: "conversation", Self.idKey: $0] } ?? [Self.kindKey: "conversation"]115        case .approval(let id): return [Self.kindKey: "approval", Self.idKey: id]116        case .quantJob(let id): return [Self.kindKey: "quantJob", Self.idKey: id]117        }118    }119120    init?(userInfo: [AnyHashable: Any]) {121        let id = (userInfo[Self.idKey] as? String).flatMap { $0.isEmpty ? nil : $0 }122        switch userInfo[Self.kindKey] as? String {123        case "conversation": self = .conversation(id)124        case "approval": guard let id else { return nil }; self = .approval(sessionId: id)125        case "quantJob": guard let id else { return nil }; self = .quantJob(id)126        default: return nil127        }128    }129130    /// `approval:<sessionId>`, `conversation:<sessionId>`, `quantJob:<id>` (DEBUG launch argument `-VQXNotify`).131    init?(argument: String) {132        let parts = argument.split(separator: ":", maxSplits: 1).map(String.init)133        guard let kind = parts.first else { return nil }134        self.init(userInfo: [Self.kindKey: kind, Self.idKey: parts.count > 1 ? parts[1] : ""])135    }136}137138// MARK: audit CSV139140nonisolated enum AuditCSV {141    static let header = ["id", "time_utc", "action", "target", "device", "ip", "detail"]142143    static func field(_ s: String) -> String {144        s.contains(where: { $0 == "," || $0 == "\"" || $0 == "\n" || $0 == "\r" }) ? "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : s145    }146147    /// One line per event, newest first as given; `detail` is the event's JSON, compact, keys sorted.148    static func export(_ events: [VQAuditEvent]) -> String {149        let iso = ISO8601DateFormatter()150        var lines = [header.joined(separator: ",")]151        for e in events {152            let detail = e.detail.map { String(decoding: $0.data(), as: UTF8.self) } ?? ""153            lines.append([String(e.id), e.at.map(iso.string(from:)) ?? "", e.action, e.target ?? "", e.device ?? "", e.ip ?? "", detail].map(field).joined(separator: ","))154        }155        return lines.joined(separator: "\r\n") + "\r\n"156    }157}158159// MARK: cost wording160161/// How token counters are said. A cost is never guessed: when one call has no known price the total is "not priced",162/// and the part that is known is stated beside it.163nonisolated enum UsageText {164    static func usd(_ v: Double) -> String {165        let digits = abs(v) >= 100 ? 2 : abs(v) >= 1 ? 3 : 4166        return "$" + String(format: "%.\(digits)f", v)167    }168169    /// `"$0.2461"`, or `"not priced"` when the server reports no total.170    static func cost(_ c: VQUsageCounters) -> String { c.costUsd.map(usd) ?? "not priced" }171172    /// The sentence under an unpriced total; nil when the total is priced.173    static func unpricedNote(_ c: VQUsageCounters) -> String? {174        guard c.costUsd == nil else { return nil }175        let n = c.unpricedCalls ?? 0176        let calls = n > 0 ? "\(n) call\(n == 1 ? "" : "s") went to a model with no published price" : "at least one call went to a model with no published price"177        if let k = c.knownCostUsd, k > 0 { return "\(calls); the priced calls add up to \(usd(k))." }178        return "\(calls); nothing is estimated in its place."179    }180181    static func tokens(_ n: Int) -> String {182        let v = Double(n)183        if n >= 1_000_000 { return String(format: "%.2f M", v / 1e6) }184        if n >= 10_000 { return String(format: "%.1f k", v / 1e3) }185        return n.formatted(.number.grouping(.automatic))186    }187188    /// `"$2 in · $10 out per MTok"`, or `"not stated"` when neither the repository nor the provider states a price.189    static func pricing(_ p: VQModelInfo.Pricing?) -> String {190        guard let p, p.inputPerMTok != nil || p.outputPerMTok != nil else { return "not stated" }191        func n(_ v: Double?) -> String { v.map { $0 == $0.rounded() ? String(Int($0)) : String(format: "%.2f", $0) }.map { "$" + $0 } ?? "—" }192        return "\(n(p.inputPerMTok)) in · \(n(p.outputPerMTok)) out"193    }194195    /// `"1 M"`, `"200 k"`, or `"not stated"`.196    static func context(_ tokens: Int?) -> String {197        guard let tokens, tokens > 0 else { return "not stated" }198        if tokens >= 1_000_000 { let m = Double(tokens) / 1e6; return (m == m.rounded() ? String(Int(m)) : String(format: "%.2f", m)) + " M" }199        return "\(Int((Double(tokens) / 1000).rounded())) k"200    }201202    /// Why a model of the registry cannot be picked (nil when it can).203    static func notSelectableReason(_ m: VQModelInfo, providerConfigured: Bool) -> String? {204        if m.selectable { return nil }205        if !providerConfigured { return "no key for this provider on the server" }206        if !m.available { return "not in the provider's listing" }207        if !m.capabilities.tools { return "does not declare tool use" }208        return "not validated with the agent's tool loop"209    }210}211
Files main
Menu

Theme