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(auth): drop residual Antigravity avatar field and retry avatar loads (#9984)

pablof5cf21121731
diff --git a/src-tauri/src/commands/auth.rs b/src-tauri/src/commands/auth.rs
index f5e13b01a..f90780036 100644
--- a/src-tauri/src/commands/auth.rs
+++ b/src-tauri/src/commands/auth.rs
@@ -148,7 +148,7 @@ pub(crate) fn map_agy_account(
ManagedAuthAccount {
is_default: current_account_id == Some(account.id.as_str()),
login: account.label(),
- avatar_url: account.picture,
+ avatar_url: None,
authenticated_at: account.authenticated_at,
github_domain: "google.com".to_string(),
reauth_required: false,
diff --git a/src-tauri/src/services/agy_account/identity.rs b/src-tauri/src/services/agy_account/identity.rs
index abfe27a8e..268ec4e6a 100644
--- a/src-tauri/src/services/agy_account/identity.rs
+++ b/src-tauri/src/services/agy_account/identity.rs
@@ -10,7 +10,6 @@ pub struct IdentityClaims {
pub sub: Option<String>,
pub email: Option<String>,
pub name: Option<String>,
- pub picture: Option<String>,
}
pub fn identity(id_token: &str) -> Option<IdentityClaims> {
@@ -41,7 +40,11 @@ mod tests {
#[test]
fn identity_requires_a_subject() {
- let token = fake_id_token(json!({"sub": "123", "email": "[email protected]"}));
+ let token = fake_id_token(json!({
+ "sub": "123",
+ "email": "[email protected]",
+ "picture": "https://lh3.googleusercontent.com/a/example",
+ }));
let claims = identity(&token).unwrap();
assert_eq!(claims.sub.as_deref(), Some("123"));
assert_eq!(claims.email.as_deref(), Some("[email protected]"));
diff --git a/src-tauri/src/services/agy_account/mod.rs b/src-tauri/src/services/agy_account/mod.rs
index 7ea1864d8..b2304fa4f 100644
--- a/src-tauri/src/services/agy_account/mod.rs
+++ b/src-tauri/src/services/agy_account/mod.rs
@@ -80,8 +80,6 @@ struct AccountData {
email: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- picture: Option<String>,
/// agy 钥匙串里那份 JSON 原样保存(以后 agy 新增的字段也跟着走)
credential: Value,
authenticated_at: i64,
@@ -118,7 +116,6 @@ pub struct AgyAccount {
pub id: String,
pub email: Option<String>,
pub name: Option<String>,
- pub picture: Option<String>,
pub authenticated_at: i64,
pub requires_reauth: bool,
}
@@ -142,7 +139,6 @@ impl From<&AccountData> for AgyAccount {
id: data.sub.clone(),
email: data.email.clone(),
name: data.name.clone(),
- picture: data.picture.clone(),
authenticated_at: data.authenticated_at,
requires_reauth: data.requires_reauth,
}
@@ -1150,10 +1146,9 @@ fn absorb(
existing.requires_reauth = false;
changed = true;
}
- // 续期后的 id_token 不带名字和头像,有新值才更新
+ // 续期后的 id_token 不带名字,有新值才更新
changed |= fill(&mut existing.email, claims.email);
changed |= fill(&mut existing.name, claims.name);
- changed |= fill(&mut existing.picture, claims.picture);
return (Some(sub), changed);
}
let dismissed = store.dismissed.contains(&sub);
@@ -1233,7 +1228,6 @@ fn upsert(
sub: sub.clone(),
email: None,
name: None,
- picture: None,
credential: Value::Null,
authenticated_at: now,
requires_reauth: false,
@@ -1244,7 +1238,6 @@ fn upsert(
entry.authenticated_at = now;
fill(&mut entry.email, claims.email.clone());
fill(&mut entry.name, claims.name.clone());
- fill(&mut entry.picture, claims.picture.clone());
AgyAccount::from(&*entry)
}
@@ -1342,7 +1335,6 @@ fn match_stored(store: &StoreFile, credential: &Value) -> Option<identity::Ident
sub: Some(account.sub.clone()),
email: email.or_else(|| account.email.clone()),
name: None,
- picture: None,
});
}
let email = email?;
@@ -1354,7 +1346,6 @@ fn match_stored(store: &StoreFile, credential: &Value) -> Option<identity::Ident
sub: Some(sub.clone()),
email: Some(stored_email.clone()),
name: None,
- picture: None,
})
}
@@ -1382,7 +1373,6 @@ fn identify(store: &StoreFile, credential: &Value) -> Option<identity::IdentityC
sub: Some(identity::email_account_id(&email)),
email: Some(email),
name: None,
- picture: None,
}),
}
}
diff --git a/src-tauri/src/services/agy_account/tests.rs b/src-tauri/src/services/agy_account/tests.rs
index 97186f03b..2eb2a4abf 100644
--- a/src-tauri/src/services/agy_account/tests.rs
+++ b/src-tauri/src/services/agy_account/tests.rs
@@ -1053,6 +1053,48 @@ async fn last_quota_reads_stored_snapshot_without_touching_keychain() {
assert_eq!(*login.writes.lock().unwrap(), 0);
}
+#[tokio::test]
+async fn legacy_account_file_ignores_removed_picture_field() {
+ let dir = tempfile::tempdir().unwrap();
+ let store_path = dir.path().join(STORE_FILENAME);
+ let legacy = json!({
+ "version": 1,
+ "accounts": {
+ "alice": {
+ "sub": "alice",
+ "email": "[email protected]",
+ "picture": "https://lh3.googleusercontent.com/a/legacy",
+ "credential": credential("alice", "a1"),
+ "authenticated_at": 100
+ },
+ "bob": {
+ "sub": "bob",
+ "email": "[email protected]",
+ "picture": null,
+ "credential": credential("bob", "b1"),
+ "authenticated_at": 200
+ }
+ }
+ });
+ std::fs::write(&store_path, serde_json::to_vec_pretty(&legacy).unwrap()).unwrap();
+
+ let login = Arc::new(MemoryLogin::default());
+ let manager = AgyAccountManager::with_login_store(dir.path().to_path_buf(), login);
+ let accounts = manager.list().await;
+ assert_eq!(accounts.len(), 2);
+ assert_eq!(accounts[0].id, "alice");
+ assert_eq!(accounts[0].email.as_deref(), Some("[email protected]"));
+ assert_eq!(accounts[1].id, "bob");
+
+ // 再次写盘后旧的 picture 键不再保留
+ manager
+ .record_quota("alice", &SubscriptionQuota::not_found("agy"))
+ .await;
+ let saved: Value = serde_json::from_slice(&std::fs::read(&store_path).unwrap()).unwrap();
+ assert!(saved["accounts"]["alice"].get("picture").is_none());
+ assert!(saved["accounts"]["bob"].get("picture").is_none());
+}
+
#[cfg(any(target_os = "macos", windows, target_os = "linux"))]
mod running_guard_and_scope {
use super::*;
@@ -1378,7 +1420,6 @@ mod running_guard_and_scope {
sub: Some(identity::email_account_id("[email protected]")),
email: Some("[email protected]".into()),
name: None,
- picture: None,
};
upsert(&mut store, dup_email_cred, &dup_claims);
drop(store);
diff --git a/src/components/providers/forms/AgyOAuthSection.tsx b/src/components/providers/forms/AgyOAuthSection.tsx
index 6c5456cc8..e773d5918 100644
--- a/src/components/providers/forms/AgyOAuthSection.tsx
+++ b/src/components/providers/forms/AgyOAuthSection.tsx
@@ -236,7 +236,6 @@ export const AgyOAuthSection: React.FC<AgyOAuthSectionProps> = ({
return {
id: account.id,
login: account.login,
- avatarUrl: account.avatar_url,
details: account.requires_reauth
? [
t("authCenter.agy.reauthNote", {
diff --git a/src/components/providers/forms/CopilotAuthSection.tsx b/src/components/providers/forms/CopilotAuthSection.tsx
index 50e1982f6..fdbbdb4fd 100644
--- a/src/components/providers/forms/CopilotAuthSection.tsx
+++ b/src/components/providers/forms/CopilotAuthSection.tsx
@@ -29,6 +29,7 @@ import { useManagedAccountUsers } from "./hooks/useManagedAccountUsers";
import type { GitHubAccount } from "@/lib/api";
import {
ManagedAccountsGroup,
+ useAvatarImage,
type GroupAccountRow,
} from "@/components/settings/auth/ManagedAccountsGroup";
import { CopilotAccountQuota } from "@/components/settings/auth/AccountQuota";
@@ -487,20 +488,21 @@ export const CopilotAuthSection: React.FC<CopilotAuthSectionProps> = ({
const CopilotAccountAvatar: React.FC<{ account: GitHubAccount }> = ({
account,
}) => {
- const [failed, setFailed] = React.useState(false);
+ const { src, imageKey, onError } = useAvatarImage(account.avatar_url);
- if (!account.avatar_url || failed) {
+ if (!src) {
return <User className="h-5 w-5 text-fg-2" />;
}
return (
<img
- src={account.avatar_url}
+ key={imageKey}
+ src={src}
alt={account.login}
className="h-5 w-5 rounded-full"
loading="lazy"
referrerPolicy="no-referrer"
- onError={() => setFailed(true)}
+ onError={onError}
/>
);
};
diff --git a/src/components/settings/auth/ManagedAccountsGroup.tsx b/src/components/settings/auth/ManagedAccountsGroup.tsx
index 45f281934..b6d963c5b 100644
--- a/src/components/settings/auth/ManagedAccountsGroup.tsx
+++ b/src/components/settings/auth/ManagedAccountsGroup.tsx
@@ -605,6 +605,64 @@ export function ManagedAccountsGroup({
);
}
+const AVATAR_RETRY_DELAYS_MS = [1000, 3000] as const;
+
+type AvatarLoadState = {
+ url: string;
+ attempt: number;
+ status: "loading" | "waiting" | "failed";
+};
+
+/**
+ * 头像加载状态:URL 变化时重置失败标记;加载失败后先回退到占位内容,
+ * 静默退避重试最多 2 次,耗尽后停留在占位内容。
+ */
+export function useAvatarImage(avatarUrl?: string | null) {
+ const url = avatarUrl?.trim() || null;
+ const [state, setState] = useState<AvatarLoadState | null>(null);
+
+ // URL 变化时立刻丢弃旧地址状态,避免 A -> B -> A 残留旧的失败/重试记录
+ if (state && state.url !== url) {
+ setState(null);
+ }
+ const active = url && state?.url === url ? state : null;
+ const attempt = active?.attempt ?? 0;
+ const status = active?.status ?? "loading";
+
+ useEffect(() => {
+ if (!url || status !== "waiting") return;
+ const delay = AVATAR_RETRY_DELAYS_MS[attempt];
+ if (delay === undefined) return;
+ const timer = window.setTimeout(() => {
+ setState((prev) =>
+ prev?.url === url &&
+ prev.status === "waiting" &&
+ prev.attempt === attempt
+ ? { url, attempt: attempt + 1, status: "loading" }
+ : prev,
+ );
+ }, delay);
+ return () => window.clearTimeout(timer);
+ }, [attempt, status, url]);
+
+ const onError = () => {
+ if (!url) return;
+ setState((prev) => {
+ const currentAttempt = prev?.url === url ? prev.attempt : 0;
+ if (currentAttempt < AVATAR_RETRY_DELAYS_MS.length) {
+ return { url, attempt: currentAttempt, status: "waiting" };
+ }
+ return { url, attempt: currentAttempt, status: "failed" };
+ });
+ };
+
+ return {
+ src: status === "loading" ? url : null,
+ imageKey: `${url ?? ""}#${attempt}`,
+ onError,
+ };
+}
+
function AccountAvatar({
login,
avatarUrl,
@@ -612,20 +670,21 @@ function AccountAvatar({
login: string;
avatarUrl?: string | null;
}) {
- const [failed, setFailed] = useState(false);
+ const { src, imageKey, onError } = useAvatarImage(avatarUrl);
return (
<span
aria-hidden="true"
className="flex h-7 w-7 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-subtle text-caption font-semibold text-fg-2"
>
- {avatarUrl && !failed ? (
+ {src ? (
<img
- src={avatarUrl}
+ key={imageKey}
+ src={src}
alt=""
className="h-full w-full object-cover"
loading="lazy"
referrerPolicy="no-referrer"
- onError={() => setFailed(true)}
+ onError={onError}
/>
) : (
login.charAt(0).toUpperCase()
diff --git a/tests/components/AuthCenterGroups.test.tsx b/tests/components/AuthCenterGroups.test.tsx
index d25a58470..4ea64711e 100644
--- a/tests/components/AuthCenterGroups.test.tsx
+++ b/tests/components/AuthCenterGroups.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen, within } from "@testing-library/react";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { TFunction } from "i18next";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -265,6 +265,183 @@ describe("Auth Center account groups", () => {
expect(xaiTip).toHaveAttribute("data-side", "bottom");
expect(xaiTip).toHaveTextContent(/Grok Build/);
});
+
+ it("retries AccountAvatar up to twice with backoff and resets when avatarUrl changes", () => {
+ vi.useFakeTimers();
+ try {
+ const renderWithAvatar = (avatarUrl: string | null) => ({
+ ...baseAuth(),
+ hasAnyAccount: true,
+ accounts: [
+ account("octocat", "octocat", {
+ avatar_url: avatarUrl,
+ }),
+ ],
+ defaultAccountId: "octocat",
+ });
+
+ // 空白字符串视为无头像,直接回退首字母
+ mocks.useCopilotAuth.mockReturnValue(renderWithAvatar(" "));
+ const { container, rerender, unmount } = render(<CopilotAuthSection />);
+ const avatarImg = () => container.querySelector(".auth-account-row img");
+ expect(avatarImg()).toBeNull();
+ expect(screen.getByText("O")).toBeInTheDocument();
+
+ mocks.useCopilotAuth.mockReturnValue(
+ renderWithAvatar("https://avatars.example.com/u/1?v=1"),
+ );
+ rerender(<CopilotAuthSection />);
+
+ const firstImg = avatarImg();
+ expect(firstImg?.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/1?v=1",
+ );
+
+ // 第 1 次加载失败:先回退首字母,1000ms 后静默发起第 1 次重试
+ fireEvent.error(firstImg!);
+ expect(avatarImg()).toBeNull();
+ expect(screen.getByText("O")).toBeInTheDocument();
+
+ act(() => vi.advanceTimersByTime(999));
+ expect(avatarImg()).toBeNull();
+ act(() => vi.advanceTimersByTime(1));
+ const secondImg = avatarImg();
+ expect(secondImg).not.toBeNull();
+ expect(secondImg).not.toBe(firstImg);
+
+ // 第 2 次失败:3000ms 后发起第 2 次重试
+ fireEvent.error(secondImg!);
+ expect(avatarImg()).toBeNull();
+ act(() => vi.advanceTimersByTime(2999));
+ expect(avatarImg()).toBeNull();
+ act(() => vi.advanceTimersByTime(1));
+ const thirdImg = avatarImg();
+ expect(thirdImg).not.toBeNull();
+ expect(thirdImg).not.toBe(secondImg);
+
+ // 第 3 次失败(2 次重试已耗尽):保持首字母回退,不再继续安排定时器
+ fireEvent.error(thirdImg!);
+ expect(avatarImg()).toBeNull();
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(avatarImg()).toBeNull();
+
+ // avatarUrl 变更后立刻重置失败状态并加载新地址
+ mocks.useCopilotAuth.mockReturnValue(
+ renderWithAvatar("https://avatars.example.com/u/1?v=2"),
+ );
+ rerender(<CopilotAuthSection />);
+ expect(avatarImg()?.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/1?v=2",
+ );
+
+ // 退避等待中途切换回旧地址(A -> B(waiting) -> A):立刻取消旧定时器并重新尝试 A
+ fireEvent.error(avatarImg()!);
+ expect(avatarImg()).toBeNull();
+ mocks.useCopilotAuth.mockReturnValue(
+ renderWithAvatar("https://avatars.example.com/u/1?v=1"),
+ );
+ rerender(<CopilotAuthSection />);
+ const reloaded = avatarImg();
+ expect(reloaded?.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/1?v=1",
+ );
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(5000));
+ expect(avatarImg()).toBe(reloaded);
+
+ // 退避等待期间卸载不残留定时器
+ fireEvent.error(reloaded!);
+ expect(vi.getTimerCount()).toBe(1);
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ act(() => vi.advanceTimersByTime(10_000));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("retries CopilotAccountAvatar with backoff and resets on avatarUrl change", () => {
+ vi.useFakeTimers();
+ try {
+ const renderSelect = (avatarUrl: string | null) => ({
+ ...baseAuth(),
+ hasAnyAccount: true,
+ accounts: [
+ account("octocat", "octocat", {
+ avatar_url: avatarUrl,
+ }),
+ ],
+ defaultAccountId: "octocat",
+ });
+
+ mocks.useCopilotAuth.mockReturnValue(
+ renderSelect("https://avatars.example.com/u/2?v=1"),
+ );
+ const { rerender } = render(
+ <CopilotAuthSection
+ mode="select"
+ selectedAccountId="octocat"
+ onAccountSelect={vi.fn()}
+ />,
+ );
+
+ const initialImg = screen.getByAltText("octocat");
+ expect(initialImg.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/2?v=1",
+ );
+
+ // 2 次退避重试均失败后停留在回退图标,直到 avatarUrl 变化再重置
+ fireEvent.error(initialImg);
+ expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();
+
+ act(() => vi.advanceTimersByTime(1000));
+ const retry1 = screen.getByAltText("octocat");
+ fireEvent.error(retry1);
+ act(() => vi.advanceTimersByTime(3000));
+ const retry2 = screen.getByAltText("octocat");
+ fireEvent.error(retry2);
+ act(() => vi.advanceTimersByTime(10_000));
+ expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();
+
+ mocks.useCopilotAuth.mockReturnValue(
+ renderSelect("https://avatars.example.com/u/2?v=2"),
+ );
+ rerender(
+ <CopilotAuthSection
+ mode="select"
+ selectedAccountId="octocat"
+ onAccountSelect={vi.fn()}
+ />,
+ );
+ const nextImg = screen.getByAltText("octocat");
+ expect(nextImg.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/2?v=2",
+ );
+
+ // 退避等待期间切换 URL 会立刻取消退避并加载新地址
+ fireEvent.error(nextImg);
+ expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();
+ mocks.useCopilotAuth.mockReturnValue(
+ renderSelect("https://avatars.example.com/u/2?v=3"),
+ );
+ rerender(
+ <CopilotAuthSection
+ mode="select"
+ selectedAccountId="octocat"
+ onAccountSelect={vi.fn()}
+ />,
+ );
+ const switchedImg = screen.getByAltText("octocat");
+ expect(switchedImg.getAttribute("src")).toBe(
+ "https://avatars.example.com/u/2?v=3",
+ );
+ act(() => vi.advanceTimersByTime(5000));
+ expect(screen.getByAltText("octocat")).toBe(switchedImg);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
describe("subscriptionQuotaState", () => {