Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/Savings.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / Savings.swift` 108 lines · 5420 bytes Raw Blame History 1 import Foundation 2 import CryptoKit 3 4 /// Token meter + answer cache. Goal: spend fewer model tokens and show the operator what was saved. 5 /// Counters persist per day in savings.json (numbers only, never chat text). 6 /// The answer cache lives in memory only (this cache writes no chat text to disk; the tools Hop runs keep their own records). 7 @MainActor 8 final class Savings: ObservableObject { 9 static let shared = Savings() 10 11 /// Token counts by where the request went: `local` = this Mac's own address, `network` = a .local computer, 12 /// `used` = everything else (online). No cost is recorded: Hop has no way to know it. 13 struct Day: Codable { var date = ""; var used = 0; var saved = 0; var instant = 0; var local = 0; var network: Int? } 14 @Published private(set) var today = Day() 15 private var cache: [String: String] = [:] 16 private var order: [String] = [] 17 private var file: URL { HopConfig.dir.appendingPathComponent("savings.json") } 18 19 private init() { 20 if let d = try? Data(contentsOf: file), let v = try? JSONDecoder().decode(Day.self, from: d) { today = v } 21 rollover() 22 } 23 24 private static var stamp: String { Date().formatted(.iso8601.year().month().day()) } 25 private func rollover() { if today.date != Self.stamp { today = Day(date: Self.stamp) } } 26 private func save() { 27 if let d = try? JSONEncoder().encode(today) { try? d.write(to: file, options: .atomic) } 28 } 29 30 /// Rough token count when a server reports none (about 4 characters per token). 31 nonisolated static func estimate(_ s: String) -> Int { max(1, s.utf8.count / 4) } 32 33 /// Tokens one answer took, counted by where the request went. 34 func spent(_ tokens: Int, at place: ModelEndpoint.Place) { 35 rollover() 36 switch place { 37 case .thisMac: today.local += tokens 38 case .network: today.network = (today.network ?? 0) + tokens 39 case .online: today.used += tokens 40 } 41 save() 42 } 43 44 // MARK: cache 45 nonisolated static func key(model: String, history: [ChatMessage]) -> String { 46 let s = model + "\u{1}" + history.map { $0.role + ":" + $0.text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }.joined(separator: "\u{1}") 47 return SHA256.hash(data: Data(s.utf8)).map { String(format: "%02x", $0) }.joined() 48 } 49 func lookup(_ key: String) -> String? { cache[key] } 50 func store(_ key: String, _ reply: String) { 51 guard !reply.isEmpty else { return } 52 if cache[key] == nil { order.append(key) } 53 cache[key] = reply 54 if order.count > 300 { cache[order.removeFirst()] = nil } 55 } 56 /// A repeat question answered from memory: zero tokens, zero wait. 57 func hit(saved tokens: Int) { 58 rollover() 59 today.saved += tokens; today.instant += 1 60 save() 61 } 62 63 var headline: String { Self.headline(today) } 64 /// The usage line: tokens by where they went. It never says what anything cost. 65 nonisolated static func headline(_ d: Day) -> String { 66 let parts = [d.saved > 0 ? "⚡ \(short(d.saved)) tokens not sent again" : nil, 67 d.local > 0 ? "🏠 \(short(d.local)) on this Mac" : nil, 68 (d.network ?? 0) > 0 ? "\(short(d.network ?? 0)) on your network" : nil, 69 d.used > 0 ? "\(short(d.used)) online" : nil].compactMap { $0 } 70 return parts.isEmpty ? "Today: no tokens used yet" : "Today: " + parts.joined(separator: " · ") 71 } 72 nonisolated static func short(_ n: Int) -> String { 73 n >= 1_000_000 ? String(format: "%.1fM", Double(n) / 1e6) : n >= 1000 ? String(format: "%.1fk", Double(n) / 1e3) : "\(n)" 74 } 75 } 76 77 /// Live state of each model: ready (`free`, as in not busy), busy (something else is using it) or offline. Checked only while Ask is open. 78 @MainActor 79 final class ModelStatus: ObservableObject { 80 static let shared = ModelStatus() 81 enum State { case free, busy, offline, unknown } 82 @Published private(set) var state: [String: State] = [:] 83 84 func refresh(_ models: [ModelEndpoint]) async { 85 for ep in models { state[ep.name] = await Self.probe(ep) } 86 } 87 /// One model's state. For an OpenAI-compatible server this is one `/health` request, the only request made here; 88 /// the Claude CLI is not asked (subscription CLI: always ready). 89 nonisolated static func probe(_ ep: ModelEndpoint) async -> State { 90 if ep.kind != "openai" { return .free } 91 var base = ep.baseURL 92 while base.hasSuffix("/") { base.removeLast() } 93 if base.hasSuffix("/v1") { base.removeLast(3) } 94 guard let u = URL(string: base + "/health") else { return .unknown } 95 do { 96 let (d, r) = try await Net.session.data(for: URLRequest(url: u, timeoutInterval: 2)) 97 guard (r as? HTTPURLResponse)?.statusCode == 200 else { return .offline } 98 let j = (try? JSONSerialization.jsonObject(with: d)) as? [String: Any] 99 return (j?["busy"] as? Bool == true) ? .busy : .free 100 } catch { return .offline } 101 } 102 func dot(_ name: String) -> String { 103 switch state[name] ?? .unknown { case .free: "🟢"; case .busy: "🟠"; case .offline: "⚫"; case .unknown: "⚪" } 104 } 105 func word(_ name: String) -> String { 106 switch state[name] ?? .unknown { case .free: "ready"; case .busy: "busy"; case .offline: "offline"; case .unknown: "…" } 107 } 108 }