From b2966149bcbac761b8ef5733f93026a5baf54729 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:02:26 +0800 Subject: [PATCH] Upstreams: one account label everywhere, read from the token; no live call for a broken sign-in - The edit dialog's sign-in box keeps saying which account it is (email and plan, from ProviderView.oauth.account) when the sign-in has expired, with the invalid state as a status label next to it, like the table row. The dialog header names the account where other upstreams show their address. - The ChatGPT sign-in dialog's "done" state names the account (email and plan) from the same place the row and the edit dialog read. It reads the upstream view once after core reports the sign-in done (core writes the config first), instead of ChatgptLoginStatus.plan, which only arrived when the 2 s poll beat the login_finished event, so the plan was usually missing. - The Z.ai sign-in dialog had the same race for its account name: the event now triggers one status read. Both dialogs settle a sign-in once. - No live ChatgptUsage / ChatgptResets call for an account whose sign-in has expired: not on page open (quotaAccounts) and not in the account section, which then shows only the sign-in box. - Command palette: account upstreams show and match their email, and say "Sign in again" like the row. Co-Authored-By: Claude Opus 5.5 --- src/palette/items.test.ts | 24 +++ src/palette/items.tsx | 21 ++- src/palette/palette.i18n.ts | 2 + src/upstreams/ChatgptAccountSection.tsx | 193 ++++++++++++---------- src/upstreams/ChatgptLoginDialog.i18n.tsx | 4 + src/upstreams/ChatgptLoginDialog.tsx | 35 ++-- src/upstreams/UpstreamDialog.tsx | 9 +- src/upstreams/ZaiLoginDialog.tsx | 30 ++-- src/upstreams/api.ts | 7 + src/upstreams/data.test.ts | 30 +++- src/upstreams/data.ts | 17 +- 11 files changed, 245 insertions(+), 127 deletions(-) diff --git a/src/palette/items.test.ts b/src/palette/items.test.ts index 7fb27806..521e8c31 100644 --- a/src/palette/items.test.ts +++ b/src/palette/items.test.ts @@ -1,3 +1,4 @@ +import type { ReactElement } from "react"; import { describe, expect, it } from "vitest"; import type { Nav } from "@/nav"; import type { ConnView } from "@/connection/api"; @@ -142,6 +143,29 @@ describe("命令面板的条目", () => { ]); }); + it("账号上游写登的是哪个账号,按邮箱也搜得到;登录失效和上游列表里一样说出来", () => { + const account = { + name: "chatgpt", + base_url: "https://chatgpt.com/backend-api/codex", + protocol: "chatgpt", + disabled: false, + health: "closed", + oauth: { + endpoint: "https://auth.openai.com/oauth/token", + needs_login: true, + account: { email: "dev@example.com", plan: "plus" }, + }, + }; + const withAccount = { ...ov, providers: [...ov.providers, account] } as unknown as Overview; + const items = buildItems(sources({ ov: withAccount })); + const item = items.find((i) => i.id === "upstream:chatgpt")!; + expect(item.detail).toBe("dev@example.com"); + expect(score("dev@example", item.title, item.keywords)).toBeGreaterThan(0); + expect((item.meta as ReactElement<{ text: string }>).props.text).toBe("需要重新登录"); + // 别的上游照旧写地址 + expect(items.find((i) => i.id === "upstream:deepseek")!.detail).toBe("api.deepseek.com"); + }); + it("只有一个连接时不出现「切换连接」", () => { const one = { ...conn, profiles: conn.profiles.slice(0, 1) } as ConnView; expect(ids(sources({ conn: one }))).not.toContain("action:switch-connection"); diff --git a/src/palette/items.tsx b/src/palette/items.tsx index 61915893..e2363d56 100644 --- a/src/palette/items.tsx +++ b/src/palette/items.tsx @@ -276,18 +276,23 @@ export function buildItems(s: Sources): Item[] { for (const p of ov.providers) { const status: [StatusTone, string] | null = p.disabled ? ["idle", t.disabled] - : p.auth_rejected != null - ? ["error", t.authRejected] - : p.health === "open" - ? ["error", t.circuitOpen] - : null; + : p.oauth?.needs_login + ? ["error", t.needsLogin] + : p.auth_rejected != null + ? ["error", t.authRejected] + : p.health === "open" + ? ["error", t.circuitOpen] + : null; + // 账号上游的地址人人一样:和上游列表一样,写登的是哪个账号 + const email = p.oauth?.account?.email; items.push({ id: `upstream:${p.name}`, group: "upstreams", title: p.name, - detail: hostOf(p.base_url), - // 地址也能搜(`11434`、`api.deepseek`);协议不算 —— 打 `openai` 会把一半上游都带出来 - keywords: [p.base_url], + detail: email ?? hostOf(p.base_url), + // 地址也能搜(`11434`、`api.deepseek`),账号的邮箱也能;协议不算 —— 打 `openai` + // 会把一半上游都带出来 + keywords: email ? [p.base_url, email] : [p.base_url], icon: , meta: status && , verb: "open", diff --git a/src/palette/palette.i18n.ts b/src/palette/palette.i18n.ts index ee81abd5..132635f0 100644 --- a/src/palette/palette.i18n.ts +++ b/src/palette/palette.i18n.ts @@ -72,6 +72,7 @@ export const paletteText = messages( disabled: "已停用", circuitOpen: "熔断中", authRejected: "凭据被拒", + needsLogin: "需要重新登录", defaultMark: "默认", defaultRoute: "默认路由", route: (name: string) => `路由 ${name}`, @@ -207,6 +208,7 @@ export const paletteText = messages( disabled: "Disabled", circuitOpen: "Circuit open", authRejected: "Credential rejected", + needsLogin: "Sign in again", defaultMark: "Default", defaultRoute: "Default route", route: (name: string) => `Route ${name}`, diff --git a/src/upstreams/ChatgptAccountSection.tsx b/src/upstreams/ChatgptAccountSection.tsx index cb7cbaef..c254946a 100644 --- a/src/upstreams/ChatgptAccountSection.tsx +++ b/src/upstreams/ChatgptAccountSection.tsx @@ -18,6 +18,7 @@ import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { notify } from "@/ui/notify"; import { Skeleton } from "@/ui/skeleton"; import { Spinner } from "@/ui/spinner"; +import { StatusLabel } from "@/ui/status-dot"; import { resetAt, resetIn } from "@/format"; import { useNow } from "@/useNow"; import type { ChatgptUsage, Overview, ProviderView, ResetCredits, ResetCreditView } from "@/types"; @@ -64,6 +65,7 @@ export function ChatgptAccountSection({ /** 用一张卡的结果 */ const codes: Record = t.codes; const name = editing.name; + const broken = editing.oauth?.needs_login === true; const [usage, setUsage] = useState(null); const [credits, setCredits] = useState(null); const [loading, setLoading] = useState(true); @@ -85,10 +87,11 @@ export function ChatgptAccountSection({ } }, [name]); - // 额度只在 core 的内存里:冷启动之后第一次打开就去问一次 + // 额度只在 core 的内存里:冷启动之后第一次打开就去问一次。**登录失效时不问**:凭据 + // 换不来令牌,额度和重置卡都问不到,这一节只剩重新登录 useEffect(() => { - void load(); - }, [load]); + if (!broken) void load(); + }, [load, broken]); async function use(credit: ResetCreditView) { setUsing(true); @@ -143,87 +146,91 @@ export function ChatgptAccountSection({ -
-
-

{t.quota}

- -
- {loading && !usage ? ( -
- {[0, 1].map((i) => ( -
-
- - -
- -
- ))} -
- ) : usage && usage.windows.length > 0 ? ( -
- {usage.windows.map((w) => { - const reset = resetAt(w.resets_at_ms, now); - return ( -
-
- {t.window(quotaWindowLabel(w.window))} - - {t.used(Math.round(w.used_percent))} - {reset && ` · ${t.resets(reset)}`} - + {!broken && ( + <> +
+
+

{t.quota}

+ +
+ {loading && !usage ? ( +
+ {[0, 1].map((i) => ( +
+
+ + +
+
- -
- ); - })} -
- ) : usage ? ( -

{t.noQuota}

- ) : null} -
+ ))} + + ) : usage && usage.windows.length > 0 ? ( +
+ {usage.windows.map((w) => { + const reset = resetAt(w.resets_at_ms, now); + return ( +
+
+ {t.window(quotaWindowLabel(w.window))} + + {t.used(Math.round(w.used_percent))} + {reset && ` · ${t.resets(reset)}`} + +
+ +
+ ); + })} +
+ ) : usage ? ( +

{t.noQuota}

+ ) : null} + -
-
-

- {t.credits} - {credits && ` · ${t.available(available.length)}`} -

-
-

{t.creditsNote}

- {!credits ? null : list.length === 0 ? ( -

{t.noCredits}

- ) : ( -
    - {list.map((c) => ( -
  • -
    -

    {c.title ?? t.credit}

    -

    - {status[c.status] ?? c.status} - {/* 到期日只对还能用的卡有意义 */} - {c.status === AVAILABLE && c.expires_at && ` · ${t.expires(c.expires_at.slice(0, 10))}`} -

    -
    - -
  • - ))} -
- )} -
+
+
+

+ {t.credits} + {credits && ` · ${t.available(available.length)}`} +

+
+

{t.creditsNote}

+ {!credits ? null : list.length === 0 ? ( +

{t.noCredits}

+ ) : ( +
    + {list.map((c) => ( +
  • +
    +

    {c.title ?? t.credit}

    +

    + {status[c.status] ?? c.status} + {/* 到期日只对还能用的卡有意义 */} + {c.status === AVAILABLE && c.expires_at && ` · ${t.expires(c.expires_at.slice(0, 10))}`} +

    +
    + +
  • + ))} +
+ )} +
+ + )} @@ -260,15 +267,15 @@ export function ChatgptAccountSection({ /** * 登录状态。 * - * 先说**登的是哪个账号** —— 上游的名字是用户自己取的,说明不了这一条。 + * 先说**登的是哪个账号** —— 上游的名字是用户自己取的,说明不了这一条。账号和套餐是 + * core 从凭据的令牌里读的,和列表那一行是同一份。**凭据失效之后仍是最后登着的那个, + * 照样写出来**:重新登录时要登回的就是它。 * **凭据失效时这里是唯一的出路**,所以它自己就带着重新登录。 */ function LoginBox({ editing, onRelogin }: { editing: ProviderView; onRelogin: () => void }) { const t = useText(chatgptAccountText); const oauth = editing.oauth; - // 账号和套餐是 core 从凭据的令牌里读的:凭据失效之后仍是最后登着的那个 - const email = oauth?.account?.email ?? null; - const plan = oauth?.account?.plan; + const who = [oauth?.account?.email, planLabel(oauth?.account?.plan)].filter(Boolean).join(" · "); const broken = oauth?.needs_login === true; const expires = oauth?.expires_at ? Date.parse(oauth.expires_at) : NaN; const left = Number.isNaN(expires) ? null : resetIn((expires - Date.now()) / 1000); @@ -276,10 +283,16 @@ function LoginBox({ editing, onRelogin }: { editing: ProviderView; onRelogin: ()
-

- {broken ? t.loginInvalid : (email ?? t.signedIn)} - {planLabel(plan) && !broken && ` · ${planLabel(plan)}`} -

+
+

+ {who || (broken ? t.loginInvalid : t.signedIn)} +

+ {broken && who && ( + + {t.loginInvalid} + + )} +
{broken ? (

{oauth?.failure ? coreText(oauth.failure) : t.needsLogin}

) : ( diff --git a/src/upstreams/ChatgptLoginDialog.i18n.tsx b/src/upstreams/ChatgptLoginDialog.i18n.tsx index 5cd7c510..af9fc00d 100644 --- a/src/upstreams/ChatgptLoginDialog.i18n.tsx +++ b/src/upstreams/ChatgptLoginDialog.i18n.tsx @@ -35,6 +35,8 @@ export const chatgptLoginText = messages( deviceWaiting: "输入完成后此处会自动继续。", deviceWarning: "登录码有效期 15 分钟。只输入这里显示的这一个;由他人提供的登录码请勿输入。", done: (provider: ReactNode) => <>已登录,上游 {provider} 已写入配置。, + account: (email: string, plan: string | null) => + plan ? `账号 ${email},订阅类型 ${plan}。` : `账号 ${email}。`, plan: (plan: string) => `订阅类型 ${plan}。`, doneHint: "模型范围、计费方式等可在该上游的编辑对话框中调整。", finish: "完成", @@ -76,6 +78,8 @@ export const chatgptLoginText = messages( deviceWaiting: "Sign-in continues here automatically once the code is entered.", deviceWarning: "The sign-in code is valid for 15 minutes. Enter only the code shown here; do not enter a sign-in code provided by someone else.", done: (provider: ReactNode) => <>Signed in. The upstream {provider} has been saved to the config., + account: (email: string, plan: string | null) => + plan ? `Account: ${email}, plan: ${plan}.` : `Account: ${email}.`, plan: (plan: string) => `Plan: ${plan}.`, doneHint: "Model scope, billing and other settings can be changed in the upstream's edit dialog.", finish: "Done", diff --git a/src/upstreams/ChatgptLoginDialog.tsx b/src/upstreams/ChatgptLoginDialog.tsx index 12a507c1..4029fba5 100644 --- a/src/upstreams/ChatgptLoginDialog.tsx +++ b/src/upstreams/ChatgptLoginDialog.tsx @@ -16,7 +16,7 @@ import { Field, FieldLabel } from "@/ui/field"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { StatusLabel } from "@/ui/status-dot"; -import type { ChatgptLoginMode, ChatgptLoginStatus, ChatgptPlan, CoreEvent, Overview } from "@/types"; +import type { AccountView, ChatgptLoginMode, ChatgptLoginStatus, CoreEvent, Overview } from "@/types"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; @@ -37,7 +37,8 @@ type Phase = | { at: "browser"; id: string } /** 码已经拿到,等用户在另一台设备上输 */ | { at: "device"; id: string; code: string; url: string } - | { at: "done"; provider: string; plan: ChatgptPlan | null }; + /** `account`:登上的是哪个账号,和列表、编辑对话框读的是同一份(上游视图的 `oauth.account`) */ + | { at: "done"; provider: string; account: AccountView | null }; /** * 用 ChatGPT 账号新建上游,或给已有的账号换一次凭据。 @@ -91,12 +92,22 @@ export function ChatgptLoginDialog({ }, []); const waiting = phase.at === "browser" || phase.at === "device" ? phase.id : null; + /** 已经收过尾的那次登录。事件和轮询都会报结果,只收一次 */ + const settled = useRef(null); function settle(s: ChatgptLoginStatus) { - if (!alive.current || s.status === "pending") return; + if (!alive.current || s.status === "pending" || settled.current === s.id) return; + settled.current = s.id; if (s.status === "done" && s.provider) { - setPhase({ at: "done", provider: s.provider, plan: s.plan ?? null }); - onSaved(s.provider); + const provider = s.provider; + onSaved(provider); + // 登上的是哪个账号,问上游视图:和列表、编辑对话框说的是同一份。问不到就只说上游 + void api + .signedInAs(provider) + .catch(() => null) + .then((account) => { + if (alive.current) setPhase({ at: "done", provider, account }); + }); return; } setPhase({ at: "form" }); @@ -169,7 +180,10 @@ export function ChatgptLoginDialog({ const nameTaken = !relogin && taken.includes(name.trim()) && phase.at === "form"; const canStart = name.trim().length > 0 && !nameTaken && understood && !busy; - const planName = phase.at === "done" ? planLabel(phase.plan) : null; + // 登上的账号:邮箱和套餐,令牌里读不出来的那一项不说 + const account = phase.at === "done" ? phase.account : null; + const plan = planLabel(account?.plan); + const who = account?.email ? t.account(account.email, plan) : plan ? t.plan(plan) : null; return ( !o && void cancel()}> @@ -295,10 +309,11 @@ export function ChatgptLoginDialog({ {phase.at === "done" && (
-

- {t.done({phase.provider})} - {planName && ` ${t.plan(planName)}`} -

+ {/* 登上的账号单独一行:接在上一句后面时,套餐名会被折断 */} +
+

{t.done({phase.provider})}

+ {who &&

{who}

} +

{t.doneHint}

)} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index f8b1cbdc..ef96c228 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -96,6 +96,8 @@ export function UpstreamDialog({ const set = (patch: Partial) => setForm((f) => ({ ...f, ...patch })); // ChatGPT 账号是登录来的,编辑它的那一套分节也不一样 const account = editing?.protocol === "chatgpt"; + /** 登的是哪个账号。core 从凭据的令牌里读,和列表那一行是同一份 */ + const email = editing?.oauth?.account?.email; const sections = (account ? ACCOUNT_SECTIONS : SECTIONS).map((id) => ({ id, label: t.sections[id] })); const [section, setSection] = useState
( mode.kind === "edit" @@ -312,8 +314,11 @@ export function UpstreamDialog({ {editing.name} ·{" "} {protocolLabel(editing.protocol)} - {/* 账号上游的地址是登录给的,改不了,写出来只是噪声 */} - {!account && ` · ${shortUrl(editing.base_url)}`} + {/* + 账号上游的地址是登录给的,改不了,写出来只是噪声:那一格和列表里一样写 + 登的是哪个账号 + */} + {account ? email && ` · ${email}` : ` · ${shortUrl(editing.base_url)}`} ) : ( {t.desc} diff --git a/src/upstreams/ZaiLoginDialog.tsx b/src/upstreams/ZaiLoginDialog.tsx index 59c4b3f6..4f36e8ab 100644 --- a/src/upstreams/ZaiLoginDialog.tsx +++ b/src/upstreams/ZaiLoginDialog.tsx @@ -80,9 +80,12 @@ export function ZaiLoginDialog({ }, []); const waiting = phase.at === "waiting" ? phase.id : null; + /** 已经收过尾的那次登录。事件和轮询都会报结果,只收一次 */ + const settled = useRef(null); function settle(s: ZaiLoginStatus) { - if (!alive.current || s.status === "pending") return; + if (!alive.current || s.status === "pending" || settled.current === s.id) return; + settled.current = s.id; if (s.status === "done" && s.provider) { setPhase({ at: "done", provider: s.provider, account: s.account ?? null }); onSaved(s.provider); @@ -99,12 +102,16 @@ export function ZaiLoginDialog({ const un = listen("core-event", (e) => { const ev = e.payload; if (ev.kind !== "login_finished" || ev.login !== waiting) return; - settle({ - id: ev.login, - status: ev.status, - provider: ev.provider ?? null, - error: ev.error ?? null, - }); + // 事件只报结果,不带登上的是哪个账号:那一项只在这次登录的状态里。立刻问一次, + // 问不到就按事件收尾 + api.zaiLoginStatus(ev.login).then(settle, () => + settle({ + id: ev.login, + status: ev.status, + provider: ev.provider ?? null, + error: ev.error ?? null, + }), + ); }); const timer = setInterval(() => { api @@ -266,10 +273,11 @@ export function ZaiLoginDialog({ {phase.at === "done" && (
-

- {t.done({phase.provider})} - {phase.account && ` ${t.account(phase.account)}`} -

+ {/* 登上的账号单独一行,和 ChatGPT 账号登录完成时一样 */} +
+

{t.done({phase.provider})}

+ {phase.account &&

{t.account(phase.account)}

} +

{t.doneHint}

)} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 8c3118a0..cee790df 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -76,6 +76,13 @@ export const api = { zaiLoginStatus: (id: string) => call("ZaiLoginStatus", null, id), cancelZaiLogin: (id: string) => invoke("cancel_zai_login", { id }), + /** + * 这个上游此刻登的是哪个账号(上游视图的 `oauth.account`,core 从凭据自己的令牌里读, + * 不联网)。登录刚完成时用它:core 先写配置再报完成,这时读到的就是这一次登录的; + * 页面手上那份概览可能还是写入之前读的 + */ + signedInAs: (name: string) => + call("Overview", null).then((o) => o.providers.find((p) => p.name === name)?.oauth?.account ?? null), chatgptUsage: (name: string) => call("ChatgptUsage", null, name), chatgptResets: (name: string) => call("ChatgptResets", null, name), /** 用掉一张卡。**用掉就回不来**,调用前必须让用户确认 */ diff --git a/src/upstreams/data.test.ts b/src/upstreams/data.test.ts index c014f0bf..5fa0079d 100644 --- a/src/upstreams/data.test.ts +++ b/src/upstreams/data.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import type { CostBucketGroup } from "@/types"; -import { HOUR, SLOTS, dayStart, slotsByUpstream } from "./data"; +import type { CostBucketGroup, OAuthView, ProviderView } from "@/types"; +import { HOUR, SLOTS, dayStart, quotaAccounts, slotsByUpstream } from "./data"; function bucket(name: string, at: number, requests: number, failed = 0): CostBucketGroup { return { @@ -63,3 +63,29 @@ describe("slotsByUpstream", () => { expect(slotsByUpstream([bucket("a", since - 2 * HOUR, 3)], since).has("a")).toBe(false); }); }); + +describe("quotaAccounts", () => { + function account(name: string, patch: Partial = {}, oauth: Partial = {}): ProviderView { + return { + name, + protocol: "chatgpt", + disabled: false, + oauth: { endpoint: "https://auth.openai.com/oauth/token", ...oauth }, + ...patch, + } as ProviderView; + } + + it("asks every enabled ChatGPT account, in name order", () => { + expect(quotaAccounts([account("work"), account("home")])).toEqual(["home", "work"]); + }); + + it("leaves out other upstreams, disabled accounts and accounts whose sign-in no longer works", () => { + const list = [ + account("anthropic", { protocol: "anthropic", oauth: null }), + account("off", { disabled: true }), + account("expired", {}, { needs_login: true }), + account("ok", {}, { needs_login: false }), + ]; + expect(quotaAccounts(list)).toEqual(["ok"]); + }); +}); diff --git a/src/upstreams/data.ts b/src/upstreams/data.ts index 3d155966..1efcb429 100644 --- a/src/upstreams/data.ts +++ b/src/upstreams/data.ts @@ -116,10 +116,7 @@ export function usePricingStatus(configVersion: string) { * 额度,`onAnswered` 让统计从 core 再读一遍,免得这里和它各存一份。 */ export function useAccountQuotas(providers: ProviderView[], onAnswered: () => void): void { - const names = providers - .filter((p) => p.protocol === "chatgpt" && !p.disabled) - .map((p) => p.name) - .sort(); + const names = quotaAccounts(providers); const key = names.join("\n"); const answered = useRef(onAnswered); answered.current = onAnswered; @@ -135,6 +132,18 @@ export function useAccountQuotas(providers: ProviderView[], onAnswered: () => vo ); } +/** + * 打开这一页时要问额度的账号:启用着的 ChatGPT 账号上游,按名字排好。 + * + * **登录已失效的不问**:凭据换不来令牌,这一问注定失败。 + */ +export function quotaAccounts(providers: readonly ProviderView[]): string[] { + return providers + .filter((p) => p.protocol === "chatgpt" && !p.disabled && p.oauth?.needs_login !== true) + .map((p) => p.name) + .sort(); +} + /** 在途请求记住多少条已经结束的 id(结束事件比快照先到时用来排除)。只是防御性的上限 */ const ENDED_CAP = 512;