Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ PokeTokenBar は、あなたがすでに使っている AI コーディングト
<td width="45%" align="center"><img src="assets/settings-ja.png" width="300" alt="設定"></td>
<td width="55%" valign="middle">
<h3>設定はお好みで</h3>
メニューバー表示項目、更新間隔(1–15分/手動)、ログイン時に起動、上限セクションだけを隠す Keychain オフ、警告/危険の閾値つき上限通知、パートナーのイベント通知。<b>韓国語/英語/日本語</b>の UI とポケモン名を完備。
メニューバー表示項目、更新間隔(1–15分/手動)、ログイン時に起動、上限セクションだけを隠す Keychain オフ、警告/危険の閾値つき上限通知、パートナーのイベント通知、そして Max/Pro/Team のコストを倍率で示す任意の月額プラン料金。<b>韓国語/英語/日本語</b>の UI とポケモン名を完備。
</td>
</tr>
<tr>
Expand All @@ -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行追加されます。料金を空にすると非表示。
- **アプリ内アップデート** — ワンクリックの更新確認、設定に現在のバージョンを表示。

## 対応ツール
Expand Down
3 changes: 2 additions & 1 deletion README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ PokeTokenBar는 당신이 이미 태우고 있는 AI 코딩 토큰(Claude Code
<td width="45%" align="center"><img src="assets/settings-ko.png" width="300" alt="설정"></td>
<td width="55%" valign="middle">
<h3>설정에서 취향대로</h3>
메뉴바 표시 항목, 새로고침 간격(1–15분/수동), 로그인 시 자동 시작, 한도 섹션만 숨기는 Keychain 끄기, 경고/임박 임계값 한도 알림, companion 이벤트 알림. <b>한국어/영어/일본어</b> UI·포켓몬 이름 완비.
메뉴바 표시 항목, 새로고침 간격(1–15분/수동), 로그인 시 자동 시작, 한도 섹션만 숨기는 Keychain 끄기, 경고/임박 임계값 한도 알림, companion 이벤트 알림, 그리고 Max/Pro/Team 비용을 배수로 보여 주는 선택적 월 플랜 가격. <b>한국어/영어/일본어</b> UI·포켓몬 이름 완비.
</td>
</tr>
<tr>
Expand All @@ -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×` 한 줄이 추가됩니다. 가격을 비우면 숨겨집니다.
- **인앱 업데이트** — 원클릭 업데이트 확인, 설정에 현재 버전 표시.

## 지원 도구
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ The <b>Pokédex</b> folds every species you've owned into one cell — 24 per pa
<td width="45%" align="center"><img src="assets/settings.png" width="300" alt="Settings"></td>
<td width="55%" valign="middle">
<h3>Tune it your way</h3>
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 <b>KO / EN / JA</b> 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 <b>KO / EN / JA</b> UI and Pokémon names.
</td>
</tr>
<tr>
Expand All @@ -101,6 +101,7 @@ The tokens you've already used are your currency. Spend them in the new <b>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
Expand Down
21 changes: 21 additions & 0 deletions Sources/PokeTokenBar/Core/Localization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)") }
Expand Down Expand Up @@ -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") }
Expand Down Expand Up @@ -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 {
Expand Down
29 changes: 29 additions & 0 deletions Sources/PokeTokenBar/Core/Models.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 · 조직명". 개인 플랜의 자동 생성 조직명("<email>'s Organization")은
/// 이메일과 중복 정보라 생략한다(조직명에 이메일이 포함되는지로 판정). 이메일 없으면 nil —
/// 조직명만으로는 어느 로그인인지 특정되지 않아 부분 라벨을 만들지 않는다.
Expand Down Expand Up @@ -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
Expand Down
25 changes: 23 additions & 2 deletions Sources/PokeTokenBar/Core/TokenFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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() }
Expand Down
25 changes: 25 additions & 0 deletions Sources/PokeTokenBar/Core/UsageStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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") // 저장 누락이던 기존 버그 — 재시작 후 풀렸음
Expand Down Expand Up @@ -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) }
Expand Down Expand Up @@ -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()
Expand Down
Loading