diff --git a/README.ja.md b/README.ja.md index a6f9ebd48..6c1aa28d9 100644 --- a/README.ja.md +++ b/README.ja.md @@ -75,7 +75,7 @@ PokeTokenBar は、あなたがすでに使っている AI コーディングト 設定

設定はお好みで

-メニューバー表示項目、更新間隔(1–15分/手動)、ログイン時に起動、上限セクションだけを隠す Keychain オフ、警告/危険の閾値つき上限通知、パートナーのイベント通知。韓国語/英語/日本語の UI とポケモン名を完備。 +メニューバー表示項目、更新間隔(1–15分/手動)、ログイン時に起動、上限セクションだけを隠す Keychain オフ、警告/危険の閾値つき上限通知、パートナーのイベント通知、そして Max/Pro/Team のコストを倍率で示す任意の月額プラン料金。韓国語/英語/日本語の UI とポケモン名を完備。 @@ -101,6 +101,7 @@ PokeTokenBar は、あなたがすでに使っている AI コーディングト - **サービス別タブ** — Claude Code・Codex・Gemini CLI・Antigravity・OpenCode・Hermes Agent・Cursor・Grok CLI・Copilot CLI・Kiro CLI・Pi Agent のうち2つ以上が検出されると、小さなタブでサービス別の詳細を切替(今日の合計は合算のまま)。 - **公式の上限** — Claude・Codex・Antigravity の5時間/週間使用率とリセットのカウントダウンを、今日の数字のすぐ下に。 - **消費予測** — 現在の5時間ウィンドウが100%に達する時刻を予測。 +- **プランレバレッジ** — Max/Pro/Team ではコストに API換算ラベルが付き、月額プラン料金を入力すると(設定 → 詳細)ポップオーバーに今月分の `プラン $100.00/月 · API換算 $2783.33 · 27.8×` が1行追加されます。料金を空にすると非表示。 - **アプリ内アップデート** — ワンクリックの更新確認、設定に現在のバージョンを表示。 ## 対応ツール diff --git a/README.ko.md b/README.ko.md index f56e5f213..5542100d9 100644 --- a/README.ko.md +++ b/README.ko.md @@ -75,7 +75,7 @@ PokeTokenBar는 당신이 이미 태우고 있는 AI 코딩 토큰(Claude Code 설정

설정에서 취향대로

-메뉴바 표시 항목, 새로고침 간격(1–15분/수동), 로그인 시 자동 시작, 한도 섹션만 숨기는 Keychain 끄기, 경고/임박 임계값 한도 알림, companion 이벤트 알림. 한국어/영어/일본어 UI·포켓몬 이름 완비. +메뉴바 표시 항목, 새로고침 간격(1–15분/수동), 로그인 시 자동 시작, 한도 섹션만 숨기는 Keychain 끄기, 경고/임박 임계값 한도 알림, companion 이벤트 알림, 그리고 Max/Pro/Team 비용을 배수로 보여 주는 선택적 월 플랜 가격. 한국어/영어/일본어 UI·포켓몬 이름 완비. @@ -101,6 +101,7 @@ PokeTokenBar는 당신이 이미 태우고 있는 AI 코딩 토큰(Claude Code - **서비스별 탭** — Claude Code·Codex·Gemini CLI·Antigravity·OpenCode·Hermes Agent·Cursor·Grok CLI·Copilot CLI·Kiro CLI·Pi Agent 중 2개 이상 감지되면 작은 탭으로 상세를 서비스별 전환(오늘 합계는 통합 유지). - **공식 한도** — Claude·Codex·Antigravity 5시간/주간 사용률 + 리셋 카운트다운을 오늘 숫자 바로 아래에. - **소진 예측** — 현재 5시간 창이 100%에 도달할 시각 예측. +- **플랜 레버리지** — Max/Pro/Team 은 비용에 API 환산 라벨이 붙고, 월 플랜 가격을 적으면(설정 → 고급) 팝오버에 이번 달 기준 `플랜 $100.00/월 · API 환산 $2783.33 · 27.8×` 한 줄이 추가됩니다. 가격을 비우면 숨겨집니다. - **인앱 업데이트** — 원클릭 업데이트 확인, 설정에 현재 버전 표시. ## 지원 도구 diff --git a/README.md b/README.md index fba9b54c2..e4ddb33f0 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ The Pokédex folds every species you've owned into one cell — 24 per pa Settings

Tune it your way

-Menu-bar items, refresh interval (1–15 min or manual), launch at login, a Keychain opt-out that just hides the limits section, limit alerts with warning/critical thresholds, and companion event notifications. Full KO / EN / JA UI and Pokémon names. +Menu-bar items, refresh interval (1–15 min or manual), launch at login, a Keychain opt-out that just hides the limits section, limit alerts with warning/critical thresholds, companion event notifications, and an optional monthly plan price that turns Max/Pro/Team cost figures into a leverage multiple. Full KO / EN / JA UI and Pokémon names. @@ -101,6 +101,7 @@ The tokens you've already used are your currency. Spend them in the new Shop< - **Per-service tabs** — when two or more of Claude Code, Codex, Gemini CLI, Antigravity, OpenCode, Hermes Agent, Cursor, Grok CLI, Copilot CLI, Kiro CLI, and Pi Agent are detected, compact tabs switch between them; today's total stays combined. - **Official limits** — Claude, Codex & Antigravity 5-hour / weekly utilization with reset countdowns, right under today's numbers. - **Burn-rate forecast** — projects when the current 5h window hits 100%. +- **Plan leverage** — on Max/Pro/Team, cost figures are labelled API-equivalent; enter your monthly plan price (Settings → Advanced) and the popover adds `Plan $100.00/mo · API-equiv $2783.33 · 27.8×` for the calendar month. Leave the price empty to hide it. - **In-app updates** — one-click update check; current version shown in Settings. ## Works with diff --git a/Sources/PokeTokenBar/Core/Localization.swift b/Sources/PokeTokenBar/Core/Localization.swift index d620390e3..5de766e8b 100644 --- a/Sources/PokeTokenBar/Core/Localization.swift +++ b/Sources/PokeTokenBar/Core/Localization.swift @@ -28,6 +28,15 @@ struct L { var todayTokens: String { t("오늘 사용한 토큰", "Today's tokens", "本日のトークン", "Tokens de hoy", "Tokens du jour", "Tokens de hoje") } var thisWeek: String { t("이번 주", "This week", "今週", "Esta semana", "Cette semaine", "Esta semana") } var thisMonth: String { t("이번 달", "This month", "今月", "Este mes", "Ce mois-ci", "Este mês") } + /// Max/Pro/Team 레버리지 행 — plan/apiEquiv 는 `TokenFormatter.cost`, multiple 은 `TokenFormatter.multiple`. + func planLeverageRow(plan: String, apiEquiv: String, multiple: String) -> String { + t("플랜 \(plan)/월 · API 환산 \(apiEquiv) · \(multiple)", + "Plan \(plan)/mo · API-equiv \(apiEquiv) · \(multiple)", + "プラン \(plan)/月 · API換算 \(apiEquiv) · \(multiple)", + "Plan \(plan)/mes · equiv. API \(apiEquiv) · \(multiple)", + "Forfait \(plan)/mois · éq. API \(apiEquiv) · \(multiple)", + "Plano \(plan)/mês · equiv. API \(apiEquiv) · \(multiple)") + } // MARK: 한도 섹션 var limitsOfficial: String { t("한도 (공식)", "Limits (official)", "上限(公式)", "Límites (oficial)", "Limites (officiel)", "Limites (oficiais)") } @@ -123,6 +132,8 @@ struct L { var menuBarItems: String { t("메뉴바 표시 항목 (복수 선택)", "Menu bar items (multi-select)", "メニューバー表示項目(複数選択)", "Elementos de la barra de menús (selección múltiple)", "Éléments de la barre des menus (sélection multiple)", "Itens da barra de menus (seleção múltipla)") } var todayTokensShort: String { t("오늘 토큰", "Today's tokens", "本日のトークン", "Tokens de hoy", "Tokens du jour", "Tokens de hoje") } var todayCost: String { t("오늘 비용 ($)", "Today's cost ($)", "本日のコスト ($)", "Coste de hoy ($)", "Coût du jour ($)", "Custo de hoje ($)") } + /// Max/Pro/Team 팝오버 비용 접미사 — 숫자가 API 환산가임을 표시. 짧아야 캡션 폭에 들어간다. + var apiEquivalentCaption: String { t("(API 환산)", "(API-equiv.)", "(API換算)", "(equiv. API)", "(éq. API)", "(equiv. API)") } var limitPercent: String { t("한도 %", "Limit %", "上限 %", "Límite %", "Limite %", "Limite %") } var limitDisplayModeLabel: String { t("한도 표시 방식", "Limit display", "上限の表示", "Visualización del límite", "Affichage de la limite", "Exibição do limite") } var limitDisplayUsed: String { t("사용량", "Used", "使用量", "Usado", "Utilisé", "Usado") } @@ -192,6 +203,16 @@ struct L { var warning: String { t("경고", "Warning", "警告", "Aviso", "Avertissement", "Aviso") } var critical: String { t("임박", "Critical", "切迫", "Crítico", "Critique", "Crítico") } var aggregationNote: String { t("토큰 집계 기준: totalTokens (input + output + cache, 로컬 날짜)", "Token basis: totalTokens (input + output + cache, local date)", "集計基準: totalTokens (input + output + cache, ローカル日付)", "Base de cálculo: totalTokens (input + output + cache, fecha local)", "Base de calcul : totalTokens (input + output + cache, date locale)", "Base de cálculo: totalTokens (input + output + cache, data local)") } + var planPriceLabel: String { t("월 플랜 가격 ($)", "Monthly plan price ($)", "月額プラン料金 ($)", "Precio mensual del plan ($)", "Prix mensuel du forfait ($)", "Preço mensal do plano ($)") } + var planPriceHint: String { + t("선택 사항. Max/Pro/Team 일 때 팝오버에 이번 달 API 환산 비용 대비 배수를 표시합니다. 비우면 숨김.", + "Optional. On Max/Pro/Team the popover shows this month's API-equivalent cost as a multiple of what you pay. Leave empty to hide.", + "任意。Max/Pro/Team の場合、今月のAPI換算コストを支払額に対する倍率でポップオーバーに表示します。空欄で非表示。", + "Opcional. En Max/Pro/Team el popover muestra el coste equivalente en API de este mes como múltiplo de lo que pagas. Déjalo vacío para ocultarlo.", + "Facultatif. Sur Max/Pro/Team, le popover affiche le coût équivalent API du mois en multiple de ce que vous payez. Laissez vide pour masquer.", + "Opcional. No Max/Pro/Team o painel mostra o custo equivalente em API deste mês como múltiplo do que você paga. Deixe vazio para ocultar.") + } + var planPricePlaceholder: String { t("예: 100", "e.g. 100", "例: 100", "p. ej. 100", "ex. 100", "ex.: 100") } var customScanProviderLabel: String { t("프로바이더", "Provider", "プロバイダー", "Proveedor", "Fournisseur", "Provedor") } var customScanRootsLabel: String { t("추가 스캔 폴더", "Additional scan folders", "追加スキャンフォルダ", "Carpetas de escaneo adicionales", "Dossiers d'analyse supplémentaires", "Pastas extras para escanear") } var customScanRootsHint: String { diff --git a/Sources/PokeTokenBar/Core/Models.swift b/Sources/PokeTokenBar/Core/Models.swift index dce241b64..19419cd95 100644 --- a/Sources/PokeTokenBar/Core/Models.swift +++ b/Sources/PokeTokenBar/Core/Models.swift @@ -227,6 +227,26 @@ struct LimitStatus: Decodable, Sendable { return base } + /// Max/Pro/Team 은 정액 구독이라 ModelPricing × tokens 가 청구서가 아니다. + /// Free·API 키(`subscriptionType` 없음)는 그 숫자가 비용에 가깝다. + /// 자격증명 JSON 이라 대소문자 섞임을 허용한다. 범용 합계 경로에 providerID 분기를 + /// 넣지 않기 위해 판정은 플랜이 실리는 이 타입에만 둔다. + var labelsCostAsAPIEquivalent: Bool { + switch subscriptionType?.lowercased() { + case "max", "pro", "team": return true + default: return false + } + } + + /// 이슈 #200 항목 2 — 사용자가 설정에 적은 월 플랜 가격 대비 이번 달 API 환산 비용. + /// 정액 구독(`labelsCostAsAPIEquivalent`)이고 가격이 양수일 때만 의미가 있다. + /// 가격표를 하드코딩하지 않는다(플랜 가격은 좌석·지역별로 다르고 바뀐다). + func planLeverage(planPrice: Double, monthAPIEquivalent: Double?) -> PlanLeverage? { + guard labelsCostAsAPIEquivalent, planPrice > 0, planPrice.isFinite, + let monthAPIEquivalent else { return nil } + return PlanLeverage(planPrice: planPrice, apiEquivalent: monthAPIEquivalent) + } + /// 계정 라벨 — "email · 조직명". 개인 플랜의 자동 생성 조직명("'s Organization")은 /// 이메일과 중복 정보라 생략한다(조직명에 이메일이 포함되는지로 판정). 이메일 없으면 nil — /// 조직명만으로는 어느 로그인인지 특정되지 않아 부분 라벨을 만들지 않는다. @@ -484,6 +504,15 @@ public struct AntigravityRateLimitStatus: Decodable, Sendable { // MARK: - Provider snapshot +/// "플랜 $100/mo · API 환산 $2,783 · 27.8×" 한 줄의 재료. `multiple` 은 이번 달(달력 월) 기준. +struct PlanLeverage: Sendable, Equatable { + /// 사용자가 설정에 입력한 월 플랜 가격(USD). 항상 > 0. + var planPrice: Double + /// 이번 달 Claude API 환산 비용(ModelPricing × tokens). + var apiEquivalent: Double + var multiple: Double { apiEquivalent / planPrice } +} + struct ProviderSnapshot: Sendable, Identifiable { var providerID: String var displayName: String diff --git a/Sources/PokeTokenBar/Core/TokenFormatter.swift b/Sources/PokeTokenBar/Core/TokenFormatter.swift index a0115fa68..6bba70fa0 100644 --- a/Sources/PokeTokenBar/Core/TokenFormatter.swift +++ b/Sources/PokeTokenBar/Core/TokenFormatter.swift @@ -30,8 +30,10 @@ enum TokenFormatter { return f.string(from: NSNumber(value: value)) ?? "\(value)" } - static func cost(_ usd: Double) -> String { - String(format: "$%.2f", usd) + static func cost(_ usd: Double, labeled suffix: String? = nil) -> String { + let figure = String(format: "$%.2f", usd) + guard let suffix, !suffix.isEmpty else { return figure } + return "\(figure) \(suffix)" } /// 메뉴바용 짧은 비용 표기: $9.5 / $311 / $1.2K @@ -41,10 +43,29 @@ enum TokenFormatter { return String(format: "$%.1fK", usd / 1_000) } + /// 레버리지 배수: 27.83 → "27.8×", 0.5 → "0.5×". 소수 1자리 고정 — 캡션 폭 안에서 안정. + static func multiple(_ value: Double) -> String { + String(format: "%.1f×", value) + } + + /// 설정의 "월 플랜 가격" 입력 파서. `$`, 천 단위 콤마, 공백은 무시하고 양의 유한수만 받는다. + /// 빈 문자열·문자·0·음수·nan → nil (= 기능 꺼짐). 지역 통화 서식은 의도적으로 안 탄다 — + /// `cost()` 가 `$%.2f` 로 고정돼 있으므로 입력도 같은 관례. + static func parsePlanPrice(_ raw: String) -> Double? { + let cleaned = raw.filter { !$0.isWhitespace && $0 != "$" && $0 != "," } + guard !cleaned.isEmpty, let value = Double(cleaned), value.isFinite, value > 0 else { return nil } + return value + } + static func percent(_ value: Double) -> String { value == value.rounded() ? String(format: "%.0f%%", value) : String(format: "%.1f%%", value) } + /// 설정 필드 재표시용: 100 → "100", 19.99 → "19.99" (소수 2자리까지, 끝 0 제거). + static func trimmedDecimal(_ value: Double) -> String { + trim(value, decimals: 2) + } + private static func trim(_ value: Double, decimals: Int) -> String { var s = String(format: "%.\(decimals)f", value) while s.hasSuffix("0") { s.removeLast() } diff --git a/Sources/PokeTokenBar/Core/UsageStore.swift b/Sources/PokeTokenBar/Core/UsageStore.swift index 15da0f96e..db69b1c8d 100644 --- a/Sources/PokeTokenBar/Core/UsageStore.swift +++ b/Sources/PokeTokenBar/Core/UsageStore.swift @@ -99,6 +99,10 @@ final class UsageStore { var floatingPetBubbleAlerts: Bool { didSet { defaults.set(floatingPetBubbleAlerts, forKey: "floatingPetBubbleAlerts") } } + /// 사용자가 적은 Claude 월 플랜 가격(USD). 0 = 미설정(기본, 레버리지 행 숨김). 이슈 #200 항목 2. + var claudePlanPriceUSD: Double { + didSet { defaults.set(claudePlanPriceUSD, forKey: "claudePlanPriceUSD") } + } var disableKeychainAccess: Bool { didSet { defaults.set(disableKeychainAccess, forKey: "disableKeychainAccess") // 저장 누락이던 기존 버그 — 재시작 후 풀렸음 @@ -253,6 +257,26 @@ final class UsageStore { /// Whether any connected provider reports real spend — gates menu/header `$0.00` for flat-rate-only setups. var showsCost: Bool { !costingSnapshots.isEmpty } + /// Max/Pro/Team — ModelPricing dollars are API-equivalent, not a bill. + /// The plan lives on official Claude limits; this does not branch generic + /// totals on `providerID` (provider-extension rule). + var labelsCostAsAPIEquivalent: Bool { limits?.labelsCostAsAPIEquivalent == true } + + /// Claude 의 이번 달(달력 월) API 환산 비용. 스냅샷이 없거나 월 집계가 아직 없으면 nil. + /// 플랜 가격은 *Claude* 플랜이므로 레버리지 분자도 Claude 만 — 다른 프로바이더 달러를 섞으면 + /// 배수가 틀린다. 공식 한도처럼 Claude 전용 기능이라 `providerID` 분기가 허용되는 경로이며, + /// 범용 today/week/month 합계는 건드리지 않는다. + var claudeMonthCostTotal: Double? { + costingSnapshots.first { $0.providerID == "claude_code" }?.monthTotal?.totalCost + } + + /// 팝오버 레버리지 행 재료. Max/Pro/Team 이고 가격이 설정돼 있고 Claude 월 비용이 있을 때만. + /// 라벨은 Keychain 에 *지금* 실린 계정의 플랜을 따른다 — 같은 루트에서 계정을 바꿔 쓴 이력은 + /// 구분하지 않는다(#201 범위). + var planLeverage: PlanLeverage? { + limits?.planLeverage(planPrice: claudePlanPriceUSD, monthAPIEquivalent: claudeMonthCostTotal) + } + var todayCostTotal: Double { let todayKey = LocalUsageReader.todayKey() return costingSnapshots.reduce(0) { $0 + ($1.today?.date == todayKey ? ($1.today?.totalCost ?? 0) : 0) } @@ -485,6 +509,7 @@ final class UsageStore { floatingPetEnabled = d.object(forKey: "floatingPetEnabled") as? Bool ?? false floatingPetSize = d.object(forKey: "floatingPetSize") as? Double ?? 96 floatingPetBubbleAlerts = d.object(forKey: "floatingPetBubbleAlerts") as? Bool ?? true + claudePlanPriceUSD = d.object(forKey: "claudePlanPriceUSD") as? Double ?? 0 disableKeychainAccess = d.object(forKey: "disableKeychainAccess") as? Bool ?? false reschedule() diff --git a/Sources/PokeTokenBar/UI/PopoverView.swift b/Sources/PokeTokenBar/UI/PopoverView.swift index 06671dd3c..a04dfcade 100644 --- a/Sources/PokeTokenBar/UI/PopoverView.swift +++ b/Sources/PokeTokenBar/UI/PopoverView.swift @@ -144,7 +144,7 @@ struct PopoverView: View { .monospacedDigit() Spacer() if store.showsCost { - Text(TokenFormatter.cost(todayCost)) + Text(costText(todayCost)) .font(.callout) .foregroundStyle(.secondary) } @@ -160,6 +160,19 @@ struct PopoverView: View { .padding(.top, 2) } + // Max/Pro/Team + 설정에 월 플랜 가격이 있으면: 이번 달 API 환산 비용 ÷ 낸 돈 (#200 항목 2). + // 판정·계산은 스토어(PlanLeverage), 문구는 L — 뷰는 포맷만. + if let leverage = store.planLeverage { + Text(l.planLeverageRow(plan: TokenFormatter.cost(leverage.planPrice), + apiEquiv: TokenFormatter.cost(leverage.apiEquivalent), + multiple: TokenFormatter.multiple(leverage.multiple))) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.85) + } + // 연결된 서비스가 2개 이상이면 작은 탭으로 서비스별 상세를 넘나든다 // (합계는 위에 유지 — 상세·한도만 탭 스코프). if store.snapshots.count > 1 { @@ -193,7 +206,7 @@ struct PopoverView: View { .font(.caption.weight(.semibold)) .monospacedDigit() if let cost { - Text(TokenFormatter.cost(cost)) + Text(costText(cost)) .font(.caption) .foregroundStyle(.secondary) } @@ -204,6 +217,12 @@ struct PopoverView: View { store.costingSnapshots.reduce(0) { $0 + ($1.today?.totalCost ?? 0) } } + /// Max/Pro/Team 이면 `$12.34 (API-equiv.)`. API 키·Free 는 숫자만. + /// 접미사는 L 에서 오고, 판정은 스토어(공식 한도의 플랜)에 둔다. + private func costText(_ usd: Double) -> String { + TokenFormatter.cost(usd, labeled: store.labelsCostAsAPIEquivalent ? l.apiEquivalentCaption : nil) + } + private func providerRow(snapshot: ProviderSnapshot, today: DailyUsage) -> some View { VStack(alignment: .leading, spacing: 3) { HStack { @@ -214,7 +233,7 @@ struct PopoverView: View { .font(.callout) .monospacedDigit() if snapshot.reportsCost { - Text(TokenFormatter.cost(today.totalCost)) + Text(costText(today.totalCost)) .font(.caption) .foregroundStyle(.secondary) } diff --git a/Sources/PokeTokenBar/UI/SettingsView.swift b/Sources/PokeTokenBar/UI/SettingsView.swift index c30faef59..09ec1cae1 100644 --- a/Sources/PokeTokenBar/UI/SettingsView.swift +++ b/Sources/PokeTokenBar/UI/SettingsView.swift @@ -26,6 +26,9 @@ struct SettingsView: View { @State private var customScanMatchTask: Task? @State private var customScanMatchGeneration = 0 @FocusState private var customScanFocused: Bool + /// 월 플랜 가격 초안 — 스캔 폴더와 같은 draft/commit 패턴(키 입력마다 defaults 에 쓰지 않는다). + @State private var planPriceDraft = "" + @FocusState private var planPriceFocused: Bool private var l: L { companion.l } private var isBundledApp: Bool { AppEnv.isBundledApp } @@ -406,6 +409,25 @@ struct SettingsView: View { .padding(.horizontal, 12).padding(.bottom, 6) } Divider() + groupRow { + VStack(alignment: .leading, spacing: 1) { + Text(l.planPriceLabel) + Text(l.planPriceHint).font(.caption2).foregroundStyle(.tertiary) + } + Spacer() + TextField(l.planPricePlaceholder, text: $planPriceDraft) + .textFieldStyle(.roundedBorder).font(.caption) + .multilineTextAlignment(.trailing) + .frame(width: 88) + .focused($planPriceFocused) + .onSubmit { commitPlanPriceDraft() } + } + .onAppear { seedPlanPriceDraft() } + .onDisappear { commitPlanPriceDraft() } + .onChange(of: planPriceFocused) { _, focused in + if !focused { commitPlanPriceDraft() } + } + Divider() groupRow { VStack(alignment: .leading, spacing: 6) { Text(l.customScanRootsLabel) @@ -535,6 +557,18 @@ struct SettingsView: View { store.setCustomScanRoots(customScanDraft, for: customScanDraftOwnerID) } + /// 파싱 실패(문자·0·음수)는 0 = 꺼짐으로 저장하고 초안을 다시 채워, 잘못된 입력이 조용히 남지 않게 한다. + private func commitPlanPriceDraft() { + let parsed = TokenFormatter.parsePlanPrice(planPriceDraft) ?? 0 + if store.claudePlanPriceUSD != parsed { store.claudePlanPriceUSD = parsed } + seedPlanPriceDraft() + } + + private func seedPlanPriceDraft() { + let price = store.claudePlanPriceUSD + planPriceDraft = price > 0 ? TokenFormatter.trimmedDecimal(price) : "" + } + private func scheduleCustomScanMatchCount() { customScanMatchTask?.cancel() customScanMatchGeneration += 1 diff --git a/Tests/PokeTokenBarTests/LocalUsageCacheTests.swift b/Tests/PokeTokenBarTests/LocalUsageCacheTests.swift index 4352eba41..8c65dc7fc 100644 --- a/Tests/PokeTokenBarTests/LocalUsageCacheTests.swift +++ b/Tests/PokeTokenBarTests/LocalUsageCacheTests.swift @@ -774,6 +774,7 @@ final class LocalUsageCacheTests: XCTestCase { // 구분기호가 지역 설정을 따르는지 — locale 인자가 무시되면 여기서 걸린다. XCTAssertEqual(TokenFormatter.grouped(253_412_890, locale: Locale(identifier: "es_ES")), "253.412.890") XCTAssertEqual(TokenFormatter.cost(48.104), "$48.10") + XCTAssertEqual(TokenFormatter.cost(48.104, labeled: "(API-equiv.)"), "$48.10 (API-equiv.)") XCTAssertEqual(TokenFormatter.costCompact(9.54), "$9.5") // < 100 → 소수 1자리 XCTAssertEqual(TokenFormatter.costCompact(311.4), "$311") // < 10K → 정수 XCTAssertEqual(TokenFormatter.costCompact(12_340), "$12.3K") // ≥ 10K → K diff --git a/Tests/PokeTokenBarTests/LocalizationInterpolationTests.swift b/Tests/PokeTokenBarTests/LocalizationInterpolationTests.swift index 9bebd55c5..45445e5d6 100644 --- a/Tests/PokeTokenBarTests/LocalizationInterpolationTests.swift +++ b/Tests/PokeTokenBarTests/LocalizationInterpolationTests.swift @@ -48,6 +48,7 @@ final class LocalizationInterpolationTests: XCTestCase { expect(lang, "claudeLimitEntry", l.claudeLimitEntry(kind: "weekly_scoped", model: a), a) expect(lang, "limitsAccount", l.limitsAccount(a), a) + expect(lang, "planLeverageRow", l.planLeverageRow(plan: a, apiEquiv: b, multiple: a), a, b) expect(lang, "codexWindow(h)", l.codexWindow(420), "7") // 420 min → 7 h / 420분 → 7시간 expect(lang, "codexWindow(m)", l.codexWindow(37), "37") expect(lang, "percentRemaining", l.percentRemaining(a), a) diff --git a/Tests/PokeTokenBarTests/PlanLeverageTests.swift b/Tests/PokeTokenBarTests/PlanLeverageTests.swift new file mode 100644 index 000000000..273003824 --- /dev/null +++ b/Tests/PokeTokenBarTests/PlanLeverageTests.swift @@ -0,0 +1,109 @@ +import XCTest +@testable import PokeTokenBar + +/// 이슈 #200 항목 2 — 월 플랜 가격 대비 API 환산 배수. 파서·배수 포맷·게이팅·문구·소스 잠금. +final class PlanLeverageTests: XCTestCase { + private var repoRoot: URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + } + + // MARK: 파서 + + /// `$`, 콤마, 공백은 관대하게 받고 양의 유한수만 통과. 실패는 nil (= 꺼짐) — 0 이나 기본값으로 뭉개지 않는다. + func testParsePlanPriceAcceptsCommonCurrencyInput() { + XCTAssertEqual(TokenFormatter.parsePlanPrice("100"), 100) + XCTAssertEqual(TokenFormatter.parsePlanPrice("$100"), 100) + XCTAssertEqual(TokenFormatter.parsePlanPrice(" 1,200.50 "), 1200.5) + XCTAssertEqual(TokenFormatter.parsePlanPrice("19.99"), 19.99) + XCTAssertEqual(TokenFormatter.parsePlanPrice("$ 20"), 20) + } + + func testParsePlanPriceRejectsEmptyZeroNegativeAndGarbage() { + for raw in ["", " ", "abc", "0", "0.00", "-5", "$-100", "nan", "inf", "1e400", "100abc"] { + XCTAssertNil(TokenFormatter.parsePlanPrice(raw), "\(raw.debugDescription) must not become a price") + } + } + + // MARK: 포맷 + + func testMultipleAndTrimmedDecimalFormatting() { + XCTAssertEqual(TokenFormatter.multiple(27.83), "27.8×") + XCTAssertEqual(TokenFormatter.multiple(3.06), "3.1×") + XCTAssertEqual(TokenFormatter.multiple(0.5), "0.5×") + XCTAssertEqual(TokenFormatter.trimmedDecimal(100), "100") + XCTAssertEqual(TokenFormatter.trimmedDecimal(19.99), "19.99") + XCTAssertEqual(TokenFormatter.trimmedDecimal(20.5), "20.5") + } + + // MARK: 계산·게이팅 + + func testPlanLeverageMultiple() { + let lev = PlanLeverage(planPrice: 100, apiEquivalent: 2783.33) + XCTAssertEqual(lev.multiple, 27.8333, accuracy: 0.001) + } + + /// 정액 플랜 + 양수 가격 + 월 비용이 모두 있어야 값이 나온다. A(꺼짐)와 B(켜짐) 둘 다 잠근다. + func testLimitStatusPlanLeverageGating() throws { + var status = try JSONDecoder().decode(LimitStatus.self, from: Data("{}".utf8)) + + status.subscriptionType = "max" + let on = status.planLeverage(planPrice: 100, monthAPIEquivalent: 2783.33) + XCTAssertEqual(on, PlanLeverage(planPrice: 100, apiEquivalent: 2783.33), "Max + price + month cost → row") + + XCTAssertNil(status.planLeverage(planPrice: 0, monthAPIEquivalent: 2783.33), "price 0 = feature off") + XCTAssertNil(status.planLeverage(planPrice: -1, monthAPIEquivalent: 2783.33), "negative price never shows") + XCTAssertNil(status.planLeverage(planPrice: .infinity, monthAPIEquivalent: 2783.33), "non-finite price never shows") + XCTAssertNil(status.planLeverage(planPrice: 100, monthAPIEquivalent: nil), "no month figure yet → nothing") + + for plan in ["free", "api", "", nil] as [String?] { + status.subscriptionType = plan + XCTAssertNil(status.planLeverage(planPrice: 100, monthAPIEquivalent: 2783.33), + "\(plan ?? "nil") is billed like API — leverage is meaningless") + } + } + + // MARK: 문구 + + /// 모든 언어에서 두 달러 값과 배수가 그대로 살아남고, 배수 기호 `×` 가 보인다. + func testPlanLeverageRowKeepsFiguresInEveryLanguage() { + for lang in AppLanguage.allCases { + let s = L(lang).planLeverageRow(plan: "$100.00", apiEquiv: "$2783.33", multiple: "27.8×") + XCTAssertTrue(s.contains("$100.00"), "\(lang.rawValue): \(s)") + XCTAssertTrue(s.contains("$2783.33"), "\(lang.rawValue): \(s)") + XCTAssertTrue(s.contains("27.8×"), "\(lang.rawValue): \(s)") + XCTAssertTrue(s.contains("API"), "\(lang.rawValue): \(s) must say the figure is API-equivalent") + } + } + + // MARK: 소스 잠금 + + /// 팝오버는 스토어의 PlanLeverage 와 L 문구를 쓰고, 메뉴바 costCompact 경로는 여전히 레버리지를 모른다 + /// (#224 의 메뉴바-무라벨 결정 유지). + func testPopoverRendersLeverageAndMenuBarDoesNot() throws { + let popover = try String(contentsOf: repoRoot.appendingPathComponent("Sources/PokeTokenBar/UI/PopoverView.swift"), encoding: .utf8) + XCTAssertTrue(popover.contains("store.planLeverage"), "popover must consult the store, not recompute the ratio") + XCTAssertTrue(popover.contains("planLeverageRow"), "copy must come from L") + XCTAssertFalse(popover.contains("claudePlanPriceUSD"), "the view must not read the raw setting and divide itself") + + let store = try String(contentsOf: repoRoot.appendingPathComponent("Sources/PokeTokenBar/Core/UsageStore.swift"), encoding: .utf8) + let compactIdx = try XCTUnwrap(store.range(of: "TokenFormatter.costCompact"), "menu bar still uses costCompact") + let window = store[compactIdx.lowerBound...].prefix(180) + XCTAssertFalse(window.contains("planLeverage"), "menu-bar cost must stay a bare figure") + XCTAssertFalse(window.contains("labeled:"), "menu-bar cost must stay unlabeled (#224)") + } + + /// 설정 필드는 초안 + 제출/블러/사라짐 커밋 — 키 입력마다 defaults 에 쓰지 않는다 (#187 패턴). + func testSettingsPlanPriceFieldCommitsOnSubmitBlurAndDisappear() throws { + let text = try String(contentsOf: repoRoot.appendingPathComponent("Sources/PokeTokenBar/UI/SettingsView.swift"), encoding: .utf8) + XCTAssertTrue(text.contains("planPriceDraft"), "field must edit a draft") + XCTAssertFalse(text.contains("$store.claudePlanPriceUSD"), "direct binding writes defaults on every keystroke") + XCTAssertTrue(text.contains("commitPlanPriceDraft"), "draft must be committed through one helper") + XCTAssertTrue(text.contains("TokenFormatter.parsePlanPrice"), "commit must go through the shared parser") + XCTAssertTrue(text.contains("planPriceFocused"), "blur must commit") + XCTAssertTrue(text.contains("l.planPriceLabel") && text.contains("l.planPriceHint") && text.contains("l.planPricePlaceholder"), + "all copy must come from L") + } +} diff --git a/Tests/PokeTokenBarTests/PokeTokenBarTests.swift b/Tests/PokeTokenBarTests/PokeTokenBarTests.swift index adfc089f9..4c08b4731 100644 --- a/Tests/PokeTokenBarTests/PokeTokenBarTests.swift +++ b/Tests/PokeTokenBarTests/PokeTokenBarTests.swift @@ -289,6 +289,68 @@ final class ModelDecodingTests: XCTestCase { XCTAssertNil(status.planDisplay) } + /// Max/Pro/Team 은 정액 구독이라 ModelPricing 달러가 청구액이 아니다 → API 환산 라벨. + /// Free·API 키(값 없음)는 그 숫자가 비용에 가깝다. 외부 JSON 이라 대소문자를 접는다. + /// A=false(free/nil) 만 검증하면 구독 분기가 죽은 채 통과하므로 B=true(max/pro/team) 도 잠근다. + func testLabelsCostAsAPIEquivalent() throws { + var status = try JSONDecoder().decode(LimitStatus.self, from: Data("{}".utf8)) + + for plan in ["max", "pro", "team", "MAX", "Pro"] { + status.subscriptionType = plan + XCTAssertTrue(status.labelsCostAsAPIEquivalent, "\(plan) is a flat-rate subscription") + } + + for plan in ["free", "api", "", nil] as [String?] { + status.subscriptionType = plan + XCTAssertFalse(status.labelsCostAsAPIEquivalent, + "\(plan ?? "nil") is billed like API (or unknown) — no qualifier") + } + } + + /// `$610.30 (API-equiv.)` — 숫자 포맷은 그대로, 접미사만 붙는다. 빈 접미사는 무라벨. + func testCostLabeledAsAPIEquivalent() { + XCTAssertEqual(TokenFormatter.cost(610.3), "$610.30") + XCTAssertEqual(TokenFormatter.cost(610.3, labeled: "(API-equiv.)"), "$610.30 (API-equiv.)") + XCTAssertEqual(TokenFormatter.cost(610.3, labeled: nil), "$610.30") + XCTAssertEqual(TokenFormatter.cost(610.3, labeled: ""), "$610.30", + "empty suffix must not add a trailing space") + } + + /// 팝오버 비용 행만 라벨을 타고, 메뉴바 costCompact 경로는 접미사를 모른다. + /// (이슈 #200 의 두 번째 설계 질문 — 메뉴바는 후속.) + func testPopoverCostRowsUseAPIEquivalentLabelAndMenuBarDoesNot() throws { + let root = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + let popover = try String(contentsOf: root.appendingPathComponent("Sources/PokeTokenBar/UI/PopoverView.swift"), encoding: .utf8) + XCTAssertTrue(popover.contains("labelsCostAsAPIEquivalent"), + "popover cost rows must consult the subscription predicate") + XCTAssertTrue(popover.contains("apiEquivalentCaption"), + "qualifier copy must come from L, not a hardcoded English suffix") + XCTAssertFalse(popover.contains("TokenFormatter.costCompact"), + "compact menu-bar cost must not leak into the popover") + + let store = try String(contentsOf: root.appendingPathComponent("Sources/PokeTokenBar/Core/UsageStore.swift"), encoding: .utf8) + let compactIdx = try XCTUnwrap(store.range(of: "TokenFormatter.costCompact"), + "menu bar still uses costCompact") + let window = store[compactIdx.lowerBound...].prefix(180) + XCTAssertFalse(window.contains("labeled:"), + "menu-bar costCompact must stay unlabeled (#200 follow-up)") + XCTAssertFalse(window.contains("apiEquivalentCaption"), + "menu bar must not grow the qualifier") + } + + /// 접미사는 모든 언어에 "API" 가 남고 괄호로 한정어임을 표시한다. + /// `allCases` 라야 언어가 늘어도 커버가 조용히 멈추지 않는다. + func testAPIEquivalentCaptionMentionsAPIInEveryLanguage() { + for lang in AppLanguage.allCases { + let s = L(lang).apiEquivalentCaption + XCTAssertTrue(s.contains("API"), "\(lang.rawValue): \(s)") + XCTAssertTrue(s.hasPrefix("(") && s.hasSuffix(")"), "\(lang.rawValue): \(s) should be parenthetical") + } + } + /// 자격증명 파싱이 subscriptionType/rateLimitTier 를 추출하는지 — 실 keychain JSON 형태 기반. func testCredentialParsesPlanFields() throws { let json = Data(""" diff --git a/Tests/PokeTokenBarTests/UsageStoreTests.swift b/Tests/PokeTokenBarTests/UsageStoreTests.swift index 90361423b..6aa34ba27 100644 --- a/Tests/PokeTokenBarTests/UsageStoreTests.swift +++ b/Tests/PokeTokenBarTests/UsageStoreTests.swift @@ -990,6 +990,98 @@ final class UsageStoreTests: XCTestCase { XCTAssertEqual(store.snapshots.count, 2, "Both providers should have snapshots") } + /// 팝오버 API 환산 라벨은 스토어가 들고 있는 Claude 플랜을 따른다. + /// 한도가 아직 없거나 Free 면 꺼지고, Max/Pro/Team 이면 켜진다 — 뷰가 구독 문자열을 직접 파싱하지 않게. + func testAPIEquivalentCostLabelFollowsClaudeSubscription() async { + let claude = FakeUsageProvider(id: "claude_code", displayName: "Claude Code", daily: todayDaily(1_000)) + + var maxPlan = claudeLimits(fiveHourUtil: 10) + maxPlan.subscriptionType = "max" + let maxStore = makeStore(providers: [claude], claude: maxPlan) + await maxStore.refresh(scheduleEmptyRetry: false) + XCTAssertTrue(maxStore.labelsCostAsAPIEquivalent, "Max → qualifier on") + + var teamPlan = claudeLimits(fiveHourUtil: 10) + teamPlan.subscriptionType = "team" + let teamStore = makeStore(providers: [claude], claude: teamPlan) + await teamStore.refresh(scheduleEmptyRetry: false) + XCTAssertTrue(teamStore.labelsCostAsAPIEquivalent, "Team → qualifier on") + + var freePlan = claudeLimits(fiveHourUtil: 10) + freePlan.subscriptionType = "free" + let freeStore = makeStore(providers: [claude], claude: freePlan) + await freeStore.refresh(scheduleEmptyRetry: false) + XCTAssertFalse(freeStore.labelsCostAsAPIEquivalent, "Free → no qualifier") + + let unknown = makeStore(providers: [claude], claude: nil) + await unknown.refresh(scheduleEmptyRetry: false) + XCTAssertFalse(unknown.labelsCostAsAPIEquivalent, "no limits loaded → no qualifier") + } + + /// 월 플랜 가격은 defaults 에 남고(같은 suite 의 새 스토어가 읽음), 0 은 미설정으로 돌아온다. + func testClaudePlanPricePersistsAcrossStores() { + let claude = FakeUsageProvider(id: "claude_code", displayName: "Claude Code", daily: todayDaily(1_000)) + let first = makeStore(providers: [claude]) + XCTAssertEqual(first.claudePlanPriceUSD, 0, "default is off") + first.claudePlanPriceUSD = 100 + XCTAssertEqual(testDefaults.double(forKey: "claudePlanPriceUSD"), 100) + + let second = makeStore(providers: [claude]) + XCTAssertEqual(second.claudePlanPriceUSD, 100, "a fresh store must read the saved price") + second.claudePlanPriceUSD = 0 + XCTAssertEqual(makeStore(providers: [claude]).claudePlanPriceUSD, 0) + } + + /// 레버리지 분자는 *Claude* 의 달력-월 비용만이다 — 같은 달 Codex 달러가 얼마든 배수는 그대로. + /// 게이팅: 가격 0 / Free / 한도 없음 / Claude 월 집계 없음 → nil. + func testPlanLeverageUsesClaudeMonthCostOnlyAndGatesOnPlanAndPrice() async { + let claude = FakeUsageProvider(id: "claude_code", displayName: "Claude Code", daily: todayDaily(1_000, cost: 2.84)) + claude.enrichment = ProviderEnrichment( + weekTotal: PeriodUsage(period: "w", totalTokens: 400_000_000, totalCost: 600), + monthTotal: PeriodUsage(period: "m", totalTokens: 1_783_000_000, totalCost: 2783.33), + periodsOK: true) + let codex = FakeUsageProvider(id: "codex", displayName: "Codex", daily: todayDaily(500, cost: 1)) + codex.enrichment = ProviderEnrichment( + monthTotal: PeriodUsage(period: "m", totalTokens: 900_000_000, totalCost: 9_999), + periodsOK: true) + + var maxPlan = claudeLimits(fiveHourUtil: 10) + maxPlan.subscriptionType = "max" + + let store = makeStore(providers: [claude, codex], claude: maxPlan) + store.claudePlanPriceUSD = 100 + await store.refresh(scheduleEmptyRetry: false) + + XCTAssertEqual(store.monthCostTotal, 2783.33 + 9_999, accuracy: 0.001, "generic month total still sums every costing provider") + XCTAssertEqual(store.claudeMonthCostTotal ?? -1, 2783.33, accuracy: 0.001) + let lev = store.planLeverage + XCTAssertEqual(lev?.planPrice, 100) + XCTAssertEqual(lev?.apiEquivalent ?? -1, 2783.33, accuracy: 0.001, "Codex dollars must not inflate a Claude plan's leverage") + XCTAssertEqual(lev?.multiple ?? -1, 27.8333, accuracy: 0.001) + + store.claudePlanPriceUSD = 0 + XCTAssertNil(store.planLeverage, "clearing the price hides the row without a refresh") + store.claudePlanPriceUSD = 100 + + var freePlan = claudeLimits(fiveHourUtil: 10) + freePlan.subscriptionType = "free" + let freeStore = makeStore(providers: [claude], claude: freePlan) + freeStore.claudePlanPriceUSD = 100 + await freeStore.refresh(scheduleEmptyRetry: false) + XCTAssertNil(freeStore.planLeverage, "Free is billed like API — no leverage") + + let noLimits = makeStore(providers: [claude], claude: nil) + noLimits.claudePlanPriceUSD = 100 + await noLimits.refresh(scheduleEmptyRetry: false) + XCTAssertNil(noLimits.planLeverage, "no plan known → nothing") + + let noMonth = FakeUsageProvider(id: "claude_code", displayName: "Claude Code", daily: todayDaily(1_000, cost: 2.84)) + let noMonthStore = makeStore(providers: [noMonth], claude: maxPlan) + noMonthStore.claudePlanPriceUSD = 100 + await noMonthStore.refresh(scheduleEmptyRetry: false) + XCTAssertNil(noMonthStore.planLeverage, "month enrichment not loaded yet → nothing rather than 0×") + } + func testCursorContributesZeroToTodayCostTotal() async { let claude = FakeUsageProvider( id: "claude_code", displayName: "Claude Code",