|
|
|
@@ -3,7 +3,6 @@ import WebKit
|
|
|
|
|
|
|
|
|
|
@MainActor
|
|
|
|
|
class UsageViewModel: ObservableObject {
|
|
|
|
|
static let orgId = "daf626a9-4924-4ff3-ba98-23b523062f8e"
|
|
|
|
|
@Published var limits: [AgentLimit] = []
|
|
|
|
|
@Published var isLoading = false
|
|
|
|
|
@Published var lastUpdated: Date?
|
|
|
|
@@ -26,14 +25,14 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private var cachedOrgId: String?
|
|
|
|
|
private var burnHistoryStore: [String: [Double]] = [:]
|
|
|
|
|
private let maxHistorySamples = 24
|
|
|
|
|
private var cachedOrgId: String?
|
|
|
|
|
private var previousPercents: [String: Double] = [:]
|
|
|
|
|
private var firedThresholds: [String: Set<Int>] = [:]
|
|
|
|
|
|
|
|
|
|
init() {
|
|
|
|
|
cachedOrgId = UserDefaults.standard.string(forKey: "claude_org_id") ?? Self.orgId
|
|
|
|
|
cachedOrgId = UserDefaults.standard.string(forKey: "claude_org_id")
|
|
|
|
|
let saved = UserDefaults.standard.double(forKey: "refresh_interval")
|
|
|
|
|
refreshInterval = saved > 0 ? saved : 60
|
|
|
|
|
showInMenuBar = UserDefaults.standard.object(forKey: "show_in_menubar") as? Bool ?? true
|
|
|
|
@@ -49,6 +48,8 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
let records = await store.dataRecords(ofTypes: types)
|
|
|
|
|
let claudeRecords = records.filter { $0.displayName.contains("claude.ai") }
|
|
|
|
|
await store.removeData(ofTypes: types, for: claudeRecords)
|
|
|
|
|
cachedOrgId = nil
|
|
|
|
|
UserDefaults.standard.removeObject(forKey: "claude_org_id")
|
|
|
|
|
isSignedIn = false
|
|
|
|
|
isNotAuthenticated = true
|
|
|
|
|
lastUpdated = nil
|
|
|
|
@@ -66,18 +67,30 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
defer { isLoading = false }
|
|
|
|
|
|
|
|
|
|
do {
|
|
|
|
|
let orgId = cachedOrgId!
|
|
|
|
|
async let usageFetch = fetchUsage(orgId: orgId)
|
|
|
|
|
async let prepaidFetch = fetchPrepaidCredits(orgId: orgId)
|
|
|
|
|
async let overageFetch = fetchOverageSpendLimit(orgId: orgId)
|
|
|
|
|
async let emailFetch = fetchUserEmail()
|
|
|
|
|
let (usage, prepaid, overage, email) = try await (usageFetch, prepaidFetch, overageFetch, emailFetch)
|
|
|
|
|
if let email { userEmail = email }
|
|
|
|
|
// Fetch org ID dynamically if not cached
|
|
|
|
|
if cachedOrgId == nil {
|
|
|
|
|
let (fetchedOrgId, fetchedPlan) = try await fetchOrgId()
|
|
|
|
|
cachedOrgId = fetchedOrgId
|
|
|
|
|
if let id = cachedOrgId {
|
|
|
|
|
UserDefaults.standard.set(id, forKey: "claude_org_id")
|
|
|
|
|
}
|
|
|
|
|
if let plan = fetchedPlan { planLabel = plan }
|
|
|
|
|
}
|
|
|
|
|
guard let orgId = cachedOrgId else {
|
|
|
|
|
throw AppError.notAuthenticated
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async let usageFetch = fetchUsage(orgId: orgId)
|
|
|
|
|
async let prepaidFetch = fetchPrepaidCredits(orgId: orgId)
|
|
|
|
|
async let overageFetch = fetchOverageSpendLimit(orgId: orgId)
|
|
|
|
|
async let emailFetch = fetchUserEmail()
|
|
|
|
|
let (usage, prepaid, overage, emailResult) = try await (usageFetch, prepaidFetch, overageFetch, emailFetch)
|
|
|
|
|
if let email = emailResult.email { userEmail = email }
|
|
|
|
|
if let plan = emailResult.planLabel { planLabel = plan }
|
|
|
|
|
limits = buildLimits(from: usage)
|
|
|
|
|
extraUsage = usage.extraUsage
|
|
|
|
|
prepaidCredits = prepaid
|
|
|
|
|
overageSpendLimit = overage
|
|
|
|
|
planLabel = "Pro"
|
|
|
|
|
lastUpdated = Date()
|
|
|
|
|
isSignedIn = true
|
|
|
|
|
|
|
|
|
@@ -110,54 +123,97 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Fetch usage
|
|
|
|
|
// MARK: - Fetch org ID from bootstrap
|
|
|
|
|
|
|
|
|
|
private func fetchUsage(orgId: String) async throws -> UsageResponse {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/usage")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
|
|
|
|
|
// Inject cookies from WKWebsiteDataStore (shared with browser/Claude app)
|
|
|
|
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
|
|
|
|
let claudeCookies = cookies.filter { $0.domain.contains("claude.ai") }
|
|
|
|
|
if let header = HTTPCookie.requestHeaderFields(with: claudeCookies)["Cookie"] {
|
|
|
|
|
req.setValue(header, forHTTPHeaderField: "Cookie")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse else { throw AppError.networkError }
|
|
|
|
|
if http.statusCode == 401 || http.statusCode == 403 { throw AppError.notAuthenticated }
|
|
|
|
|
guard http.statusCode == 200 else { throw AppError.networkError }
|
|
|
|
|
|
|
|
|
|
return try JSONDecoder().decode(UsageResponse.self, from: data)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func fetchUserEmail() async throws -> String? {
|
|
|
|
|
private func fetchOrgId() async throws -> (orgId: String?, planLabel: String?) {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/bootstrap")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
|
|
|
|
let claudeCookies = cookies.filter { $0.domain.contains("claude.ai") }
|
|
|
|
|
if claudeCookies.isEmpty { throw AppError.notAuthenticated }
|
|
|
|
|
if let header = HTTPCookie.requestHeaderFields(with: claudeCookies)["Cookie"] {
|
|
|
|
|
req.setValue(header, forHTTPHeaderField: "Cookie")
|
|
|
|
|
}
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse else { throw AppError.networkError }
|
|
|
|
|
if http.statusCode == 401 || http.statusCode == 403 { throw AppError.notAuthenticated }
|
|
|
|
|
guard http.statusCode == 200 else { throw AppError.networkError }
|
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return (nil, nil) }
|
|
|
|
|
|
|
|
|
|
func planFromOrg(_ org: [String: Any]?) -> String? {
|
|
|
|
|
guard let caps = org?["capabilities"] as? [String] else { return nil }
|
|
|
|
|
guard let cap = caps.first(where: { $0.hasPrefix("claude_") }) else { return nil }
|
|
|
|
|
let name = String(cap.dropFirst("claude_".count))
|
|
|
|
|
return name.prefix(1).uppercased() + name.dropFirst().lowercased()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// account.memberships[0].organization.uuid
|
|
|
|
|
if let account = json["account"] as? [String: Any],
|
|
|
|
|
let memberships = account["memberships"] as? [[String: Any]],
|
|
|
|
|
let org = memberships.first?["organization"] as? [String: Any],
|
|
|
|
|
let uuid = org["uuid"] as? String {
|
|
|
|
|
return (uuid, planFromOrg(org))
|
|
|
|
|
}
|
|
|
|
|
// root memberships (older API shape)
|
|
|
|
|
if let memberships = json["memberships"] as? [[String: Any]],
|
|
|
|
|
let org = memberships.first?["organization"] as? [String: Any],
|
|
|
|
|
let uuid = org["uuid"] as? String {
|
|
|
|
|
return (uuid, planFromOrg(org))
|
|
|
|
|
}
|
|
|
|
|
// root organizations array
|
|
|
|
|
if let orgs = json["organizations"] as? [[String: Any]],
|
|
|
|
|
let uuid = orgs.first?["uuid"] as? String {
|
|
|
|
|
return (uuid, planFromOrg(orgs.first))
|
|
|
|
|
}
|
|
|
|
|
return (nil, nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: - Fetch usage
|
|
|
|
|
|
|
|
|
|
private func claudeCookieHeader() async -> String? {
|
|
|
|
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
|
|
|
|
let claudeCookies = cookies.filter { $0.domain.contains("claude.ai") }
|
|
|
|
|
return HTTPCookie.requestHeaderFields(with: claudeCookies)["Cookie"]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func fetchUsage(orgId: String) async throws -> UsageResponse {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/usage")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
if let cookie = await claudeCookieHeader() { req.setValue(cookie, forHTTPHeaderField: "Cookie") }
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse else { throw AppError.networkError }
|
|
|
|
|
if http.statusCode == 401 || http.statusCode == 403 { throw AppError.notAuthenticated }
|
|
|
|
|
guard http.statusCode == 200 else { throw AppError.networkError }
|
|
|
|
|
return try JSONDecoder().decode(UsageResponse.self, from: data)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func fetchUserEmail() async throws -> (email: String?, planLabel: String?) {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/bootstrap")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
if let cookie = await claudeCookieHeader() { req.setValue(cookie, forHTTPHeaderField: "Cookie") }
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return nil }
|
|
|
|
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
|
|
|
let account = json["account"] as? [String: Any],
|
|
|
|
|
let email = account["email_address"] as? String else { return nil }
|
|
|
|
|
return email
|
|
|
|
|
let account = json["account"] as? [String: Any] else { return (nil, nil) }
|
|
|
|
|
let email = account["email_address"] as? String
|
|
|
|
|
var planLabel: String? = nil
|
|
|
|
|
if let memberships = account["memberships"] as? [[String: Any]],
|
|
|
|
|
let caps = memberships.first?["organization"]?["capabilities"] as? [String],
|
|
|
|
|
let cap = caps.first(where: { $0.hasPrefix("claude_") }) {
|
|
|
|
|
let name = String(cap.dropFirst("claude_".count))
|
|
|
|
|
planLabel = name.prefix(1).uppercased() + name.dropFirst().lowercased()
|
|
|
|
|
}
|
|
|
|
|
return (email, planLabel)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private func fetchPrepaidCredits(orgId: String) async throws -> PrepaidCredits? {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/prepaid/credits")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
|
|
|
|
let claudeCookies = cookies.filter { $0.domain.contains("claude.ai") }
|
|
|
|
|
if let header = HTTPCookie.requestHeaderFields(with: claudeCookies)["Cookie"] {
|
|
|
|
|
req.setValue(header, forHTTPHeaderField: "Cookie")
|
|
|
|
|
}
|
|
|
|
|
if let cookie = await claudeCookieHeader() { req.setValue(cookie, forHTTPHeaderField: "Cookie") }
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return nil }
|
|
|
|
|
return try? JSONDecoder().decode(PrepaidCredits.self, from: data)
|
|
|
|
@@ -167,11 +223,7 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
let url = URL(string: "https://claude.ai/api/organizations/\(orgId)/overage_spend_limit")!
|
|
|
|
|
var req = URLRequest(url: url)
|
|
|
|
|
req.setValue("application/json", forHTTPHeaderField: "accept")
|
|
|
|
|
let cookies = await WKWebsiteDataStore.default().httpCookieStore.allCookies()
|
|
|
|
|
let claudeCookies = cookies.filter { $0.domain.contains("claude.ai") }
|
|
|
|
|
if let header = HTTPCookie.requestHeaderFields(with: claudeCookies)["Cookie"] {
|
|
|
|
|
req.setValue(header, forHTTPHeaderField: "Cookie")
|
|
|
|
|
}
|
|
|
|
|
if let cookie = await claudeCookieHeader() { req.setValue(cookie, forHTTPHeaderField: "Cookie") }
|
|
|
|
|
let (data, response) = try await URLSession.shared.data(for: req)
|
|
|
|
|
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { return nil }
|
|
|
|
|
return try? JSONDecoder().decode(OverageSpendLimit.self, from: data)
|
|
|
|
@@ -245,14 +297,11 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
|
|
|
|
|
private func checkLimitNotifications(for limits: [AgentLimit]) {
|
|
|
|
|
let thresholds = [80, 95]
|
|
|
|
|
|
|
|
|
|
for limit in limits {
|
|
|
|
|
let key = limit.window.rawValue
|
|
|
|
|
let curr = limit.usedPercent
|
|
|
|
|
let prev = previousPercents[key]
|
|
|
|
|
var fired = firedThresholds[key] ?? []
|
|
|
|
|
|
|
|
|
|
// Threshold warnings (80% and 95%)
|
|
|
|
|
for t in thresholds {
|
|
|
|
|
let threshold = Double(t)
|
|
|
|
|
guard curr >= threshold, prev ?? threshold < threshold, !fired.contains(t) else { continue }
|
|
|
|
@@ -263,8 +312,6 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
userInfo: ["windowName": limit.window.displayName, "percent": t]
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Reset detection: was high, now low
|
|
|
|
|
if let prev, prev > 50, curr < 20 {
|
|
|
|
|
fired.removeAll()
|
|
|
|
|
NotificationCenter.default.post(
|
|
|
|
@@ -273,7 +320,6 @@ class UsageViewModel: ObservableObject {
|
|
|
|
|
userInfo: ["windowName": limit.window.displayName]
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
firedThresholds[key] = fired
|
|
|
|
|
previousPercents[key] = curr
|
|
|
|
|
}
|
|
|
|
@@ -317,4 +363,3 @@ extension Notification.Name {
|
|
|
|
|
static let limitReset = Notification.Name("limitReset")
|
|
|
|
|
static let openUpdateSheet = Notification.Name("openUpdateSheet")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|