Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

fix(quota): keep DeepSeek balance and Kimi identity off the network in manual-only mode (#10022)

SaladDaya09b54184f92
diff --git a/src-tauri/src/commands/dsh.rs b/src-tauri/src/commands/dsh.rs
index 95adc3cc3..0e885d37b 100644
--- a/src-tauri/src/commands/dsh.rs
+++ b/src-tauri/src/commands/dsh.rs
@@ -2,9 +2,10 @@
/// The DeepSeek account (OAuth) login shared by DSH Web and Desktop, with profile and balance.
#[tauri::command]
-pub async fn dsh_account_status() -> Result<crate::services::dsh_account::DshAccountStatus, String>
-{
- crate::services::dsh_account::status().await
+pub async fn dsh_account_status(
+ remote: bool,
+) -> Result<crate::services::dsh_account::DshAccountStatus, String> {
+ crate::services::dsh_account::status(remote).await
}
/// Sign out of the DeepSeek account for both DSH Web and Desktop.
diff --git a/src-tauri/src/commands/kimi_oauth.rs b/src-tauri/src/commands/kimi_oauth.rs
index 225494111..214da591d 100644
--- a/src-tauri/src/commands/kimi_oauth.rs
+++ b/src-tauri/src/commands/kimi_oauth.rs
@@ -8,9 +8,10 @@ use tauri::State;
#[tauri::command]
pub async fn kimi_oauth_status(
+ identify: bool,
state: State<'_, KimiOAuthManager>,
) -> Result<KimiOAuthStatus, String> {
- state.status().await
+ state.status(identify).await
}
#[tauri::command(rename_all = "camelCase")]
diff --git a/src-tauri/src/services/dsh_account.rs b/src-tauri/src/services/dsh_account.rs
index bebece0d3..7125513be 100644
--- a/src-tauri/src/services/dsh_account.rs
+++ b/src-tauri/src/services/dsh_account.rs
@@ -71,6 +71,12 @@ pub struct DshAccountStatus {
pub top_up_url: Option<String>,
/// Profile or balance query failure; the login itself is kept.
pub error: Option<String>,
+ /// Profile and balance were asked for (`status(true)`); false means only the
+ /// local login record was read.
+ pub queried: bool,
+ /// SHA-256 of the stored token. `issuer` is only the platform origin, so this
+ /// is what tells two logins apart when carrying a ↻ balance across a local refresh.
+ pub grant_fingerprint: Option<String>,
}
enum PlatformError {
@@ -187,8 +193,16 @@ fn validated_origin(issuer: &str) -> Result<&'static str, String> {
}
}
-/// The shared login plus, when signed in, the account profile and balance.
-pub async fn status() -> Result<DshAccountStatus, String> {
+fn grant_fingerprint(token: &str) -> String {
+ Sha256::digest(token.as_bytes())
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect()
+}
+
+/// The shared login plus, when signed in and `remote` is true, the account profile
+/// and balance. With `remote` false nothing is sent to Platform (manual-only quota).
+pub async fn status(remote: bool) -> Result<DshAccountStatus, String> {
let Some((token, issuer)) = crate::dsh_config::account_grant().map_err(|e| e.to_string())?
else {
return Ok(DshAccountStatus::default());
@@ -199,8 +213,13 @@ pub async fn status() -> Result<DshAccountStatus, String> {
usage_url: Some(format!("{origin}/usage")),
top_up_url: Some(format!("{origin}/top_up")),
issuer: Some(issuer),
+ queried: remote,
+ grant_fingerprint: Some(grant_fingerprint(&token)),
..Default::default()
};
+ if !remote {
+ return Ok(status);
+ }
let client = crate::proxy::http_client::no_redirect()?;
let (profile, balance) = tokio::join!(
platform_request(
@@ -717,7 +736,7 @@ mod tests {
let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let issuer = format!("http://{}", listener.local_addr().unwrap());
crate::dsh_config::store_account_grant("test-token", &issuer).unwrap();
- assert!(status().await.unwrap_err().contains("issuer"));
+ assert!(status(true).await.unwrap_err().contains("issuer"));
sign_out().await.unwrap();
assert!(crate::dsh_config::account_grant().unwrap().is_none());
assert!(
@@ -731,6 +750,39 @@ mod tests {
}
}
+ /// Manual-only quota: reading the login must not reach Platform. A fake token sent
+ /// there would come back expired (401) or as a request error.
+ #[tokio::test]
+ #[serial_test::serial]
+ async fn local_status_reads_the_login_without_contacting_platform() {
+ let home = tempfile::tempdir().unwrap();
+ let previous = std::env::var_os("DSH_HOME");
+ std::env::set_var("DSH_HOME", home.path());
+ crate::dsh_config::store_account_grant("test-token", PLATFORM_ORIGIN).unwrap();
+
+ let status = status(false).await.unwrap();
+
+ match previous {
+ Some(value) => std::env::set_var("DSH_HOME", value),
+ None => std::env::remove_var("DSH_HOME"),
+ }
+ assert!(status.signed_in);
+ assert!(!status.queried);
+ assert!(!status.expired, "Platform was contacted");
+ assert_eq!(status.error, None, "Platform was contacted");
+ assert_eq!(status.profile, None);
+ assert_eq!(
+ status.grant_fingerprint.as_deref(),
+ Some(grant_fingerprint("test-token").as_str())
+ );
+ }
+
+ #[test]
+ fn grant_fingerprint_changes_with_the_token() {
+ assert_eq!(grant_fingerprint("a").len(), 64);
+ assert_ne!(grant_fingerprint("a"), grant_fingerprint("b"));
+ }
+
#[test]
fn pkce_challenge_is_the_s256_of_the_verifier() {
let pkce = Pkce::generate();
diff --git a/src-tauri/src/services/kimi_oauth/mod.rs b/src-tauri/src/services/kimi_oauth/mod.rs
index a0f152fdf..fef8ef72d 100644
--- a/src-tauri/src/services/kimi_oauth/mod.rs
+++ b/src-tauri/src/services/kimi_oauth/mod.rs
@@ -644,10 +644,14 @@ impl KimiOAuthManager {
}
}
- pub async fn status(&self) -> Result<KimiOAuthStatus, String> {
+ /// `identify` asks Kimi for the nickname of accounts whose token changed; with it
+ /// false nothing is sent to Kimi (manual-only quota).
+ pub async fn status(&self, identify: bool) -> Result<KimiOAuthStatus, String> {
let home = kimi_config::data_dir();
let store = self.store();
- account::identify_accounts(&home, &store).await;
+ if identify {
+ account::identify_accounts(&home, &store).await;
+ }
accounts_status(&home, &store)
}
diff --git a/src/components/KimiAccountQuotaFooter.tsx b/src/components/KimiAccountQuotaFooter.tsx
index 7313ffe97..7aa34ff3e 100644
--- a/src/components/KimiAccountQuotaFooter.tsx
+++ b/src/components/KimiAccountQuotaFooter.tsx
@@ -1,11 +1,10 @@
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQueryClient } from "@tanstack/react-query";
import { useKimiAccountQuota } from "@/lib/query/subscription";
-import { kimiOAuthApi } from "@/lib/api/kimiOAuth";
import { SubscriptionQuotaView } from "@/components/SubscriptionQuotaFooter";
import { useQuotaDisplay } from "@/components/quota/useQuotaDisplay";
-import { KIMI_OAUTH_STATUS_KEY } from "@/components/providers/forms/hooks/useKimiOAuth";
+import { useKimiOAuthStatus } from "@/components/providers/forms/hooks/useKimiOAuth";
interface KimiAccountQuotaFooterProps {
/** Kimi 官方账号的供应商 ID(授权中心里的账号 ID 与它相同) */
@@ -41,11 +40,8 @@ const KimiAccountQuotaFooter: React.FC<KimiAccountQuotaFooterProps> = ({
// 卡片名里的昵称来自账号身份缓存,而缓存要查过账号状态才有。没进过授权中心时
// 这里顺带查一次,查到昵称后重新拉供应商列表,卡片就能显示是哪个号。
- const { data: status } = useQuery({
- queryKey: KIMI_OAUTH_STATUS_KEY,
- queryFn: kimiOAuthApi.status,
- staleTime: 5 * 60_000,
- });
+ // 只手动查询时不联网查昵称。
+ const { data: status } = useKimiOAuthStatus({ staleTime: 5 * 60_000 });
const nickname = status?.accounts.find(
(account) => account.id === accountId,
)?.nickname;
diff --git a/src/components/providers/DshAccount.tsx b/src/components/providers/DshAccount.tsx
index f4ce3a109..f2447f585 100644
--- a/src/components/providers/DshAccount.tsx
+++ b/src/components/providers/DshAccount.tsx
@@ -16,6 +16,7 @@ import {
} from "@/lib/api/dsh";
import { deliverLoginLink } from "@/lib/authLoginLink";
import { extractErrorMessage } from "@/utils/errorUtils";
+import { useQuotaPolicy } from "@/lib/query/quotaPolicy";
import { ProviderIconBox } from "@/components/ProviderIconBox";
import { resolveProviderIcon } from "@/utils/providerIcon";
import { CardChipBadge } from "./ProviderCard";
@@ -25,13 +26,69 @@ import type { CardChip } from "./presentation";
/** 授权中心和两个 DeepSeek Harness 供应商页共用一份查询:登录本来就是 Web / Desktop 共用的 */
export const DSH_ACCOUNT_STATUS_KEY = ["dsh-account-status"] as const;
+let dshForceRefreshEpoch = 0;
+
+/** 授权中心「全部刷新」时调用:只手动查询时,下一次查询也去平台查资料和余额。 */
+export function markDshForceRefresh() {
+ dshForceRefreshEpoch += 1;
+}
+
+/**
+ * 登录状态,自动查询时连同资料和余额。余额算官方额度:只手动查询时只读本机登录,
+ * 点 ↻ 或「全部刷新」才去平台查。
+ */
export function useDshAccountStatus(enabled = true) {
- return useQuery({
+ const queryClient = useQueryClient();
+ const { autoAllowed, manualOnly } = useQuotaPolicy();
+ const force = useRef(false);
+ const seenForceEpoch = useRef(dshForceRefreshEpoch);
+ const query = useQuery({
queryKey: DSH_ACCOUNT_STATUS_KEY,
- queryFn: dshApi.accountStatus,
- staleTime: 60_000,
- enabled,
+ queryFn: async () => {
+ const remote =
+ autoAllowed ||
+ force.current ||
+ seenForceEpoch.current !== dshForceRefreshEpoch;
+ force.current = false;
+ seenForceEpoch.current = dshForceRefreshEpoch;
+ const next = await dshApi.accountStatus(remote);
+ if (remote || !next.signedIn) return next;
+ const prev = queryClient.getQueryData<DshAccountStatus>(
+ DSH_ACCOUNT_STATUS_KEY,
+ );
+ // 同一登录则留下一次 ↻ 的资料和余额,避免本机刷新把它们冲掉
+ return prev?.signedIn &&
+ prev.queried &&
+ prev.grantFingerprint &&
+ prev.grantFingerprint === next.grantFingerprint
+ ? {
+ ...next,
+ profile: prev.profile,
+ wallets: prev.wallets,
+ bonusWallets: prev.bonusWallets,
+ queried: true,
+ error: prev.error,
+ expired: prev.expired,
+ }
+ : next;
+ },
+ // 只手动查询时本机登录立刻算过期:切回窗口或重新挂载就会重读,登入登出能马上看到。
+ // 余额仍靠下面把同一登录的上次 ↻ 结果补回去,不会被本机刷新冲掉。
+ staleTime: manualOnly ? 0 : 60_000,
+ refetchOnWindowFocus: true,
+ enabled: enabled && (autoAllowed || manualOnly),
});
+ // 开关重新打开后查询本来就是 enabled,60 秒内不会自动重查,行会一直停在「点刷新查询额度」。
+ useEffect(() => {
+ if (autoAllowed && query.data?.signedIn && query.data.queried === false) {
+ void query.refetch();
+ }
+ }, [autoAllowed, query.data?.signedIn, query.data?.queried, query.refetch]);
+ const refresh = () => {
+ force.current = true;
+ return query.refetch();
+ };
+ return { ...query, refresh };
}
const CURRENCY_SYMBOL: Record<string, string> = { CNY: "¥", USD: "$" };
@@ -63,7 +120,7 @@ function DshBalance({
}: {
login: string;
status: DshAccountStatus;
- queriedAt: number;
+ queriedAt: number | null;
loading: boolean;
onRefresh: () => void;
}) {
@@ -74,7 +131,9 @@ function DshBalance({
return (
<>
<div className="flex min-w-0 shrink-0 flex-col items-end justify-center gap-0.5 text-end">
- {status.error ? (
+ {!status.queried ? (
+ <span className={`${cell} text-fg-3`}>{t("quota.manualIdle")}</span>
+ ) : status.error ? (
<span className={`${cell} text-fg-3`}>
{t("dsh.account.balanceFailed")}
</span>
@@ -238,9 +297,9 @@ export function DshAccountLogin({ helpSide }: DshAccountLoginProps) {
<DshBalance
login={name}
status={data}
- queriedAt={status.dataUpdatedAt}
+ queriedAt={data.queried ? status.dataUpdatedAt : null}
loading={status.isFetching}
- onRefresh={() => void status.refetch()}
+ onRefresh={() => void status.refresh()}
/>
),
removeLabel: t("dsh.account.signOut"),
diff --git a/src/components/providers/forms/hooks/useKimiOAuth.ts b/src/components/providers/forms/hooks/useKimiOAuth.ts
index 0cef77e3d..6349a8a0e 100644
--- a/src/components/providers/forms/hooks/useKimiOAuth.ts
+++ b/src/components/providers/forms/hooks/useKimiOAuth.ts
@@ -9,18 +9,44 @@ import {
import { deliverLoginLink } from "@/lib/authLoginLink";
import { extractErrorMessage } from "@/utils/errorUtils";
import { toast } from "@/lib/toast";
+import { useQuotaPolicy } from "@/lib/query/quotaPolicy";
export const KIMI_OAUTH_STATUS_KEY = ["kimi-oauth-status"];
const STATUS_KEY = KIMI_OAUTH_STATUS_KEY;
+/**
+ * 账号列表和昵称。只手动查询时不联网查昵称;把自动查询重新打开时补一次,
+ * 否则 5 分钟 staleTime(卡片)或下一次 30 秒轮询(授权中心)到来前都还是旧结果。
+ */
+export function useKimiOAuthStatus(options?: {
+ staleTime?: number;
+ refetchInterval?: number;
+}) {
+ const { autoAllowed, manualOnly } = useQuotaPolicy();
+ const identified = useRef(false);
+ const query = useQuery({
+ queryKey: STATUS_KEY,
+ queryFn: () => {
+ identified.current = autoAllowed;
+ return kimiOAuthApi.status(autoAllowed);
+ },
+ staleTime: options?.staleTime,
+ refetchInterval: options?.refetchInterval,
+ enabled: autoAllowed || manualOnly,
+ });
+ useEffect(() => {
+ if (autoAllowed && query.isSuccess && !identified.current) {
+ void query.refetch();
+ }
+ }, [autoAllowed, query.isSuccess, query.refetch]);
+ return query;
+}
+
export function useKimiOAuth() {
const { t } = useTranslation();
const queryClient = useQueryClient();
- const status = useQuery({
- queryKey: STATUS_KEY,
- queryFn: kimiOAuthApi.status,
- refetchInterval: 30_000,
- });
+ // 账号昵称要联网问 Kimi;只手动查询时只列本机保存的账号
+ const status = useKimiOAuthStatus({ refetchInterval: 30_000 });
const [flow, setFlow] = useState<KimiLoginStart | null>(null);
const [starting, setStarting] = useState(false);
const [error, setError] = useState<string | null>(null);
diff --git a/src/components/settings/auth/AutoQuotaToggle.tsx b/src/components/settings/auth/AutoQuotaToggle.tsx
index f84c9eb48..b65b57e31 100644
--- a/src/components/settings/auth/AutoQuotaToggle.tsx
+++ b/src/components/settings/auth/AutoQuotaToggle.tsx
@@ -10,7 +10,6 @@ import { ToggleCard } from "./ToggleCard";
/**
* 「自动查询额度」(#8990):关掉后官方账号的额度只在点 ↻ /「全部刷新」时查,打开授权中心、
* 供应商卡片定时刷新、悬停托盘都不再自动查额度——网络代理还没就绪时不会意外直连官方服务。
- * DeepSeek 账号的余额和登录状态是同一个请求,不归这个开关管,文案里写明。
* 存在设置里(托盘在后端也要读)。
*/
export function AutoQuotaToggle() {
@@ -42,7 +41,7 @@ export function AutoQuotaToggle() {
})}
description={t("authCenter.autoQuota.description", {
defaultValue:
- "关掉后,官方账号的额度只在你点刷新时查询,打开授权中心、卡片定时刷新和悬停托盘都不会自动去查。DeepSeek 账号的余额和登录状态一起显示,不受这个开关影响。",
+ "关掉后,官方账号的额度只在你点刷新时查询,打开授权中心、卡片定时刷新和悬停托盘都不会自动去查。",
})}
checked={settings?.officialQuotaManualOnly !== true}
disabled={!settings || saving}
diff --git a/src/components/settings/auth/RefreshAllQuotaButton.tsx b/src/components/settings/auth/RefreshAllQuotaButton.tsx
index 8f89dcc2b..b2f3ab884 100644
--- a/src/components/settings/auth/RefreshAllQuotaButton.tsx
+++ b/src/components/settings/auth/RefreshAllQuotaButton.tsx
@@ -9,7 +9,10 @@ import {
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { ManagedAuthStatus } from "@/lib/api/auth";
-import { DSH_ACCOUNT_STATUS_KEY } from "@/components/providers/DshAccount";
+import {
+ DSH_ACCOUNT_STATUS_KEY,
+ markDshForceRefresh,
+} from "@/components/providers/DshAccount";
import {
WORKBUDDY_QUOTA_KEY,
markWorkBuddyQuotaForceRefresh,
@@ -89,6 +92,7 @@ export function RefreshAllQuotaButton() {
onClick={() => {
markAgyQuotaForceRefresh();
markCodebuddyQuotaForceRefresh();
+ markDshForceRefresh();
markWorkBuddyQuotaForceRefresh();
void Promise.all(
queryClient
diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json
index a0106a3b2..b4bfcd5fa 100644
--- a/src/i18n/locales/de.json
+++ b/src/i18n/locales/de.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "Kontingent automatisch abfragen",
- "description": "Wenn deaktiviert, werden offizielle Kontokontingente nur beim Klicken auf Aktualisieren abgefragt: Das Öffnen des Auth-Centers, geplante Kartenaktualisierungen und das Überfahren des Tray-Symbols fragen sie nicht ab. DeepSeek-Kontoguthaben werden zusammen mit dem Anmeldestatus angezeigt und sind von diesem Schalter nicht betroffen."
+ "description": "Wenn deaktiviert, werden offizielle Kontokontingente nur beim Klicken auf Aktualisieren abgefragt: Das Öffnen des Auth-Centers, geplante Kartenaktualisierungen und das Überfahren des Tray-Symbols fragen sie nicht ab."
}
},
"kimi": {
diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json
index e6e2ad8fd..456c972ce 100644
--- a/src/i18n/locales/en.json
+++ b/src/i18n/locales/en.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "Query quota automatically",
- "description": "When off, official account quotas are only queried when you click refresh: opening the Auth Center, scheduled card refreshes and hovering the tray won't query them. DeepSeek account balances are shown with the sign-in status and aren't affected by this switch."
+ "description": "When off, official account quotas are only queried when you click refresh: opening the Auth Center, scheduled card refreshes and hovering the tray won't query them."
}
},
"kimi": {
diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json
index 0521eab2e..fbad11f9f 100644
--- a/src/i18n/locales/ja.json
+++ b/src/i18n/locales/ja.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "残量を自動で取得",
- "description": "オフにすると、公式アカウントの残量は更新をクリックしたときだけ取得します。認証センターを開いたとき、カードの定期更新、トレイへのホバーでは取得しません。DeepSeek アカウントの残高はログイン状態と一緒に表示されるため、このスイッチの影響を受けません。"
+ "description": "オフにすると、公式アカウントの残量は更新をクリックしたときだけ取得します。認証センターを開いたとき、カードの定期更新、トレイへのホバーでは取得しません。"
}
},
"kimi": {
diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json
index 44b451bbe..e28e1cc08 100644
--- a/src/i18n/locales/ko.json
+++ b/src/i18n/locales/ko.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "할당량 자동 조회",
- "description": "끄면 새로고침을 클릭할 때만 공식 계정 할당량을 조회합니다. 인증 센터 열기, 카드 예약 새로고침 및 트레이 아이콘 마우스오버 시에는 조회하지 않습니다. DeepSeek 계정 잔액은 로그인 상태와 함께 표시되므로 이 스위치의 영향을 받지 않습니다."
+ "description": "끄면 새로고침을 클릭할 때만 공식 계정 할당량을 조회합니다. 인증 센터 열기, 카드 예약 새로고침 및 트레이 아이콘 마우스오버 시에는 조회하지 않습니다."
}
},
"kimi": {
diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json
index 1c66d26b0..4cd602e8b 100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@ -5511,7 +5511,7 @@
},
"autoQuota": {
"title": "Автоматически запрашивать квоту",
- "description": "Когда выключено, квоты официальных аккаунтов запрашиваются только по нажатию кнопки обновления: открытие Центра авторизации, плановые обновления карточек и наведение на значок в трее их не запрашивают. Баланс аккаунтов DeepSeek показывается вместе со статусом входа, поэтому этот переключатель на него не влияет."
+ "description": "Когда выключено, квоты официальных аккаунтов запрашиваются только по нажатию кнопки обновления: открытие Центра авторизации, плановые обновления карточек и наведение на значок в трее их не запрашивают."
}
},
"kimi": {
diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.json
index 6160562bd..766fea853 100644
--- a/src/i18n/locales/tr.json
+++ b/src/i18n/locales/tr.json
@@ -5442,7 +5442,7 @@
},
"autoQuota": {
"title": "Kotayı otomatik sorgula",
- "description": "Kapalıyken resmi hesap kotaları yalnızca yenile düğmesine tıkladığınızda sorgulanır: Yetkilendirme Merkezi’ni açmak, kartların zamanlanmış yenilemeleri ve tepsi simgesinin üzerine gelmek kotaları sorgulamaz. DeepSeek hesap bakiyeleri oturum durumuyla birlikte gösterildiğinden bu anahtardan etkilenmez."
+ "description": "Kapalıyken resmi hesap kotaları yalnızca yenile düğmesine tıkladığınızda sorgulanır: Yetkilendirme Merkezi’ni açmak, kartların zamanlanmış yenilemeleri ve tepsi simgesinin üzerine gelmek kotaları sorgulamaz."
}
},
"kimi": {
diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json
index b7737eb96..401f8680e 100644
--- a/src/i18n/locales/zh-TW.json
+++ b/src/i18n/locales/zh-TW.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "自動查詢額度",
- "description": "關掉後,官方帳號的額度只在你點重新整理時查詢,開啟授權中心、卡片定時重新整理和懸停系統匣都不會自動去查。DeepSeek 帳號的餘額和登入狀態一起顯示,不受這個開關影響。"
+ "description": "關掉後,官方帳號的額度只在你點重新整理時查詢,開啟授權中心、卡片定時重新整理和懸停系統匣都不會自動去查。"
}
},
"kimi": {
diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json
index 0b1755de2..b14300e0d 100644
--- a/src/i18n/locales/zh.json
+++ b/src/i18n/locales/zh.json
@@ -5513,7 +5513,7 @@
},
"autoQuota": {
"title": "自动查询额度",
- "description": "关掉后,官方账号的额度只在你点刷新时查询,打开授权中心、卡片定时刷新和悬停托盘都不会自动去查。DeepSeek 账号的余额和登录状态一起显示,不受这个开关影响。"
+ "description": "关掉后,官方账号的额度只在你点刷新时查询,打开授权中心、卡片定时刷新和悬停托盘都不会自动去查。"
}
},
"kimi": {
diff --git a/src/lib/api/dsh.ts b/src/lib/api/dsh.ts
index ce3c42fb3..c323c3694 100644
--- a/src/lib/api/dsh.ts
+++ b/src/lib/api/dsh.ts
@@ -23,6 +23,8 @@ export interface DshAccountStatus {
/** 平台拒绝了保存的登录(已过期),DeepSeek Harness 下次请求账号时会清掉 */
expired: boolean;
issuer: string | null;
+ /** SHA-256 of the stored token; issuer is only the platform origin. */
+ grantFingerprint: string | null;
profile: DshAccountProfile | null;
/** 充值余额 */
wallets: DshWallet[];
@@ -32,6 +34,8 @@ export interface DshAccountStatus {
topUpUrl: string | null;
/** 资料或余额没查到;登录本身还在 */
error: string | null;
+ /** 这次去平台查了资料和余额;false 时只读了本机登录(只手动查询) */
+ queried: boolean;
}
export interface DshLoginStart {
@@ -42,7 +46,9 @@ export interface DshLoginStart {
}
export const dshApi = {
- accountStatus: () => invoke<DshAccountStatus>("dsh_account_status"),
+ /** `remote` 为 false 时不联网,只读本机登录 */
+ accountStatus: (remote: boolean) =>
+ invoke<DshAccountStatus>("dsh_account_status", { remote }),
/** Web 和 Desktop 同时退出 */
accountSignOut: () => invoke<void>("dsh_account_sign_out"),
/** 和 DeepSeek Harness Web 同一套浏览器登录;登录写进 Web 与 Desktop 共用的凭据文件 */
diff --git a/src/lib/api/kimiOAuth.ts b/src/lib/api/kimiOAuth.ts
index 410c2d6bc..88cf25aee 100644
--- a/src/lib/api/kimiOAuth.ts
+++ b/src/lib/api/kimiOAuth.ts
@@ -33,7 +33,9 @@ export interface KimiLoginStart {
}
export const kimiOAuthApi = {
- status: () => invoke<KimiOAuthStatus>("kimi_oauth_status"),
+ /** `identify` 为 false 时不联网查账号昵称(只手动查询) */
+ status: (identify: boolean) =>
+ invoke<KimiOAuthStatus>("kimi_oauth_status", { identify }),
start: (region: KimiRegion, accountId?: string) =>
invoke<KimiLoginStart>("kimi_oauth_start", {
region,
diff --git a/tests/components/DshAccountCard.test.tsx b/tests/components/DshAccountCard.test.tsx
index f23e98209..17ef5111d 100644
--- a/tests/components/DshAccountCard.test.tsx
+++ b/tests/components/DshAccountCard.test.tsx
@@ -9,12 +9,14 @@ const signedIn: DshAccountStatus = {
signedIn: true,
expired: false,
issuer: "https://platform.deepseek.com",
+ grantFingerprint: "fp-jason",
profile: { id: "u1", name: "Jason", contact: null, avatarUrl: null },
wallets: [{ currency: "CNY", balance: "102.11" }],
bonusWallets: [],
usageUrl: null,
topUpUrl: null,
error: null,
+ queried: true,
};
function renderCard(status: DshAccountStatus) {
diff --git a/tests/components/DshAddProviderDialog.test.tsx b/tests/components/DshAddProviderDialog.test.tsx
index f301a0327..fba4af3c1 100644
--- a/tests/components/DshAddProviderDialog.test.tsx
+++ b/tests/components/DshAddProviderDialog.test.tsx
@@ -46,12 +46,14 @@ const signedOut: DshAccountStatus = {
signedIn: false,
expired: false,
issuer: null,
+ grantFingerprint: null,
profile: null,
wallets: [],
bonusWallets: [],
usageUrl: null,
topUpUrl: null,
error: null,
+ queried: false,
};
describe("DeepSeek account entry in the DeepSeek Harness add-provider dialog", () => {
diff --git a/tests/lib/quotaManualOnly.test.tsx b/tests/lib/quotaManualOnly.test.tsx
index 312d87b66..9ea41b314 100644
--- a/tests/lib/quotaManualOnly.test.tsx
+++ b/tests/lib/quotaManualOnly.test.tsx
@@ -1,4 +1,8 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ QueryClient,
+ QueryClientProvider,
+ focusManager,
+} from "@tanstack/react-query";
import {
act,
fireEvent,
@@ -19,6 +23,8 @@ import {
} from "@/lib/query/subscription";
import { useQuotaPlan } from "@/lib/query/accountPlans";
import { useWorkBuddyAccountQuota } from "@/components/providers/workbuddyQuota";
+import { useDshAccountStatus } from "@/components/providers/DshAccount";
+import KimiAccountQuotaFooter from "@/components/KimiAccountQuotaFooter";
import { SubscriptionQuotaView } from "@/components/SubscriptionQuotaFooter";
import { AutoQuotaToggle } from "@/components/settings/auth/AutoQuotaToggle";
import { RefreshAllQuotaButton } from "@/components/settings/auth/RefreshAllQuotaButton";
@@ -31,6 +37,16 @@ const mocks = vi.hoisted(() => ({
codebuddyAccountQuota: vi.fn(),
getSettings: vi.fn(),
saveSettings: vi.fn(),
+ dshAccountStatus: vi.fn(),
+ kimiStatus: vi.fn(),
+ kimiQuota: vi.fn(),
+}));
+vi.mock("@/lib/api/dsh", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/api/dsh")>()),
+ dshApi: { accountStatus: mocks.dshAccountStatus },
+}));
+vi.mock("@/lib/api/kimiOAuth", () => ({
+ kimiOAuthApi: { status: mocks.kimiStatus, quota: mocks.kimiQuota },
}));
vi.mock("@/lib/api/subscription", () => ({
subscriptionApi: {
@@ -95,6 +111,18 @@ describe("manual-only official quota (#8990)", () => {
queriedAt: 1,
});
mocks.getSettings.mockReset();
+ mocks.dshAccountStatus.mockReset().mockResolvedValue({
+ signedIn: true,
+ expired: false,
+ wallets: [],
+ bonusWallets: [],
+ });
+ mocks.kimiStatus.mockReset().mockResolvedValue({
+ accounts: [],
+ currentAccountId: null,
+ primaryHidden: false,
+ });
+ mocks.kimiQuota.mockReset().mockResolvedValue(quota);
mocks.saveSettings.mockReset().mockResolvedValue(true);
});
@@ -307,6 +335,246 @@ describe("manual-only official quota (#8990)", () => {
);
});
+ // `dsh_account_status(remote)` and `kimi_oauth_status(identify)` only contact
+ // DeepSeek / Kimi when their flag is true.
+ it("keeps the DeepSeek balance query off the network until a refresh click", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(newClient()),
+ });
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(true));
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([[false]]);
+
+ await act(async () => {
+ await result.current.refresh();
+ });
+ expect(mocks.dshAccountStatus).toHaveBeenLastCalledWith(true);
+ });
+
+ it("queries the DeepSeek balance on its own when automatic queries are on", async () => {
+ mocks.getSettings.mockResolvedValue({});
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(newClient()),
+ });
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(true));
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([[true]]);
+ });
+
+ it("lets Refresh all query the DeepSeek balance when automatic queries are off", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ function Row() {
+ const { data } = useDshAccountStatus();
+ return <span>{data ? "shown" : "pending"}</span>;
+ }
+ render(
+ <>
+ <Row />
+ <RefreshAllQuotaButton />
+ </>,
+ { wrapper: wrapperFor(newClient()) },
+ );
+ await screen.findByText("shown");
+ fireEvent.click(
+ screen.getByRole("button", { name: zh.authCenter.quota.refreshAll }),
+ );
+ await waitFor(() =>
+ expect(mocks.dshAccountStatus).toHaveBeenLastCalledWith(true),
+ );
+ });
+
+ it("does not ask Kimi for account identities from a card while automatic queries are off", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ render(
+ <KimiAccountQuotaFooter accountId="kimi-a" name="Kimi" isCurrent />,
+ {
+ wrapper: wrapperFor(newClient()),
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(mocks.kimiQuota).not.toHaveBeenCalled();
+ for (const call of mocks.kimiStatus.mock.calls)
+ expect(call).toEqual([false]);
+ });
+
+ it("queries the DeepSeek balance when automatic queries are turned back on", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ mocks.dshAccountStatus.mockImplementation(async (remote: boolean) => ({
+ signedIn: true,
+ expired: false,
+ wallets: [],
+ bonusWallets: [],
+ queried: remote,
+ }));
+ const client = newClient();
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(client),
+ });
+ await waitFor(() => expect(result.current.data?.queried).toBe(false));
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([[false]]);
+
+ mocks.getSettings.mockResolvedValue({});
+ await act(async () => {
+ await client.invalidateQueries({ queryKey: ["settings"] });
+ });
+
+ await waitFor(() => expect(result.current.data?.queried).toBe(true));
+ expect(mocks.dshAccountStatus).toHaveBeenCalledWith(true);
+ });
+
+ it("asks Kimi for account identities when automatic queries are turned back on", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ const client = newClient();
+ render(
+ <KimiAccountQuotaFooter accountId="kimi-a" name="Kimi" isCurrent />,
+ { wrapper: wrapperFor(client) },
+ );
+ await waitFor(() => expect(mocks.kimiStatus).toHaveBeenCalled());
+ expect(mocks.kimiStatus.mock.calls).toEqual([[false]]);
+ expect(mocks.kimiQuota).not.toHaveBeenCalled();
+
+ mocks.getSettings.mockResolvedValue({});
+ await act(async () => {
+ await client.invalidateQueries({ queryKey: ["settings"] });
+ });
+
+ await waitFor(() => expect(mocks.kimiStatus).toHaveBeenCalledWith(true));
+ });
+
+ it("updates the DeepSeek login state on window focus when automatic queries are off", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ mocks.dshAccountStatus.mockResolvedValue({
+ signedIn: true,
+ expired: false,
+ wallets: [],
+ bonusWallets: [],
+ queried: false,
+ });
+ focusManager.setFocused(true);
+ try {
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(newClient()),
+ });
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(true));
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([[false]]);
+
+ mocks.dshAccountStatus.mockResolvedValue({
+ signedIn: false,
+ expired: false,
+ wallets: [],
+ bonusWallets: [],
+ queried: false,
+ });
+ act(() => focusManager.setFocused(false));
+ act(() => focusManager.setFocused(true));
+
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(false));
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([[false], [false]]);
+ } finally {
+ focusManager.setFocused(undefined);
+ }
+ });
+
+ it("keeps a manually queried DeepSeek balance across a local login refresh", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ const local = {
+ signedIn: true,
+ expired: false,
+ issuer: "https://platform.deepseek.com",
+ grantFingerprint: "fp-a",
+ profile: null,
+ wallets: [],
+ bonusWallets: [],
+ queried: false,
+ };
+ const remote = {
+ ...local,
+ queried: true,
+ profile: { id: "u1", name: "Jason", contact: null, avatarUrl: null },
+ wallets: [{ currency: "CNY", balance: "10.00" }],
+ };
+ mocks.dshAccountStatus.mockImplementation(async (remoteQuery: boolean) =>
+ remoteQuery ? remote : local,
+ );
+ focusManager.setFocused(true);
+ try {
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(newClient()),
+ });
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(true));
+ await act(async () => {
+ await result.current.refresh();
+ });
+ await waitFor(() => expect(result.current.data?.queried).toBe(true));
+ expect(result.current.data?.wallets).toEqual([
+ { currency: "CNY", balance: "10.00" },
+ ]);
+
+ act(() => focusManager.setFocused(false));
+ act(() => focusManager.setFocused(true));
+ await waitFor(() =>
+ expect(mocks.dshAccountStatus.mock.calls).toEqual([
+ [false],
+ [true],
+ [false],
+ ]),
+ );
+ expect(result.current.data?.queried).toBe(true);
+ expect(result.current.data?.profile?.name).toBe("Jason");
+ expect(result.current.data?.wallets).toEqual([
+ { currency: "CNY", balance: "10.00" },
+ ]);
+ } finally {
+ focusManager.setFocused(undefined);
+ }
+ });
+
+ it("drops a cached DeepSeek balance when the local login changes", async () => {
+ mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
+ const localA = {
+ signedIn: true,
+ expired: false,
+ issuer: "https://platform.deepseek.com",
+ grantFingerprint: "fp-a",
+ profile: null,
+ wallets: [],
+ bonusWallets: [],
+ queried: false,
+ };
+ const remoteA = {
+ ...localA,
+ queried: true,
+ profile: { id: "u1", name: "Jason", contact: null, avatarUrl: null },
+ wallets: [{ currency: "CNY", balance: "10.00" }],
+ };
+ mocks.dshAccountStatus.mockImplementation(async (remoteQuery: boolean) =>
+ remoteQuery ? remoteA : localA,
+ );
+ focusManager.setFocused(true);
+ try {
+ const { result } = renderHook(() => useDshAccountStatus(), {
+ wrapper: wrapperFor(newClient()),
+ });
+ await waitFor(() => expect(result.current.data?.signedIn).toBe(true));
+ await act(async () => {
+ await result.current.refresh();
+ });
+ await waitFor(() => expect(result.current.data?.queried).toBe(true));
+
+ mocks.dshAccountStatus.mockResolvedValue({
+ ...localA,
+ grantFingerprint: "fp-b",
+ });
+ act(() => focusManager.setFocused(false));
+ act(() => focusManager.setFocused(true));
+ await waitFor(() => expect(result.current.data?.queried).toBe(false));
+ expect(result.current.data?.signedIn).toBe(true);
+ expect(result.current.data?.wallets).toEqual([]);
+ expect(result.current.data?.profile).toBeNull();
+ } finally {
+ focusManager.setFocused(undefined);
+ }
+ });
+
it("clears the default Codex quota snapshot on account switch without auto-refetching in manual-only mode", async () => {
mocks.getSettings.mockResolvedValue({ officialQuotaManualOnly: true });
mocks.getCodexOauthQuota
diff --git a/tests/msw/handlers.ts b/tests/msw/handlers.ts
index 8fc3afb2c..269f445bf 100644
--- a/tests/msw/handlers.ts
+++ b/tests/msw/handlers.ts
@@ -641,6 +641,7 @@ export const handlers = [
signedIn: false,
expired: false,
issuer: null,
+ grantFingerprint: null,
profile: null,
wallets: [],
bonusWallets: [],