mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-31 11:01:36 +08:00
feat(tray): show cached provider usage in the system tray menu (#2184)
* feat: add Rust-side write-through usage cache Introduce an in-memory UsageCache on AppState that the existing usage query commands populate on success. The cache is read-only to the rest of the app today; the next commit consumes it from the tray menu. - New services::usage_cache module with split maps: subscription keyed by AppType, script keyed by (AppType, provider_id). - AppType gains Eq + Hash so it can be used as a HashMap key. - commands::subscription::get_subscription_quota now takes State<AppState> and writes through on success (signature change is invisible to the frontend — Tauri injects State automatically). - commands::provider::queryProviderUsage body extracted into an inner async fn; the public command wraps it with write-through, covering Copilot, coding-plan, balance, and generic script paths uniformly. Cache is in-memory only; auto-query interval and the upcoming tray refresh action rebuild it after restarts. * feat(tray): surface cached usage in the system tray menu Read UsageCache populated by the previous commit and render it in three places, scoped to whatever TRAY_SECTIONS covers (Claude/Codex/Gemini): 1. Inline suffix on each provider submenu item "AnyProvider · 🟢 5h 18% / 7d 23%" 2. Disabled summary row per visible app under "Show Main" "Claude · Anthropic Official · 🟢 5h 18% / 7d 23%" 3. "Refresh all usage" menu item that triggers get_subscription_quota + queryProviderUsage for every applicable provider, then rebuilds the tray menu via the existing refresh_tray_menu path. Color encoding uses emoji (🟢 <70% / 🟠 70-89% / 🔴 ≥90%) since Tauri 2 tray labels are plain text. Missing cache entry leaves the label unchanged — tray never issues network requests when opened. Three new i18n-ready strings live in TrayTexts (en/zh/ja), following the existing pattern for tray text. Closes #2178. * feat(usage): bridge tray UsageCache writes to frontend React Query Why: tray hover triggers backend-only refresh that wrote to UsageCache but never notified the frontend, leaving main UI stale while tray showed fresh numbers. Emit a payload-carrying event after each cache write so React Query can setQueryData directly, keeping both views in sync without duplicate fetches. * fix(tray): skip hidden apps on hover refresh and drop stale disabled-script cache Address P2 findings from automated review on #2184: 1. refresh_all_usage_in_tray now filters TRAY_SECTIONS by settings.visible_apps before scheduling subscription/script queries, matching create_tray_menu and preventing wasted external API calls (and rate-limit/auth-error log noise) for apps the user has hidden. 2. format_usage_suffix only trusts the script cache when provider.meta.usage_script is still enabled; when a script is disabled/removed the cached suffix is now invalidated so the tray label no longer shows stale data indefinitely. * refactor: consolidate codex provider helpers and fix test semantics - Add Provider::is_codex_oauth() and Provider::codex_fast_mode_enabled() to eliminate duplicated meta extraction in claude.rs and stream_check.rs - Fix non-codex-oauth tests to pass codex_fast_mode=false (was true, harmless but semantically misleading) - Remove redundant is_dir() guard after resolve_skill_source_dir already guarantees the returned path is a directory * style: apply cargo fmt * fix(tray): reflect failed refreshes in cache and support Gemini flash-lite Follow-up to the tray usage-display feature addressing review feedback: - Write snapshots for both Ok(success:false) and Err paths in queryProviderUsage / get_subscription_quota so stale success data no longer persists across failed refreshes; the original Err is still returned to the frontend onError handler. - Include gemini_flash_lite tier in the tray summary with label "l". Matches the frontend SubscriptionQuotaFooter and keeps the worst emoji correct when lite is the highest utilization. - Add TIER_GEMINI_PRO / _FLASH / _FLASH_LITE constants in services/subscription.rs and reuse them in classify_gemini_model and sort_order. - Extract Provider::has_usage_script_enabled() to remove the duplicated meta.usage_script chain at two call sites. - Use db.get_provider_by_id in refresh_all_usage_in_tray instead of materialising the full provider map, and parallelise subscription and script futures via futures::future::join. - Narrow refresh_all_usage_in_tray to each section's effective current provider (script if enabled, else subscription when the provider is official). Hover refreshes now issue at most TRAY_SECTIONS.len() outbound requests. - Add 10 unit tests in tray::tests covering Claude/Codex h/w dispatch, Gemini p/f/l dispatch (including lite-only and lite-worst cases), and success/failure guards. --------- Co-authored-by: Jason <farion1231@gmail.com>
This commit is contained in:
@@ -16,6 +16,7 @@ pub mod skill;
|
||||
pub mod speedtest;
|
||||
pub mod stream_check;
|
||||
pub mod subscription;
|
||||
pub mod usage_cache;
|
||||
pub mod usage_stats;
|
||||
pub mod webdav;
|
||||
pub mod webdav_auto_sync;
|
||||
@@ -30,6 +31,7 @@ pub use proxy::ProxyService;
|
||||
#[allow(unused_imports)]
|
||||
pub use skill::{DiscoverableSkill, Skill, SkillRepo, SkillService};
|
||||
pub use speedtest::{EndpointLatency, SpeedtestService};
|
||||
pub use usage_cache::UsageCache;
|
||||
#[allow(unused_imports)]
|
||||
pub use usage_stats::{
|
||||
DailyStats, LogFilters, ModelStats, PaginatedLogs, ProviderLimitStatus, ProviderStats,
|
||||
|
||||
@@ -941,10 +941,6 @@ impl SkillService {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if !remote_skill_dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let remote_hash = match Self::compute_dir_hash(&remote_skill_dir) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
|
||||
@@ -355,16 +355,8 @@ impl StreamCheckService {
|
||||
});
|
||||
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要 store:false + include 标记,
|
||||
// 否则 Stream Check 会和生产路径一样被服务端 400 拒绝。
|
||||
let is_codex_oauth = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.provider_type.as_deref())
|
||||
== Some("codex_oauth");
|
||||
let codex_fast_mode = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.map(|m| m.codex_fast_mode_enabled())
|
||||
.unwrap_or(false);
|
||||
let is_codex_oauth = provider.is_codex_oauth();
|
||||
let codex_fast_mode = provider.codex_fast_mode_enabled();
|
||||
|
||||
let body = if is_openai_responses {
|
||||
anthropic_to_responses(
|
||||
|
||||
@@ -291,12 +291,22 @@ struct ApiExtraUsage {
|
||||
currency: Option<String>,
|
||||
}
|
||||
|
||||
/// 已知的 Claude 用量窗口名称
|
||||
/// 已知的 Claude 用量窗口名称。`QuotaTier::name` 会是其中之一。
|
||||
pub const TIER_FIVE_HOUR: &str = "five_hour";
|
||||
pub const TIER_SEVEN_DAY: &str = "seven_day";
|
||||
pub const TIER_SEVEN_DAY_OPUS: &str = "seven_day_opus";
|
||||
pub const TIER_SEVEN_DAY_SONNET: &str = "seven_day_sonnet";
|
||||
|
||||
/// Gemini 用量分组名称(按模型而非时间窗口)。`classify_gemini_model` 输出。
|
||||
pub const TIER_GEMINI_PRO: &str = "gemini_pro";
|
||||
pub const TIER_GEMINI_FLASH: &str = "gemini_flash";
|
||||
pub const TIER_GEMINI_FLASH_LITE: &str = "gemini_flash_lite";
|
||||
|
||||
const KNOWN_TIERS: &[&str] = &[
|
||||
"five_hour",
|
||||
"seven_day",
|
||||
"seven_day_opus",
|
||||
"seven_day_sonnet",
|
||||
TIER_FIVE_HOUR,
|
||||
TIER_SEVEN_DAY,
|
||||
TIER_SEVEN_DAY_OPUS,
|
||||
TIER_SEVEN_DAY_SONNET,
|
||||
];
|
||||
|
||||
/// 查询 Claude 官方订阅额度
|
||||
@@ -993,11 +1003,11 @@ fn extract_project_id(value: &serde_json::Value) -> Option<String> {
|
||||
/// 将 Gemini 模型 ID 分类为 Pro / Flash / Flash Lite
|
||||
fn classify_gemini_model(model_id: &str) -> &str {
|
||||
if model_id.contains("flash-lite") {
|
||||
"gemini_flash_lite"
|
||||
TIER_GEMINI_FLASH_LITE
|
||||
} else if model_id.contains("flash") {
|
||||
"gemini_flash"
|
||||
TIER_GEMINI_FLASH
|
||||
} else if model_id.contains("pro") {
|
||||
"gemini_pro"
|
||||
TIER_GEMINI_PRO
|
||||
} else {
|
||||
model_id
|
||||
}
|
||||
@@ -1152,9 +1162,9 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
// 转换为 tiers(remainingFraction → utilization: 已用百分比)
|
||||
let sort_order = |name: &str| -> usize {
|
||||
match name {
|
||||
"gemini_pro" => 0,
|
||||
"gemini_flash" => 1,
|
||||
"gemini_flash_lite" => 2,
|
||||
TIER_GEMINI_PRO => 0,
|
||||
TIER_GEMINI_FLASH => 1,
|
||||
TIER_GEMINI_FLASH_LITE => 2,
|
||||
_ => 3,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! 托盘展示用的用量缓存(进程内、写穿式)。
|
||||
//!
|
||||
//! 各 usage 查询命令成功时写入;系统托盘构建菜单时读取。不持久化,
|
||||
//! 进程重启即空,由下一次自动查询或托盘悬停触发的刷新重新填充。
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::provider::UsageResult;
|
||||
use crate::services::subscription::SubscriptionQuota;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UsageCache {
|
||||
subscription: RwLock<HashMap<AppType, SubscriptionQuota>>,
|
||||
script: RwLock<HashMap<(AppType, String), UsageResult>>,
|
||||
}
|
||||
|
||||
impl UsageCache {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn put_subscription(&self, app_type: AppType, quota: SubscriptionQuota) {
|
||||
if let Ok(mut w) = self.subscription.write() {
|
||||
w.insert(app_type, quota);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn put_script(&self, app_type: AppType, provider_id: String, result: UsageResult) {
|
||||
if let Ok(mut w) = self.script.write() {
|
||||
w.insert((app_type, provider_id), result);
|
||||
}
|
||||
}
|
||||
|
||||
/// 以借用形式暴露订阅快照,避免托盘每次重建时深拷贝整个 `SubscriptionQuota`。
|
||||
pub fn with_subscription<R>(
|
||||
&self,
|
||||
app_type: &AppType,
|
||||
f: impl FnOnce(&SubscriptionQuota) -> R,
|
||||
) -> Option<R> {
|
||||
self.subscription
|
||||
.read()
|
||||
.ok()
|
||||
.and_then(|r| r.get(app_type).map(f))
|
||||
}
|
||||
|
||||
/// 以借用形式暴露脚本型用量结果,同上。
|
||||
pub fn with_script<R>(
|
||||
&self,
|
||||
app_type: &AppType,
|
||||
provider_id: &str,
|
||||
f: impl FnOnce(&UsageResult) -> R,
|
||||
) -> Option<R> {
|
||||
self.script
|
||||
.read()
|
||||
.ok()
|
||||
.and_then(|r| r.get(&(app_type.clone(), provider_id.to_string())).map(f))
|
||||
}
|
||||
|
||||
pub fn invalidate_script(&self, app_type: &AppType, provider_id: &str) {
|
||||
// 热路径会对每个禁用脚本的 provider 在托盘重建时调用一次:先走读锁
|
||||
// `contains_key` 快速放行"本来就不在缓存里"的常见情况,避免无谓的写锁升级。
|
||||
let key = (app_type.clone(), provider_id.to_string());
|
||||
if !self.script.read().is_ok_and(|r| r.contains_key(&key)) {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut w) = self.script.write() {
|
||||
w.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::services::subscription::CredentialStatus;
|
||||
|
||||
fn fake_quota() -> SubscriptionQuota {
|
||||
SubscriptionQuota {
|
||||
tool: "claude".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
success: true,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_result() -> UsageResult {
|
||||
UsageResult {
|
||||
success: true,
|
||||
data: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscription_round_trip() {
|
||||
let cache = UsageCache::new();
|
||||
assert!(cache
|
||||
.with_subscription(&AppType::Claude, |q| q.success)
|
||||
.is_none());
|
||||
cache.put_subscription(AppType::Claude, fake_quota());
|
||||
let got = cache
|
||||
.with_subscription(&AppType::Claude, |q| q.success)
|
||||
.unwrap();
|
||||
assert!(got);
|
||||
assert!(cache
|
||||
.with_subscription(&AppType::Codex, |q| q.success)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_round_trip_and_invalidate() {
|
||||
let cache = UsageCache::new();
|
||||
assert!(cache
|
||||
.with_script(&AppType::Codex, "pid", |r| r.success)
|
||||
.is_none());
|
||||
cache.put_script(AppType::Codex, "pid".to_string(), fake_result());
|
||||
assert!(cache
|
||||
.with_script(&AppType::Codex, "pid", |r| r.success)
|
||||
.is_some());
|
||||
cache.invalidate_script(&AppType::Codex, "pid");
|
||||
assert!(cache
|
||||
.with_script(&AppType::Codex, "pid", |r| r.success)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_keys_isolated_by_app_type() {
|
||||
let cache = UsageCache::new();
|
||||
cache.put_script(AppType::Claude, "same".to_string(), fake_result());
|
||||
assert!(cache
|
||||
.with_script(&AppType::Claude, "same", |r| r.success)
|
||||
.is_some());
|
||||
assert!(cache
|
||||
.with_script(&AppType::Codex, "same", |r| r.success)
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user