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(providers): isolate stale state across app switches and complete cross-page quota cache invalidation (#9997)

funkpopo9b6a9a0babc3
diff --git a/src/App.tsx b/src/App.tsx
index 53efa9406..1b9927d7d 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -24,7 +24,10 @@ import type { Provider, VisibleApps } from "@/types";
import { KNOWN_APP_TYPES, type AppTypeFilter } from "@/types/usage";
import type { EnvConflict } from "@/types/env";
import type { SubscriptionQuota } from "@/types/subscription";
-import { invalidateGrokCliLoginCaches } from "@/lib/query/subscription";
+import {
+ invalidateClaudeOfficialLoginCaches,
+ invalidateGrokCliLoginCaches,
+} from "@/lib/query/subscription";
import { providersQueryOptions, useProvidersQuery } from "@/lib/query/queries";
import { useSettingsQuery } from "@/lib/query/settings";
import { proxyKeys } from "@/lib/query/proxy";
@@ -361,6 +364,11 @@ function App() {
// 新增页和编辑页共用的表单很大,启动后空闲时先拉好(编辑页在 EditProviderHost 里预取)
useEffect(() => preloadOnIdle(loadAddProviderDialog), []);
const [usageProvider, setUsageProvider] = useState<Provider | null>(null);
+ const [usageModalSession, setUsageModalSession] = useState(0);
+ const openUsageScriptModal = useCallback((provider: Provider) => {
+ setUsageModalSession((n) => n + 1);
+ setUsageProvider(provider);
+ }, []);
const [confirmAction, setConfirmAction] = useState<{
provider: Provider;
action: "remove" | "delete";
@@ -536,9 +544,7 @@ function App() {
}
if (event.appType === "claude") {
// 托盘切卡、应用项目同样可能把默认登录收成新账号
- await queryClient.invalidateQueries({
- queryKey: ["managed-auth-status", "claude_official"],
- });
+ await invalidateClaudeOfficialLoginCaches(queryClient);
}
if (event.appType === "grokbuild") {
// 托盘切卡同样可能把 Grok CLI 原登录收成新账号、换成绑定的号
@@ -1628,7 +1634,7 @@ function App() {
onDelete: (provider: Provider) =>
setConfirmAction({ provider, action: "delete" }),
onDuplicate: handleDuplicateProvider,
- onConfigureUsage: setUsageProvider,
+ onConfigureUsage: openUsageScriptModal,
onOpenWebsite: handleOpenWebsite,
onOpenTerminal:
activeApp === "claude" ||
@@ -1985,7 +1991,7 @@ function App() {
{effectiveUsageProvider && (
<UsageScriptModal
- key={effectiveUsageProvider.id}
+ key={`${activeApp}:${effectiveUsageProvider.id}:${usageModalSession}`}
provider={effectiveUsageProvider}
appId={activeApp}
isOpen={Boolean(usageProvider)}
diff --git a/src/components/apps/AppsPage.tsx b/src/components/apps/AppsPage.tsx
index 17e3caa16..4169fbc90 100644
--- a/src/components/apps/AppsPage.tsx
+++ b/src/components/apps/AppsPage.tsx
@@ -45,6 +45,7 @@ import {
} from "lucide-react";
import { settingsApi, type AppId } from "@/lib/api";
import { providersApi } from "@/lib/api/providers";
+import { CLAUDE_DESKTOP_STATUS_QUERY_KEY } from "@/lib/query/queries";
import type { ToolInstallationOverview } from "@/lib/api/settings";
import type { VisibleApps } from "@/types";
import { DEFAULT_VISIBLE_APPS, orderAppIds } from "@/config/appConfig";
@@ -207,7 +208,7 @@ export function AppsPage() {
});
const tableRef = useRef<HTMLDivElement>(null);
const { data: desktopStatus, isPending: isDesktopStatusPending } = useQuery({
- queryKey: ["claude-desktop-status"],
+ queryKey: CLAUDE_DESKTOP_STATUS_QUERY_KEY,
queryFn: () => providersApi.getClaudeDesktopStatus(),
staleTime: 30_000,
});
diff --git a/src/components/providers/AddProviderDialog.tsx b/src/components/providers/AddProviderDialog.tsx
index d7eabcb1d..69f8a956a 100644
--- a/src/components/providers/AddProviderDialog.tsx
+++ b/src/components/providers/AddProviderDialog.tsx
@@ -100,16 +100,66 @@ export function AddProviderDialog({
const [universalFormOpen, setUniversalFormOpen] = useState(false);
const [selectedUniversalPreset, setSelectedUniversalPreset] =
useState<UniversalProviderPreset | null>(null);
- const [isFormSubmitting, setIsFormSubmitting] = useState(false);
+ const formSessionSequence = useRef(0);
+ const formSessionToken = useMemo(
+ () => ++formSessionSequence.current,
+ [appId, open],
+ );
+ const currentFormSessionToken = useRef(formSessionToken);
+ currentFormSessionToken.current = formSessionToken;
+ const [formSubmittingState, setFormSubmittingState] = useState({
+ token: formSessionToken,
+ submitting: false,
+ });
+ const isFormSubmitting =
+ formSubmittingState.token === formSessionToken &&
+ formSubmittingState.submitting;
+ const handleSubmittingChange = useCallback(
+ (submitting: boolean) => {
+ if (currentFormSessionToken.current === formSessionToken) {
+ setFormSubmittingState({ token: formSessionToken, submitting });
+ }
+ },
+ [formSessionToken],
+ );
// 表单用了聚合的简化布局:页头应用名后标「聚合模式」
- const [stackLayout, setStackLayout] = useState(false);
- const [accountLogin, setAccountLogin] = useState(false);
+ const [stackLayoutState, setStackLayoutState] = useState({
+ token: formSessionToken,
+ stackLayout: false,
+ });
+ const stackLayout =
+ stackLayoutState.token === formSessionToken && stackLayoutState.stackLayout;
+ const handleStackLayoutChange = useCallback(
+ (next: boolean) => {
+ if (currentFormSessionToken.current === formSessionToken) {
+ setStackLayoutState({ token: formSessionToken, stackLayout: next });
+ }
+ },
+ [formSessionToken],
+ );
+ const [accountLoginState, setAccountLoginState] = useState({
+ token: formSessionToken,
+ accountLogin: false,
+ });
+ const accountLogin =
+ accountLoginState.token === formSessionToken &&
+ accountLoginState.accountLogin;
+ const handleAccountLoginChange = useCallback(
+ (next: boolean) => {
+ if (currentFormSessionToken.current === formSessionToken) {
+ setAccountLoginState({ token: formSessionToken, accountLogin: next });
+ }
+ },
+ [formSessionToken],
+ );
const [authSettingsTarget, setAuthSettingsTarget] =
useState<AuthCenterTarget | null>(null);
useEffect(() => {
setAuthSettingsTarget(null);
- setAccountLogin(false);
+ setManageUniversalOpen(false);
+ setUniversalFormOpen(false);
+ setSelectedUniversalPreset(null);
}, [appId, open]);
// Claude:预设的关键字段套在当前 live 上显示(去掉当前供应商的关键字段),保存时
@@ -122,18 +172,32 @@ export function AddProviderDialog({
// Codex、Gemini CLI、Grok Build:表单把预设投影到当前配置文件上显示,投影结果就是保存时
// 三方比较的底(投影进行中或失败时为 null,保存只存供应商)。投影成它的草稿一起留着,
// 后端按草稿分开预设带的字段和从 live 带进来的字段。
- const [draftEditorBase, setDraftEditorBase] = useState<{
- base: Record<string, unknown>;
- draft?: Record<string, unknown>;
- } | null>(null);
+ const [draftEditorBaseState, setDraftEditorBaseState] = useState<{
+ token: number;
+ value: {
+ base: Record<string, unknown>;
+ draft?: Record<string, unknown>;
+ } | null;
+ }>({ token: formSessionToken, value: null });
+ const draftEditorBase =
+ draftEditorBaseState.token === formSessionToken
+ ? draftEditorBaseState.value
+ : null;
const handleDraftEditorBase = useCallback(
- (base: Record<string, unknown> | null, draft?: Record<string, unknown>) =>
- setDraftEditorBase(base ? { base, draft } : null),
- [],
+ (base: Record<string, unknown> | null, draft?: Record<string, unknown>) => {
+ if (currentFormSessionToken.current === formSessionToken) {
+ setDraftEditorBaseState({
+ token: formSessionToken,
+ value: base ? { base, draft } : null,
+ });
+ }
+ },
+ [formSessionToken],
);
// 新增时表单自己把预设投影到配置文件上的应用(Claude Code 在对话框里取底,见上)。
const projectsDraft = appId !== "claude" && appHas(appId, "editorView");
- const { submitWithConflictRetry, conflictDialog } = useLiveEditConflict();
+ const { submitWithConflictRetry, conflictDialog } =
+ useLiveEditConflict(formSessionToken);
useEffect(() => {
if (!open || appId !== "claude") {
@@ -165,9 +229,9 @@ export function AddProviderDialog({
const closeDialog = useCallback(() => {
setAuthSettingsTarget(null);
// 表单每次打开都会重新投影;这里清掉,免得下次打开时先用上一次的底。
- setDraftEditorBase(null);
+ setDraftEditorBaseState({ token: formSessionToken, value: null });
onOpenChange(false);
- }, [onOpenChange]);
+ }, [onOpenChange, formSessionToken]);
const handlePanelClose = useCallback(() => {
if (authSettingsTarget) {
@@ -181,27 +245,21 @@ export function AddProviderDialog({
}
closeDialog();
}, [authSettingsTarget, closeDialog, step]);
- const formReadyToken = useMemo(
- () => Symbol("provider-form-ready"),
- [appId, open],
- );
- const currentFormReadyToken = useRef(formReadyToken);
- currentFormReadyToken.current = formReadyToken;
const [formReadyState, setFormReadyState] = useState({
- token: formReadyToken,
+ token: formSessionToken,
ready: !appHas(appId, "piFamily"),
});
const isFormReady =
- formReadyState.token === formReadyToken
+ formReadyState.token === formSessionToken
? formReadyState.ready
: !appHas(appId, "piFamily");
const handleSubmitReadyChange = useCallback(
(ready: boolean) => {
- if (currentFormReadyToken.current === formReadyToken) {
- setFormReadyState({ token: formReadyToken, ready });
+ if (currentFormSessionToken.current === formSessionToken) {
+ setFormReadyState({ token: formSessionToken, ready });
}
},
- [formReadyToken],
+ [formSessionToken],
);
const handleUniversalProviderSave = useCallback(
@@ -240,11 +298,13 @@ export function AddProviderDialog({
);
}
- setUniversalFormOpen(false);
- setSelectedUniversalPreset(null);
- onOpenChange(false);
+ if (currentFormSessionToken.current === formSessionToken) {
+ setUniversalFormOpen(false);
+ setSelectedUniversalPreset(null);
+ onOpenChange(false);
+ }
},
- [t, onOpenChange],
+ [t, onOpenChange, formSessionToken],
);
const handleUniversalFormClose = useCallback(() => {
@@ -457,7 +517,9 @@ export function AddProviderDialog({
...providerData,
...(editorBase ? { editorSave: { ...editorBase, onConflict } } : {}),
});
- closeDialog();
+ if (currentFormSessionToken.current === formSessionToken) {
+ closeDialog();
+ }
};
await submitWithConflictRetry(submit);
},
@@ -469,6 +531,7 @@ export function AddProviderDialog({
projectsDraft,
draftEditorBase,
submitWithConflictRetry,
+ formSessionToken,
],
);
@@ -508,16 +571,17 @@ export function AddProviderDialog({
const form = (
<ProviderForm
+ key={formSessionToken}
appId={appId}
submitLabel={t("common.add")}
modeView={modeView}
- onStackLayoutChange={setStackLayout}
+ onStackLayoutChange={handleStackLayoutChange}
onSubmit={handleSubmit}
onCancel={closeDialog}
onManageAuthAccounts={setAuthSettingsTarget}
- onSubmittingChange={setIsFormSubmitting}
+ onSubmittingChange={handleSubmittingChange}
onSubmitReadyChange={handleSubmitReadyChange}
- onAccountLoginChange={setAccountLogin}
+ onAccountLoginChange={handleAccountLoginChange}
showButtons={false}
claudeLiveBase={
appId === "claude" ? (claudeLiveBase ?? undefined) : undefined
diff --git a/src/components/providers/EditProviderDialog.tsx b/src/components/providers/EditProviderDialog.tsx
index 6929be849..5aef61ed0 100644
--- a/src/components/providers/EditProviderDialog.tsx
+++ b/src/components/providers/EditProviderDialog.tsx
@@ -75,8 +75,6 @@ export function EditProviderDialog({
modeView,
}: EditProviderDialogProps) {
const { t } = useTranslation();
- // 表单用了聚合的简化布局:页头应用名后标「聚合模式」
- const [stackLayout, setStackLayout] = useState(false);
const [authSettingsTarget, setAuthSettingsTarget] =
useState<AuthCenterTarget | null>(null);
@@ -91,6 +89,21 @@ export function EditProviderDialog({
);
const currentFormSessionToken = useRef(formSessionToken);
currentFormSessionToken.current = formSessionToken;
+ // 表单用了聚合的简化布局:页头应用名后标「聚合模式」
+ const [stackLayoutState, setStackLayoutState] = useState({
+ token: formSessionToken,
+ stackLayout: false,
+ });
+ const stackLayout =
+ stackLayoutState.token === formSessionToken && stackLayoutState.stackLayout;
+ const handleStackLayoutChange = useCallback(
+ (next: boolean) => {
+ if (currentFormSessionToken.current === formSessionToken) {
+ setStackLayoutState({ token: formSessionToken, stackLayout: next });
+ }
+ },
+ [formSessionToken],
+ );
// The host stays mounted between edits. A pending save from a closed form
// must neither disable the next editor nor clear its own pending submission.
const [formSubmittingState, setFormSubmittingState] = useState({
@@ -126,16 +139,28 @@ export function EditProviderDialog({
);
// 默认使用传入的 provider.settingsConfig,若当前编辑对象是"当前生效供应商",则尝试读取实时配置替换初始值
- const [liveSettings, setLiveSettings] = useState<Record<
- string,
- unknown
- > | null>(null);
-
- // 使用 ref 标记是否已经加载过,防止重复读取覆盖用户编辑
- const [hasLoadedLive, setHasLoadedLive] = useState(false);
+ // 与 formSessionToken 绑定,避免同窗口切换供应商或应用时残留上一个供应商的 liveSettings / editorView。
+ const [liveState, setLiveState] = useState<{
+ token: number;
+ loaded: boolean;
+ settings: Record<string, unknown> | null;
+ editorView: ProviderEditorView | null;
+ }>({
+ token: formSessionToken,
+ loaded: false,
+ settings: null,
+ editorView: null,
+ });
+ const isCurrentLiveState = liveState.token === formSessionToken;
+ const hasLoadedLive = isCurrentLiveState && liveState.loaded;
+ const liveSettings = isCurrentLiveState ? liveState.settings : null;
+ const editorView = isCurrentLiveState ? liveState.editorView : null;
+ const loadedSessionTokenRef = useRef<number | null>(null);
+ const tRef = useRef(t);
+ tRef.current = t;
+ const isProxyTakeoverRef = useRef(isProxyTakeover);
+ isProxyTakeoverRef.current = isProxyTakeover;
- // Claude:底部 JSON 显示「切到这个供应商之后 settings.json 的样子」,保存时拿它做三方比较。
- const [editorView, setEditorView] = useState<ProviderEditorView | null>(null);
const { submitWithConflictRetry, conflictDialog } =
useLiveEditConflict(formSessionToken);
@@ -154,16 +179,32 @@ export function EditProviderDialog({
useEffect(() => {
let cancelled = false;
+ const commitLiveState = (
+ loaded: boolean,
+ settings: Record<string, unknown> | null,
+ view: ProviderEditorView | null,
+ ) => {
+ if (!cancelled && currentFormSessionToken.current === formSessionToken) {
+ if (loaded) {
+ loadedSessionTokenRef.current = formSessionToken;
+ }
+ setLiveState({
+ token: formSessionToken,
+ loaded,
+ settings,
+ editorView: view,
+ });
+ }
+ };
const load = async () => {
if (!open || !provider) {
- setLiveSettings(null);
- setEditorView(null);
- setHasLoadedLive(false);
+ loadedSessionTokenRef.current = null;
+ commitLiveState(false, null, null);
return;
}
- // 关键修复:只在首次打开时加载一次
- if (hasLoadedLive) {
+ // 关键修复:同一编辑会话只加载一次,避免编辑期间轮询或重渲染覆盖表单与三方基准
+ if (loadedSessionTokenRef.current === formSessionToken) {
return;
}
@@ -178,20 +219,15 @@ export function EditProviderDialog({
provider.id,
appId === "codex" ? provider.meta : undefined,
);
- if (!cancelled) {
- setEditorView(view);
- setLiveSettings(view.settings);
- }
+ commitLiveState(true, view.settings, view);
} catch (error) {
// 读不了配置文件(比如手改坏了):退回显示保存的供应商配置。
- if (!cancelled) {
- setEditorView(null);
- setLiveSettings(null);
- toastEditorViewFailed(t, error);
- }
- } finally {
- if (!cancelled) {
- setHasLoadedLive(true);
+ commitLiveState(true, null, null);
+ if (
+ !cancelled &&
+ currentFormSessionToken.current === formSessionToken
+ ) {
+ toastEditorViewFailed(tRef.current, error);
}
}
return;
@@ -199,11 +235,8 @@ export function EditProviderDialog({
// 代理接管模式:Live 配置已被代理改写,读取 live 会导致编辑界面展示代理地址/占位符等内容
// 因此直接回退到 SSOT(数据库)配置,避免用户困惑与误保存
- if (isProxyTakeover) {
- if (!cancelled) {
- setLiveSettings(null);
- setHasLoadedLive(true);
- }
+ if (isProxyTakeoverRef.current) {
+ commitLiveState(true, null, null);
return;
}
@@ -222,29 +255,20 @@ export function EditProviderDialog({
appId === "codebuddy" ||
appId === "zcode"
) {
- if (!cancelled) {
- setLiveSettings(null);
- setHasLoadedLive(true);
- }
+ commitLiveState(true, null, null);
return;
}
if (appId === "openclaw") {
try {
const live = await openclawApi.getLiveProvider(provider.id);
- if (!cancelled && live && typeof live === "object") {
- setLiveSettings(live);
- } else if (!cancelled) {
- setLiveSettings(null);
- }
+ commitLiveState(
+ true,
+ live && typeof live === "object" ? live : null,
+ null,
+ );
} catch {
- if (!cancelled) {
- setLiveSettings(null);
- }
- } finally {
- if (!cancelled) {
- setHasLoadedLive(true);
- }
+ commitLiveState(true, null, null);
}
return;
}
@@ -256,32 +280,27 @@ export function EditProviderDialog({
const live = (await vscodeApi.getLiveProviderSettings(
appId,
)) as Record<string, unknown>;
- if (!cancelled && live && typeof live === "object") {
- setLiveSettings(live);
- setHasLoadedLive(true);
- }
+ commitLiveState(
+ true,
+ live && typeof live === "object" ? live : null,
+ null,
+ );
} catch {
// 读取实时配置失败则回退到 SSOT(不打断编辑流程)
- if (!cancelled) {
- setLiveSettings(null);
- setHasLoadedLive(true);
- }
+ commitLiveState(true, null, null);
}
} else {
- if (!cancelled) {
- setLiveSettings(null);
- setHasLoadedLive(true);
- }
+ commitLiveState(true, null, null);
}
- } finally {
- // no-op
+ } catch {
+ commitLiveState(true, null, null);
}
};
void load();
return () => {
cancelled = true;
};
- }, [open, provider?.id, appId, hasLoadedLive, isProxyTakeover]); // 只依赖 provider.id,不依赖整个 provider 对象
+ }, [open, provider?.id, appId, formSessionToken]);
const initialSettingsConfig = useMemo(
() => liveSettings ?? asRecord(provider?.settingsConfig) ?? {},
@@ -448,7 +467,7 @@ export function EditProviderDialog({
isProxyTakeover={isProxyTakeover}
inactiveFields={editorView?.inactive}
modeView={modeView}
- onStackLayoutChange={setStackLayout}
+ onStackLayoutChange={handleStackLayoutChange}
/>
)}
{conflictDialog}
diff --git a/src/components/providers/ProviderList.tsx b/src/components/providers/ProviderList.tsx
index 6891309b5..044d7159a 100644
--- a/src/components/providers/ProviderList.tsx
+++ b/src/components/providers/ProviderList.tsx
@@ -23,6 +23,7 @@ import type { OpenClawProviderConfig, Provider } from "@/types";
import { getOpencodeDeclaredModels } from "@/components/providers/forms/helpers/opencodeFormUtils";
import type { AppId } from "@/lib/api";
import { providersApi } from "@/lib/api/providers";
+import { CLAUDE_DESKTOP_STATUS_QUERY_KEY } from "@/lib/query/queries";
import {
extractErrorMessage,
translatePiProviderMutationError,
@@ -280,7 +281,9 @@ export function ProviderList({
if (imported) {
queryClient.invalidateQueries({ queryKey: ["providers", appId] });
if (appId === "claude-desktop") {
- queryClient.invalidateQueries({ queryKey: ["claudeDesktopStatus"] });
+ queryClient.invalidateQueries({
+ queryKey: CLAUDE_DESKTOP_STATUS_QUERY_KEY,
+ });
}
toast.success(t("provider.importCurrentDescription"));
} else {
@@ -637,7 +640,7 @@ export function ProviderList({
const renderCard = (provider: Provider, presentation: CardPresentation) => (
<SortableProviderCard
- key={provider.id}
+ key={`${appId}:${provider.id}`}
provider={provider}
appId={appId}
presentation={presentation}
diff --git a/src/components/providers/forms/hooks/useManagedAuth.ts b/src/components/providers/forms/hooks/useManagedAuth.ts
index e198e074e..2f6116b79 100644
--- a/src/components/providers/forms/hooks/useManagedAuth.ts
+++ b/src/components/providers/forms/hooks/useManagedAuth.ts
@@ -11,6 +11,7 @@ import {
agyAuthStatusQuery,
invalidateAgyLoginCaches,
invalidateAgyQuotaCaches,
+ invalidateManagedAuthQuotaCaches,
subscriptionKeys,
syncAgyLoginOnWindowFocus,
} from "@/lib/query/subscription";
@@ -363,6 +364,9 @@ export function useManagedAuth(
queryKey: subscriptionKeys.quota("grokbuild"),
});
}
+ await invalidateManagedAuthQuotaCaches(queryClient, authProvider, {
+ allAccounts: true,
+ });
},
});
@@ -395,7 +399,7 @@ export function useManagedAuth(
// Account removal can succeed before provider unbinding fails.
if (authProvider === "codex_oauth") await refetchStatus();
},
- onSettled: async () => {
+ onSettled: async (_, __, accountId) => {
if (authProvider === "codex_oauth") {
await queryClient.invalidateQueries({
queryKey: ["providers", "codex"],
@@ -408,6 +412,9 @@ export function useManagedAuth(
queryKey: subscriptionKeys.quota("grokbuild"),
});
}
+ await invalidateManagedAuthQuotaCaches(queryClient, authProvider, {
+ accountId,
+ });
},
});
@@ -434,9 +441,7 @@ export function useManagedAuth(
}
},
onSettled: async () => {
- if (authProvider === "agy_oauth") {
- await invalidateAgyLoginCaches(queryClient);
- }
+ await invalidateManagedAuthQuotaCaches(queryClient, authProvider);
},
});
diff --git a/src/components/providers/mode/useDesktopConfigMessages.ts b/src/components/providers/mode/useDesktopConfigMessages.ts
index e3f081197..6794334f3 100644
--- a/src/components/providers/mode/useDesktopConfigMessages.ts
+++ b/src/components/providers/mode/useDesktopConfigMessages.ts
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { providersApi } from "@/lib/api/providers";
+import { CLAUDE_DESKTOP_STATUS_QUERY_KEY } from "@/lib/query/queries";
/**
* Claude Desktop 配置文件的检查结果(后端 `get_claude_desktop_status`):平台不支持、profile 里
@@ -10,7 +11,7 @@ import { providersApi } from "@/lib/api/providers";
export function useDesktopConfigMessages(enabled: boolean): string[] {
const { t } = useTranslation();
const { data: status } = useQuery({
- queryKey: ["claudeDesktopStatus"],
+ queryKey: CLAUDE_DESKTOP_STATUS_QUERY_KEY,
queryFn: () => providersApi.getClaudeDesktopStatus(),
refetchInterval: 5000,
enabled,
diff --git a/src/components/universal/UniversalProviderFormModal.tsx b/src/components/universal/UniversalProviderFormModal.tsx
index 6f76dd5f4..948dd1f67 100644
--- a/src/components/universal/UniversalProviderFormModal.tsx
+++ b/src/components/universal/UniversalProviderFormModal.tsx
@@ -64,6 +64,9 @@ export function UniversalProviderFormModal({
// Populate before paint so opening the panel never shows empty/stale fields.
useLayoutEffect(() => {
+ setShowApiKey(false);
+ setSyncConfirmOpen(false);
+ setPendingProvider(null);
if (editingProvider) {
// 编辑模式:加载现有数据
setName(editingProvider.name);
diff --git a/src/hooks/useModeActions.ts b/src/hooks/useModeActions.ts
index dba2c92d2..9d60a63a2 100644
--- a/src/hooks/useModeActions.ts
+++ b/src/hooks/useModeActions.ts
@@ -6,6 +6,7 @@ import type { AppId } from "@/lib/api";
import { providersApi } from "@/lib/api/providers";
import { proxyApi } from "@/lib/api/proxy";
import { proxyKeys } from "@/lib/query/proxy";
+import { invalidateClaudeOfficialLoginCaches } from "@/lib/query/subscription";
import type { AppMode } from "@/types/proxy";
import { APP_DISPLAY_NAME } from "@/components/shell/AppGlyph";
@@ -101,6 +102,9 @@ export function useModeActions(app: AppId) {
await providersApi.switch(useProviderId, app);
}
await refresh();
+ if (app === "claude") {
+ await invalidateClaudeOfficialLoginCaches(queryClient);
+ }
toast.success(
[
t("mode.toast.exited", { app: appName, provider: providerName }),
@@ -112,12 +116,15 @@ export function useModeActions(app: AppId) {
);
} catch (error) {
await refresh();
+ if (app === "claude") {
+ await invalidateClaudeOfficialLoginCaches(queryClient);
+ }
throw error;
} finally {
setPending(false);
}
},
- [app, appName, refresh, restartHint, t],
+ [app, appName, queryClient, refresh, restartHint, t],
);
return { enter, exitToDirect, pending, restartHint };
diff --git a/src/lib/query/accountPlans.ts b/src/lib/query/accountPlans.ts
index 938e8262d..deefd8e13 100644
--- a/src/lib/query/accountPlans.ts
+++ b/src/lib/query/accountPlans.ts
@@ -23,12 +23,16 @@ export function useQuotaPlansByKey(
(onChange: () => void) => queryClient.getQueryCache().subscribe(onChange),
[queryClient],
);
- // 快照是字符串,缓存里别的查询变了也不会白白重渲染;null=这次没查成功,沿用上次的
+ // 快照是字符串,缓存里别的查询变了也不会白白重渲染;
+ // false=无缓存或已被重置(清空旧值),null=这次没查成功(沿用上次的)。
const snapshot = useSyncExternalStore(subscribe, () =>
JSON.stringify(
- entries.map(([name, key]): [string, string | null] => {
+ entries.map(([name, key]): [string, string | null | false] => {
const data = queryClient.getQueryData(key);
- if (!data || (data as PlanCarrier).success === false) {
+ if (data === undefined) {
+ return [name, false];
+ }
+ if ((data as PlanCarrier).success === false) {
return [name, null];
}
return [name, pick(data)?.trim() || ""];
@@ -38,10 +42,10 @@ export function useQuotaPlansByKey(
const lastRef = useRef<Record<string, string>>({});
return useMemo(() => {
- const seen = JSON.parse(snapshot) as [string, string | null][];
+ const seen = JSON.parse(snapshot) as [string, string | null | false][];
const plans: Record<string, string> = {};
for (const [name, plan] of seen) {
- const shown = plan ?? lastRef.current[name];
+ const shown = plan === null ? lastRef.current[name] : plan || "";
if (shown) plans[name] = shown;
}
lastRef.current = plans;
diff --git a/src/lib/query/mutations.ts b/src/lib/query/mutations.ts
index 4e766e467..dcbf54c70 100644
--- a/src/lib/query/mutations.ts
+++ b/src/lib/query/mutations.ts
@@ -16,11 +16,13 @@ import { openclawKeys } from "@/hooks/useOpenClaw";
import { invalidateHermesProviderCaches } from "@/hooks/useHermes";
import { invalidateZcodeProviderCaches } from "@/hooks/useZcode";
import { proxyKeys } from "@/lib/query/proxy";
+import { CLAUDE_DESKTOP_STATUS_QUERY_KEY } from "@/lib/query/queries";
import { usageKeys } from "@/lib/query/usage";
import { sessionKeys } from "@/lib/query/sessions";
import { invalidatePiProviderCaches } from "@/lib/query/pi";
import {
invalidateAgyLoginCaches,
+ invalidateClaudeOfficialLoginCaches,
invalidateGrokCliLoginCaches,
} from "@/lib/query/subscription";
import { GROKBUILD_OFFICIAL_PROVIDER_ID } from "@/utils/providerCapabilities";
@@ -189,11 +191,23 @@ export const useAddProviderMutation = (appId: AppId) => {
}),
);
},
- onSettled: async () => {
+ onSettled: async (_data, _error, variables) => {
if (appHas(appId, "piFamily")) {
await invalidatePiProviderCaches(queryClient, appId);
} else if (appId === "agy") {
await invalidateAgyLoginCaches(queryClient);
+ } else if (
+ appId === "claude" &&
+ (variables.category === "official" ||
+ variables.meta?.authBinding?.authProvider === "claude_official")
+ ) {
+ await invalidateClaudeOfficialLoginCaches(queryClient);
+ } else if (
+ appId === "grokbuild" &&
+ (variables.category === "official" ||
+ variables.ensureGrokBuildOfficialSeed)
+ ) {
+ await invalidateGrokCliLoginCaches(queryClient);
}
},
});
@@ -264,7 +278,7 @@ export const useUpdateProviderMutation = (appId: AppId) => {
}),
);
},
- onSettled: async () => {
+ onSettled: async (_data, _error, variables) => {
if (appHas(appId, "piFamily")) {
await invalidatePiProviderCaches(queryClient, appId);
} else if (appId === "agy") {
@@ -278,6 +292,13 @@ export const useUpdateProviderMutation = (appId: AppId) => {
// 保存当前绑号的 Grok 官方卡会把原 CLI 登录收进授权中心再写入绑定的号;
// 写入失败前也可能已经收过:成功失败都重读
await invalidateGrokCliLoginCaches(queryClient);
+ } else if (
+ appId === "claude" &&
+ (variables.provider.category === "official" ||
+ variables.provider.meta?.authBinding?.authProvider ===
+ "claude_official")
+ ) {
+ await invalidateClaudeOfficialLoginCaches(queryClient);
}
},
});
@@ -380,15 +401,13 @@ export const useSwitchProviderMutation = (appId: AppId) => {
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["providers", appId] });
if (appId === "claude") {
- // 切到绑了账号的官方卡时,后端可能把原来的默认登录收成了新账号:授权中心要重读
- await queryClient.invalidateQueries({
- queryKey: ["managed-auth-status", "claude_official"],
- });
+ // 切到绑了账号的官方卡时,后端可能把原来的默认登录收成了新账号:授权中心和套餐缓存要重读
+ await invalidateClaudeOfficialLoginCaches(queryClient);
}
if (appId === "claude-desktop") {
await queryClient.invalidateQueries({ queryKey: proxyKeys.status });
await queryClient.invalidateQueries({
- queryKey: ["claudeDesktopStatus"],
+ queryKey: CLAUDE_DESKTOP_STATUS_QUERY_KEY,
});
}
diff --git a/src/lib/query/queries.ts b/src/lib/query/queries.ts
index a2daa48a0..12d56e590 100644
--- a/src/lib/query/queries.ts
+++ b/src/lib/query/queries.ts
@@ -32,6 +32,8 @@ const sortProviders = (
return Object.fromEntries(sortedEntries);
};
+export const CLAUDE_DESKTOP_STATUS_QUERY_KEY = ["claudeDesktopStatus"] as const;
+
export interface ProvidersQueryData {
providers: Record<string, Provider>;
currentProviderId: string;
diff --git a/src/lib/query/subscription.ts b/src/lib/query/subscription.ts
index 5809e21ce..fe15dd233 100644
--- a/src/lib/query/subscription.ts
+++ b/src/lib/query/subscription.ts
@@ -15,7 +15,7 @@ import type {
ClaudeAccountPlan,
SubscriptionQuota,
} from "@/types/subscription";
-import type { ManagedAuthStatus } from "@/lib/api/auth";
+import type { ManagedAuthProvider, ManagedAuthStatus } from "@/lib/api/auth";
import { resolveManagedAccountId } from "@/lib/authBinding";
import { PROVIDER_TYPES } from "@/config/constants";
import { appHas } from "@/config/appSpecs";
@@ -136,6 +136,113 @@ export async function syncAgyLoginOnWindowFocus(queryClient: QueryClient) {
}
}
+/** Refresh Claude official auth accounts, default plan, and Claude quota caches. */
+export async function invalidateClaudeOfficialLoginCaches(
+ queryClient: QueryClient,
+) {
+ void queryClient
+ .invalidateQueries({
+ queryKey: subscriptionKeys.quota("claude"),
+ })
+ .catch(() => undefined);
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: managedAuthStatusQueryKey("claude_official"),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: ["claude_official", "default_plan"],
+ }),
+ ]);
+}
+
+/**
+ * Refresh shared quota / default-plan caches when an Auth Center account is
+ * removed, logged out, or switched as default.
+ */
+export async function invalidateManagedAuthQuotaCaches(
+ queryClient: QueryClient,
+ authProvider: ManagedAuthProvider,
+ options?: { accountId?: string; allAccounts?: boolean },
+) {
+ const statusKeys: Array<readonly unknown[]> = [];
+ const quotaKeys: Array<readonly unknown[]> = [];
+ const accountId = options?.accountId?.trim();
+ const allAccounts = options?.allAccounts === true;
+
+ if (authProvider === "agy_oauth") {
+ const resetKeys: Array<readonly unknown[]> = [
+ subscriptionKeys.quota("agy"),
+ ];
+ if (allAccounts) {
+ resetKeys.push(["agy_oauth", "quota"], ["agy_oauth", "last_quota"]);
+ } else if (accountId) {
+ resetKeys.push(
+ ["agy_oauth", "quota", accountId],
+ ["agy_oauth", "last_quota", accountId],
+ );
+ }
+ void Promise.all(
+ resetKeys.map((queryKey) =>
+ queryClient.resetQueries({ queryKey }).catch(() => undefined),
+ ),
+ );
+ if (allAccounts) {
+ await queryClient.invalidateQueries({
+ queryKey: agyAuthStatusQuery.queryKey,
+ });
+ } else {
+ await invalidateAgyLoginCaches(queryClient);
+ }
+ return;
+ }
+
+ if (authProvider === "codex_oauth") {
+ quotaKeys.push(["codex_oauth", "quota", "default"]);
+ if (allAccounts) {
+ quotaKeys.push(["codex_oauth", "quota"]);
+ } else if (accountId) {
+ quotaKeys.push(["codex_oauth", "quota", accountId]);
+ }
+ } else if (authProvider === "github_copilot") {
+ quotaKeys.push(["copilot", "quota", "default"]);
+ if (allAccounts) {
+ quotaKeys.push(["copilot", "quota"]);
+ } else if (accountId) {
+ quotaKeys.push(["copilot", "quota", accountId]);
+ }
+ } else if (authProvider === "xai_oauth") {
+ quotaKeys.push(["xai_oauth", "quota", "default"]);
+ if (allAccounts) {
+ quotaKeys.push(["xai_oauth", "quota"]);
+ } else if (accountId) {
+ quotaKeys.push(["xai_oauth", "quota", accountId]);
+ }
+ } else if (authProvider === "claude_official") {
+ statusKeys.push(["claude_official", "default_plan"]);
+ quotaKeys.push(subscriptionKeys.quota("claude"));
+ if (allAccounts) {
+ quotaKeys.push(["claude_official", "quota"]);
+ } else if (accountId) {
+ quotaKeys.push(["claude_official", "quota", accountId]);
+ }
+ } else if (authProvider === "codebuddy_oauth") {
+ if (allAccounts) {
+ quotaKeys.push(["codebuddy_oauth", "quota"]);
+ } else if (accountId) {
+ quotaKeys.push(["codebuddy_oauth", "quota", accountId]);
+ }
+ }
+
+ void Promise.all(
+ quotaKeys.map((queryKey) =>
+ queryClient.resetQueries({ queryKey }).catch(() => undefined),
+ ),
+ );
+ await Promise.all(
+ statusKeys.map((queryKey) => queryClient.invalidateQueries({ queryKey })),
+ );
+}
+
/**
* Grok 的 CLI 登录(~/.grok/auth.json)可能被后端改写之后要重读的缓存:
* 切到/保存绑了 xAI 账号的 Grok 官方卡会把原登录收进授权中心再换号,
@@ -191,6 +298,9 @@ function useQuotaKeepLastGood(
if (lastGoodRef.current.key !== scopeKey) {
lastGoodRef.current = { key: scopeKey, snap: null };
}
+ if (query.data === undefined && query.dataUpdatedAt === 0 && !query.isError) {
+ lastGoodRef.current.snap = null;
+ }
const { data, lastGood } = resolveDisplayUsage(
query.data,
query.dataUpdatedAt,
diff --git a/tests/components/AddProviderDialog.test.tsx b/tests/components/AddProviderDialog.test.tsx
index b6b96b6d4..73abb5bae 100644
--- a/tests/components/AddProviderDialog.test.tsx
+++ b/tests/components/AddProviderDialog.test.tsx
@@ -44,6 +44,8 @@ let mockProjectedBase: Record<string, unknown> | null = null;
// 投影成那份底的草稿(预设或模板)。
let mockProjectedDraft: Record<string, unknown> | undefined;
let submitReadyCallbacks: Array<(isReady: boolean) => void> = [];
+let submittingCallbacks: Array<(submitting: boolean) => void> = [];
+let stackLayoutCallbacks: Array<(stackLayout: boolean) => void> = [];
// 对话框是否把「统一供应商」入口交给表单:只有 `showUniversalTab` 为真时才传。
let universalProps: {
onUniversalPresetSelect?: unknown;
@@ -54,6 +56,8 @@ vi.mock("@/components/providers/forms/ProviderForm", () => ({
ProviderForm: ({
onSubmit,
onSubmitReadyChange,
+ onSubmittingChange,
+ onStackLayoutChange,
onManageAuthAccounts,
onEditorBaseChange,
onUniversalPresetSelect,
@@ -61,6 +65,8 @@ vi.mock("@/components/providers/forms/ProviderForm", () => ({
}: {
onSubmit: (values: ProviderFormValues) => void;
onSubmitReadyChange?: (isReady: boolean) => void;
+ onSubmittingChange?: (submitting: boolean) => void;
+ onStackLayoutChange?: (stackLayout: boolean) => void;
onManageAuthAccounts?: (target: "codex_oauth") => void;
onEditorBaseChange?: (
base: Record<string, unknown> | null,
@@ -81,6 +87,16 @@ vi.mock("@/components/providers/forms/ProviderForm", () => ({
onSubmitReadyChange(mockFormReady);
}
}, [onSubmitReadyChange]);
+ useEffect(() => {
+ if (onSubmittingChange) {
+ submittingCallbacks.push(onSubmittingChange);
+ }
+ }, [onSubmittingChange]);
+ useEffect(() => {
+ if (onStackLayoutChange) {
+ stackLayoutCallbacks.push(onStackLayoutChange);
+ }
+ }, [onStackLayoutChange]);
useEffect(() => {
onEditorBaseChange?.(mockProjectedBase, mockProjectedDraft);
}, [onEditorBaseChange]);
@@ -124,6 +140,8 @@ describe("AddProviderDialog", () => {
mockProjectedBase = null;
mockProjectedDraft = undefined;
submitReadyCallbacks = [];
+ submittingCallbacks = [];
+ stackLayoutCallbacks = [];
mockFormValues = {
name: "Test Provider",
websiteUrl: "https://provider.example.com",
@@ -628,4 +646,86 @@ context_window = 500000
);
expect(universalProps.onManageUniversalProviders).toBeTypeOf("function");
});
+
+ it("resets stackLayout and submitting state when switching appId or reopening", async () => {
+ const props = {
+ onOpenChange: vi.fn(),
+ onSubmit: vi.fn(),
+ };
+ const { rerender } = render(
+ <AddProviderDialog open appId="codex" {...props} />,
+ );
+
+ const addButton = await screen.findByRole("button", { name: "common.add" });
+ await waitFor(() => expect(stackLayoutCallbacks.length).toBeGreaterThan(0));
+
+ act(() => {
+ stackLayoutCallbacks.at(-1)?.(true);
+ submittingCallbacks.at(-1)?.(true);
+ });
+ expect(screen.getByText("Codex(聚合模式)")).toBeInTheDocument();
+ expect(addButton).toBeDisabled();
+
+ rerender(<AddProviderDialog open appId="gemini" {...props} />);
+ await waitFor(() =>
+ expect(screen.queryByText("Codex(聚合模式)")).not.toBeInTheDocument(),
+ );
+ expect(screen.getByRole("button", { name: "common.add" })).toBeEnabled();
+
+ act(() => submittingCallbacks.at(-1)?.(true));
+ expect(screen.getByRole("button", { name: "common.add" })).toBeDisabled();
+
+ rerender(<AddProviderDialog open={false} appId="gemini" {...props} />);
+ rerender(<AddProviderDialog open appId="gemini" {...props} />);
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "common.add" })).toBeEnabled(),
+ );
+ });
+
+ it("does not close a newly opened dialog when a previous app save resolves late", async () => {
+ let resolveSave!: () => void;
+ const handleSubmit = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveSave = resolve;
+ }),
+ );
+ const handleOpenChange = vi.fn();
+
+ const { rerender } = render(
+ <AddProviderDialog
+ open
+ onOpenChange={handleOpenChange}
+ appId="codex"
+ onSubmit={handleSubmit}
+ />,
+ );
+
+ fireEvent.click(await screen.findByRole("button", { name: "common.add" }));
+ await waitFor(() => expect(handleSubmit).toHaveBeenCalledTimes(1));
+
+ rerender(
+ <AddProviderDialog
+ open={false}
+ onOpenChange={handleOpenChange}
+ appId="codex"
+ onSubmit={handleSubmit}
+ />,
+ );
+ rerender(
+ <AddProviderDialog
+ open
+ onOpenChange={handleOpenChange}
+ appId="gemini"
+ onSubmit={handleSubmit}
+ />,
+ );
+ handleOpenChange.mockClear();
+
+ await act(async () => {
+ resolveSave();
+ });
+
+ expect(handleOpenChange).not.toHaveBeenCalled();
+ });
});
diff --git a/tests/components/EditProviderDialog.test.tsx b/tests/components/EditProviderDialog.test.tsx
index 94109d8e4..7b0b881a4 100644
--- a/tests/components/EditProviderDialog.test.tsx
+++ b/tests/components/EditProviderDialog.test.tsx
@@ -770,4 +770,38 @@ describe("EditProviderDialog", () => {
act(() => submitReadyCallbacks.at(-1)?.(true));
await waitFor(() => expect(saveButton).toBeEnabled());
});
+
+ it("does not reload editorView when isProxyTakeover changes mid-edit", async () => {
+ const provider: Provider = {
+ id: "claude-provider",
+ name: "Claude Provider",
+ settingsConfig: {
+ env: { ANTHROPIC_BASE_URL: "https://api.example.com" },
+ },
+ };
+ apiMocks.getEditorView.mockResolvedValue({
+ settings: { env: { ANTHROPIC_BASE_URL: "https://api.example.com" } },
+ inactive: [],
+ });
+
+ const props = {
+ provider,
+ onOpenChange: vi.fn(),
+ onSubmit: vi.fn(),
+ appId: "claude" as const,
+ };
+ const { rerender } = render(
+ <EditProviderDialog open {...props} isProxyTakeover={false} />,
+ );
+
+ await waitFor(() =>
+ expect(apiMocks.getEditorView).toHaveBeenCalledTimes(1),
+ );
+ await screen.findByRole("button", { name: "common.save" });
+
+ rerender(<EditProviderDialog open {...props} isProxyTakeover={true} />);
+ await act(async () => {});
+
+ expect(apiMocks.getEditorView).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/tests/components/UniversalProviderFormModal.test.tsx b/tests/components/UniversalProviderFormModal.test.tsx
new file mode 100644
index 000000000..7f9db78b3
--- /dev/null
+++ b/tests/components/UniversalProviderFormModal.test.tsx
@@ -0,0 +1,103 @@
+import { fireEvent, render } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { UniversalProviderFormModal } from "@/components/universal/UniversalProviderFormModal";
+import type { UniversalProvider } from "@/types";
+
+vi.mock("@/hooks/useDarkMode", () => ({
+ useDarkMode: () => false,
+}));
+
+vi.mock("@/components/JsonEditor", () => ({
+ default: ({ value }: { value: string }) => (
+ <pre data-testid="json-editor">{value}</pre>
+ ),
+}));
+
+vi.mock("@/components/ProviderIcon", () => ({
+ ProviderIcon: () => null,
+}));
+
+vi.mock("@/components/common/FullScreenPanel", () => ({
+ FullScreenPanel: ({
+ isOpen,
+ children,
+ footer,
+ }: {
+ isOpen: boolean;
+ children: React.ReactNode;
+ footer?: React.ReactNode;
+ }) =>
+ isOpen ? (
+ <div>
+ {children}
+ {footer}
+ </div>
+ ) : null,
+}));
+
+const makeProvider = (id: string, apiKey: string): UniversalProvider => ({
+ id,
+ name: `Provider ${id}`,
+ providerType: "newapi",
+ baseUrl: "https://api.example.com",
+ apiKey,
+ apps: { claude: true, codex: true, gemini: true },
+ models: {},
+});
+
+describe("UniversalProviderFormModal state reset", () => {
+ it("resets showApiKey to password mode when switching providers or reopening", () => {
+ const first = makeProvider("p1", "sk-first");
+ const second = makeProvider("p2", "sk-second");
+
+ const { rerender } = render(
+ <UniversalProviderFormModal
+ isOpen
+ onClose={vi.fn()}
+ onSave={vi.fn()}
+ editingProvider={first}
+ />,
+ );
+
+ const apiKeyInput = () =>
+ document.getElementById("apiKey") as HTMLInputElement;
+ expect(apiKeyInput()).toHaveAttribute("type", "password");
+
+ const toggleButton = apiKeyInput().parentElement?.querySelector("button");
+ expect(toggleButton).not.toBeNull();
+ fireEvent.click(toggleButton!);
+ expect(apiKeyInput()).toHaveAttribute("type", "text");
+
+ rerender(
+ <UniversalProviderFormModal
+ isOpen
+ onClose={vi.fn()}
+ onSave={vi.fn()}
+ editingProvider={second}
+ />,
+ );
+ expect(apiKeyInput()).toHaveAttribute("type", "password");
+ expect(apiKeyInput()).toHaveValue("sk-second");
+
+ fireEvent.click(apiKeyInput().parentElement!.querySelector("button")!);
+ expect(apiKeyInput()).toHaveAttribute("type", "text");
+
+ rerender(
+ <UniversalProviderFormModal
+ isOpen={false}
+ onClose={vi.fn()}
+ onSave={vi.fn()}
+ editingProvider={second}
+ />,
+ );
+ rerender(
+ <UniversalProviderFormModal
+ isOpen
+ onClose={vi.fn()}
+ onSave={vi.fn()}
+ editingProvider={second}
+ />,
+ );
+ expect(apiKeyInput()).toHaveAttribute("type", "password");
+ });
+});
diff --git a/tests/hooks/useManagedAuth.test.tsx b/tests/hooks/useManagedAuth.test.tsx
index 882128313..58cbcd550 100644
--- a/tests/hooks/useManagedAuth.test.tsx
+++ b/tests/hooks/useManagedAuth.test.tsx
@@ -16,9 +16,12 @@ const apiMocks = vi.hoisted(() => ({
authCancelLogin: vi.fn(),
authRemoveAccount: vi.fn(),
authLogout: vi.fn(),
+ authSetDefaultAccount: vi.fn(),
}));
const toastMocks = vi.hoisted(() => ({
success: vi.fn(),
+ warning: vi.fn(),
+ error: vi.fn(),
}));
vi.mock("@/lib/api", () => ({
@@ -31,6 +34,8 @@ vi.mock("@/lib/api", () => ({
authLogout: (...args: unknown[]) => apiMocks.authLogout(...args),
authRemoveAccount: (...args: unknown[]) =>
apiMocks.authRemoveAccount(...args),
+ authSetDefaultAccount: (...args: unknown[]) =>
+ apiMocks.authSetDefaultAccount(...args),
},
settingsApi: {
openExternal: vi.fn().mockResolvedValue(undefined),
@@ -44,6 +49,8 @@ vi.mock("@/lib/clipboard", () => ({
vi.mock("sonner", () => ({
toast: {
success: toastMocks.success,
+ warning: toastMocks.warning,
+ error: toastMocks.error,
},
}));
@@ -211,6 +218,7 @@ describe("useManagedAuth", () => {
apiMocks.authCancelLogin.mockReset().mockResolvedValue(true);
apiMocks.authRemoveAccount.mockReset().mockResolvedValue(undefined);
apiMocks.authLogout.mockReset().mockResolvedValue(undefined);
+ apiMocks.authSetDefaultAccount.mockReset().mockResolvedValue(undefined);
});
describe.each(["codex_oauth", "agy_oauth"] as const)(
@@ -1106,4 +1114,119 @@ describe("useManagedAuth", () => {
),
);
});
+
+ it("resets shared default and account quota caches on removeAccount and logout", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ apiMocks.authRemoveAccount.mockResolvedValue(undefined);
+ apiMocks.authLogout.mockResolvedValue(undefined);
+ queryClient.setQueryData(["codex_oauth", "quota", "default"], { ok: 1 });
+ queryClient.setQueryData(["codex_oauth", "quota", "acct-1"], { ok: 1 });
+ queryClient.setQueryData(["copilot", "quota", "default"], { ok: 1 });
+ queryClient.setQueryData(["copilot", "quota", "acct-gh"], { ok: 1 });
+
+ const codex = renderHook(() => useManagedAuth("codex_oauth"), {
+ wrapper: createWrapper(queryClient),
+ });
+ await waitFor(() =>
+ expect(codex.result.current.isStatusSuccess).toBe(true),
+ );
+ act(() => codex.result.current.removeAccount("acct-1"));
+ await waitFor(() =>
+ expect(
+ queryClient.getQueryData(["codex_oauth", "quota", "acct-1"]),
+ ).toBeUndefined(),
+ );
+ expect(
+ queryClient.getQueryData(["codex_oauth", "quota", "default"]),
+ ).toBeUndefined();
+
+ const copilot = renderHook(() => useManagedAuth("github_copilot"), {
+ wrapper: createWrapper(queryClient),
+ });
+ await waitFor(() =>
+ expect(copilot.result.current.isStatusSuccess).toBe(true),
+ );
+ act(() => copilot.result.current.logout());
+ await waitFor(() =>
+ expect(
+ queryClient.getQueryData(["copilot", "quota", "acct-gh"]),
+ ).toBeUndefined(),
+ );
+ expect(
+ queryClient.getQueryData(["copilot", "quota", "default"]),
+ ).toBeUndefined();
+ });
+
+ it("resets default quota and invalidates plan caches on setDefaultAccount across providers", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ apiMocks.authSetDefaultAccount.mockResolvedValue(undefined);
+ queryClient.setQueryData(["claude_official", "default_plan"], {
+ plan: "max",
+ });
+ queryClient.setQueryData(["subscription", "quota", "claude"], { ok: 1 });
+ queryClient.setQueryData(["xai_oauth", "quota", "default"], { ok: 1 });
+ queryClient.setQueryData(["subscription", "quota", "agy"], { ok: 1 });
+ queryClient.setQueryData(["agy_oauth", "last_quota", "acct-1"], { ok: 1 });
+
+ const claude = renderHook(() => useManagedAuth("claude_official"), {
+ wrapper: createWrapper(queryClient),
+ });
+ await waitFor(() =>
+ expect(claude.result.current.isStatusSuccess).toBe(true),
+ );
+ act(() => claude.result.current.setDefaultAccount("acct-1"));
+ await waitFor(() => {
+ expect(
+ queryClient.getQueryState(["claude_official", "default_plan"])
+ ?.isInvalidated,
+ ).toBe(true);
+ expect(
+ queryClient.getQueryData(["subscription", "quota", "claude"]),
+ ).toBeUndefined();
+ });
+
+ const xai = renderHook(() => useManagedAuth("xai_oauth"), {
+ wrapper: createWrapper(queryClient),
+ });
+ await waitFor(() => expect(xai.result.current.isStatusSuccess).toBe(true));
+ act(() => xai.result.current.setDefaultAccount("acct-1"));
+ await waitFor(() =>
+ expect(
+ queryClient.getQueryData(["xai_oauth", "quota", "default"]),
+ ).toBeUndefined(),
+ );
+
+ const agy = renderHook(() => useManagedAuth("agy_oauth"), {
+ wrapper: createWrapper(queryClient),
+ });
+ await waitFor(() => expect(agy.result.current.isStatusSuccess).toBe(true));
+ const agyStatusCallsBefore = apiMocks.authGetStatus.mock.calls.filter(
+ ([provider]) => provider === "agy_oauth",
+ ).length;
+ act(() => agy.result.current.setDefaultAccount("acct-1"));
+ await waitFor(() => {
+ expect(
+ apiMocks.authGetStatus.mock.calls.filter(
+ ([provider]) => provider === "agy_oauth",
+ ).length,
+ ).toBeGreaterThan(agyStatusCallsBefore);
+ expect(
+ queryClient.getQueryData(["subscription", "quota", "agy"]),
+ ).toBeUndefined();
+ expect(
+ queryClient.getQueryState(["agy_oauth", "last_quota", "acct-1"])
+ ?.isInvalidated,
+ ).toBe(true);
+ });
+ });
});
diff --git a/tests/hooks/useModeActions.test.tsx b/tests/hooks/useModeActions.test.tsx
new file mode 100644
index 000000000..87e8dbb7d
--- /dev/null
+++ b/tests/hooks/useModeActions.test.tsx
@@ -0,0 +1,138 @@
+import type { ReactNode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { http, HttpResponse } from "msw";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useModeActions } from "@/hooks/useModeActions";
+import { useSubscriptionQuota } from "@/lib/query/subscription";
+import { server } from "../msw/server";
+import { createTestQueryClient } from "../utils/testQueryClient";
+
+vi.mock("sonner", () => ({
+ toast: {
+ success: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ error: vi.fn(),
+ },
+}));
+
+describe("useModeActions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("invalidates Claude official login caches on exitToDirect without blocking on quota refetch", async () => {
+ const takeoverCalls: unknown[] = [];
+ const switchCalls: unknown[] = [];
+ let quotaCalls = 0;
+
+ server.use(
+ http.post("http://tauri.local/get_settings", () =>
+ HttpResponse.json({ officialQuotaManualOnly: false }),
+ ),
+ http.post("http://tauri.local/get_subscription_quota", () => {
+ quotaCalls += 1;
+ if (quotaCalls === 1) {
+ return HttpResponse.json({
+ tool: "claude",
+ credentialStatus: "valid",
+ credentialMessage: null,
+ success: true,
+ tiers: [],
+ extraUsage: null,
+ error: null,
+ queriedAt: 1,
+ });
+ }
+ return new Promise(() => {});
+ }),
+ http.post(
+ "http://tauri.local/set_proxy_takeover_for_app",
+ async ({ request }) => {
+ takeoverCalls.push(await request.json());
+ return HttpResponse.json(null);
+ },
+ ),
+ http.post("http://tauri.local/switch_provider", async ({ request }) => {
+ switchCalls.push(await request.json());
+ return HttpResponse.json({ warnings: [] });
+ }),
+ );
+
+ const client = createTestQueryClient();
+ const statusKey = ["managed-auth-status", "claude_official"];
+ const defaultPlanKey = ["claude_official", "default_plan"];
+ const quotaKey = ["subscription", "quota", "claude"];
+ client.setQueryData(statusKey, { accounts: [] });
+ client.setQueryData(defaultPlanKey, { subscriptionType: "pro" });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(
+ () => ({
+ quota: useSubscriptionQuota("claude", true),
+ actions: useModeActions("claude"),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.quota.isSuccess).toBe(true));
+
+ await act(async () => {
+ await result.current.actions.exitToDirect({
+ directProviderId: "p1",
+ useProviderId: "p2",
+ providerName: "Provider 2",
+ });
+ });
+
+ expect(takeoverCalls).toEqual([
+ { appType: "claude", enabled: false, stack: false, route: null },
+ ]);
+ expect(switchCalls).toEqual([{ id: "p2", app: "claude" }]);
+ expect(quotaCalls).toBe(2);
+ expect(client.getQueryState(statusKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(defaultPlanKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(quotaKey)?.isInvalidated).toBe(true);
+ client.clear();
+ });
+
+ it("does not invalidate Claude official caches on exitToDirect for other apps", async () => {
+ server.use(
+ http.post("http://tauri.local/set_proxy_takeover_for_app", () =>
+ HttpResponse.json(null),
+ ),
+ http.post("http://tauri.local/switch_provider", () =>
+ HttpResponse.json({ warnings: [] }),
+ ),
+ );
+
+ const client = createTestQueryClient();
+ const statusKey = ["managed-auth-status", "claude_official"];
+ const defaultPlanKey = ["claude_official", "default_plan"];
+ const quotaKey = ["subscription", "quota", "claude"];
+ client.setQueryData(statusKey, { accounts: [] });
+ client.setQueryData(defaultPlanKey, { subscriptionType: "pro" });
+ client.setQueryData(quotaKey, { success: true, tiers: [] });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(() => useModeActions("codex"), { wrapper });
+
+ await act(async () => {
+ await result.current.exitToDirect({
+ directProviderId: "p1",
+ useProviderId: "p2",
+ providerName: "Provider 2",
+ });
+ });
+
+ expect(client.getQueryState(statusKey)?.isInvalidated).toBe(false);
+ expect(client.getQueryState(defaultPlanKey)?.isInvalidated).toBe(false);
+ expect(client.getQueryState(quotaKey)?.isInvalidated).toBe(false);
+ client.clear();
+ });
+});
diff --git a/tests/hooks/useSwitchProviderResult.test.tsx b/tests/hooks/useSwitchProviderResult.test.tsx
index e8c191567..c1e12694a 100644
--- a/tests/hooks/useSwitchProviderResult.test.tsx
+++ b/tests/hooks/useSwitchProviderResult.test.tsx
@@ -1,9 +1,10 @@
import type { ReactNode } from "react";
-import { act, renderHook } from "@testing-library/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import { describe, expect, it } from "vitest";
import { useSwitchProviderMutation } from "@/lib/query/mutations";
+import { useSubscriptionQuota } from "@/lib/query/subscription";
import { server } from "../msw/server";
import { createTestQueryClient } from "../utils/testQueryClient";
@@ -101,4 +102,68 @@ describe("provider switch result transport", () => {
client.clear();
},
);
+
+ it("does not block Claude provider switch while an active quota query is hanging", async () => {
+ let quotaCalls = 0;
+ let trayCalls = 0;
+ server.use(
+ http.post("http://tauri.local/get_settings", () =>
+ HttpResponse.json({ officialQuotaManualOnly: false }),
+ ),
+ http.post("http://tauri.local/get_subscription_quota", () => {
+ quotaCalls += 1;
+ if (quotaCalls === 1) {
+ return HttpResponse.json({
+ tool: "claude",
+ credentialStatus: "valid",
+ credentialMessage: null,
+ success: true,
+ tiers: [],
+ extraUsage: null,
+ error: null,
+ queriedAt: 1,
+ });
+ }
+ return new Promise(() => {});
+ }),
+ http.post("http://tauri.local/switch_provider", () =>
+ HttpResponse.json({ warnings: [] }),
+ ),
+ http.post("http://tauri.local/update_tray_menu", () => {
+ trayCalls += 1;
+ return HttpResponse.json(true);
+ }),
+ );
+
+ const client = createTestQueryClient();
+ const statusKey = ["managed-auth-status", "claude_official"];
+ const defaultPlanKey = ["claude_official", "default_plan"];
+ const quotaKey = ["subscription", "quota", "claude"];
+ client.setQueryData(statusKey, { accounts: [] });
+ client.setQueryData(defaultPlanKey, { subscriptionType: "pro" });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ const { result } = renderHook(
+ () => ({
+ quota: useSubscriptionQuota("claude", true),
+ switchMutation: useSwitchProviderMutation("claude"),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.quota.isSuccess).toBe(true));
+
+ await act(async () => {
+ await result.current.switchMutation.mutateAsync("provider-b");
+ });
+
+ expect(trayCalls).toBe(1);
+ expect(quotaCalls).toBe(2);
+ expect(client.getQueryState(statusKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(defaultPlanKey)?.isInvalidated).toBe(true);
+ expect(client.getQueryState(quotaKey)?.isInvalidated).toBe(true);
+ client.clear();
+ });
});
diff --git a/tests/lib/accountPlans.test.tsx b/tests/lib/accountPlans.test.tsx
index 8018a320c..e72f448b2 100644
--- a/tests/lib/accountPlans.test.tsx
+++ b/tests/lib/accountPlans.test.tsx
@@ -2,7 +2,7 @@ import type { ReactNode } from "react";
import { act, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
-import { useAccountQuotaPlans } from "@/lib/query/accountPlans";
+import { useAccountQuotaPlans, useQuotaPlan } from "@/lib/query/accountPlans";
function setup() {
const client = new QueryClient();
@@ -72,4 +72,31 @@ describe("useAccountQuotaPlans", () => {
);
expect(result.current).toEqual({ a: "Max" });
});
+
+ it("clears the displayed plan when the quota query is reset while keeping last plan on failure", () => {
+ const { client, wrapper } = setup();
+ client.setQueryData(["codex_oauth", "quota", "default"], {
+ success: true,
+ planName: "Pro",
+ });
+ const { result } = renderHook(
+ () => useQuotaPlan(["codex_oauth", "quota", "default"]),
+ { wrapper },
+ );
+ expect(result.current).toBe("Pro");
+
+ act(() => {
+ client.setQueryData(["codex_oauth", "quota", "default"], {
+ success: false,
+ });
+ });
+ expect(result.current).toBe("Pro");
+
+ act(() => {
+ void client.resetQueries({
+ queryKey: ["codex_oauth", "quota", "default"],
+ });
+ });
+ expect(result.current).toBeNull();
+ });
});
diff --git a/tests/lib/quotaManualOnly.test.tsx b/tests/lib/quotaManualOnly.test.tsx
index a43f40cb0..312d87b66 100644
--- a/tests/lib/quotaManualOnly.test.tsx
+++ b/tests/lib/quotaManualOnly.test.tsx
@@ -12,9 +12,12 @@ import { createInstance } from "i18next";
import { I18nextProvider, initReactI18next } from "react-i18next";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
+ invalidateManagedAuthQuotaCaches,
useClaudeAccountQuota,
useCodebuddyAccountQuota,
+ useCodexOauthQuota,
} from "@/lib/query/subscription";
+import { useQuotaPlan } from "@/lib/query/accountPlans";
import { useWorkBuddyAccountQuota } from "@/components/providers/workbuddyQuota";
import { SubscriptionQuotaView } from "@/components/SubscriptionQuotaFooter";
import { AutoQuotaToggle } from "@/components/settings/auth/AutoQuotaToggle";
@@ -23,13 +26,17 @@ import zh from "@/i18n/locales/zh.json";
const mocks = vi.hoisted(() => ({
getClaudeAccountQuota: vi.fn(),
+ getCodexOauthQuota: vi.fn(),
workbuddyAccountQuota: vi.fn(),
codebuddyAccountQuota: vi.fn(),
getSettings: vi.fn(),
saveSettings: vi.fn(),
}));
vi.mock("@/lib/api/subscription", () => ({
- subscriptionApi: { getClaudeAccountQuota: mocks.getClaudeAccountQuota },
+ subscriptionApi: {
+ getClaudeAccountQuota: mocks.getClaudeAccountQuota,
+ getCodexOauthQuota: mocks.getCodexOauthQuota,
+ },
}));
vi.mock("@/lib/api/settings", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/api/settings")>()),
@@ -78,6 +85,7 @@ const newClient = () =>
describe("manual-only official quota (#8990)", () => {
beforeEach(() => {
mocks.getClaudeAccountQuota.mockReset().mockResolvedValue(quota);
+ mocks.getCodexOauthQuota.mockReset().mockResolvedValue(quota);
mocks.workbuddyAccountQuota.mockReset().mockResolvedValue({
snapshot: null,
current: false,
@@ -298,4 +306,56 @@ describe("manual-only official quota (#8990)", () => {
}),
);
});
+
+ 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
+ .mockResolvedValueOnce({
+ ...quota,
+ tool: "codex",
+ planName: "Plus",
+ })
+ .mockResolvedValueOnce({
+ ...quota,
+ tool: "codex",
+ success: false,
+ error: "API error (HTTP 500)",
+ planName: null,
+ });
+
+ const client = newClient();
+ const { result } = renderHook(
+ () => ({
+ quota: useCodexOauthQuota(undefined),
+ plan: useQuotaPlan(["codex_oauth", "quota", "default"]),
+ }),
+ { wrapper: wrapperFor(client) },
+ );
+
+ await waitFor(() => expect(result.current.quota.manualIdle).toBe(true));
+ expect(mocks.getCodexOauthQuota).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await result.current.quota.refetch();
+ });
+ await waitFor(() => expect(result.current.quota.data?.success).toBe(true));
+ expect(result.current.plan).toBe("Plus");
+ expect(result.current.quota.manualIdle).toBe(false);
+
+ await act(async () => {
+ await invalidateManagedAuthQuotaCaches(client, "codex_oauth");
+ });
+
+ expect(result.current.quota.data).toBeUndefined();
+ expect(result.current.quota.manualIdle).toBe(true);
+ expect(result.current.plan).toBeNull();
+ expect(mocks.getCodexOauthQuota).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await result.current.quota.refetch();
+ });
+ await waitFor(() => expect(result.current.quota.data?.success).toBe(false));
+ expect(result.current.quota.data?.error).toBe("API error (HTTP 500)");
+ expect(result.current.plan).toBeNull();
+ });
});