Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/palette/items.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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");
Expand Down
21 changes: 13 additions & 8 deletions src/palette/items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: <UpstreamLogo name={p.name} baseUrl={p.base_url} protocol={p.protocol} />,
meta: status && <Status tone={status[0]} text={status[1]} />,
verb: "open",
Expand Down
2 changes: 2 additions & 0 deletions src/palette/palette.i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export const paletteText = messages(
disabled: "已停用",
circuitOpen: "熔断中",
authRejected: "凭据被拒",
needsLogin: "需要重新登录",
defaultMark: "默认",
defaultRoute: "默认路由",
route: (name: string) => `路由 ${name}`,
Expand Down Expand Up @@ -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}`,
Expand Down
193 changes: 103 additions & 90 deletions src/upstreams/ChatgptAccountSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -64,6 +65,7 @@ export function ChatgptAccountSection({
/** 用一张卡的结果 */
const codes: Record<string, string> = t.codes;
const name = editing.name;
const broken = editing.oauth?.needs_login === true;
const [usage, setUsage] = useState<ChatgptUsage | null>(null);
const [credits, setCredits] = useState<ResetCredits | null>(null);
const [loading, setLoading] = useState(true);
Expand All @@ -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);
Expand Down Expand Up @@ -143,87 +146,91 @@ export function ChatgptAccountSection({

<LoginBox editing={editing} onRelogin={onRelogin} />

<section className="flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-3">
<h3 className="tw-head font-medium">{t.quota}</h3>
<Button variant="ghost" size="sm" onClick={() => void load()} pending={loading}>
{!loading && <RefreshCwIcon />}
{t.reload}
</Button>
</div>
{loading && !usage ? (
<div role="status" aria-busy="true" className="flex flex-col gap-3.5">
{[0, 1].map((i) => (
<div key={i} className="flex flex-col gap-1.5">
<div className="flex justify-between">
<Skeleton className="h-3 w-24 rounded-sm" />
<Skeleton className="h-3 w-32 rounded-sm" />
</div>
<Skeleton className="h-1 w-full rounded-full" />
</div>
))}
</div>
) : usage && usage.windows.length > 0 ? (
<div className="flex flex-col gap-2.5 motion-fade">
{usage.windows.map((w) => {
const reset = resetAt(w.resets_at_ms, now);
return (
<div key={w.window} className="flex flex-col gap-1">
<div className="flex items-baseline justify-between tw-body">
<span>{t.window(quotaWindowLabel(w.window))}</span>
<span className="tw-num text-muted-foreground">
{t.used(Math.round(w.used_percent))}
{reset && ` · ${t.resets(reset)}`}
</span>
{!broken && (
<>
<section className="flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-3">
<h3 className="tw-head font-medium">{t.quota}</h3>
<Button variant="ghost" size="sm" onClick={() => void load()} pending={loading}>
{!loading && <RefreshCwIcon />}
{t.reload}
</Button>
</div>
{loading && !usage ? (
<div role="status" aria-busy="true" className="flex flex-col gap-3.5">
{[0, 1].map((i) => (
<div key={i} className="flex flex-col gap-1.5">
<div className="flex justify-between">
<Skeleton className="h-3 w-24 rounded-sm" />
<Skeleton className="h-3 w-32 rounded-sm" />
</div>
<Skeleton className="h-1 w-full rounded-full" />
</div>
<QuotaBar percent={w.used_percent} label={t.window(quotaWindowLabel(w.window))} />
</div>
);
})}
</div>
) : usage ? (
<p className="tw-body text-muted-foreground">{t.noQuota}</p>
) : null}
</section>
))}
</div>
) : usage && usage.windows.length > 0 ? (
<div className="flex flex-col gap-2.5 motion-fade">
{usage.windows.map((w) => {
const reset = resetAt(w.resets_at_ms, now);
return (
<div key={w.window} className="flex flex-col gap-1">
<div className="flex items-baseline justify-between tw-body">
<span>{t.window(quotaWindowLabel(w.window))}</span>
<span className="tw-num text-muted-foreground">
{t.used(Math.round(w.used_percent))}
{reset && ` · ${t.resets(reset)}`}
</span>
</div>
<QuotaBar percent={w.used_percent} label={t.window(quotaWindowLabel(w.window))} />
</div>
);
})}
</div>
) : usage ? (
<p className="tw-body text-muted-foreground">{t.noQuota}</p>
) : null}
</section>

<section className="flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-3">
<h3 className="tw-head font-medium">
{t.credits}
{credits && ` · ${t.available(available.length)}`}
</h3>
</div>
<p className="tw-label text-muted-foreground">{t.creditsNote}</p>
{!credits ? null : list.length === 0 ? (
<p className="tw-body text-muted-foreground">{t.noCredits}</p>
) : (
<ul className="flex flex-col gap-2">
{list.map((c) => (
<li
key={c.id}
className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2"
>
<div className="min-w-0">
<p className="tw-body">{c.title ?? t.credit}</p>
<p className="tw-label text-muted-foreground">
{status[c.status] ?? c.status}
{/* 到期日只对还能用的卡有意义 */}
{c.status === AVAILABLE && c.expires_at && ` · ${t.expires(c.expires_at.slice(0, 10))}`}
</p>
</div>
<Button
variant="outline"
size="sm"
disabled={c.status !== AVAILABLE || using}
onClick={() => setConfirming(c)}
>
{t.useEllipsis}
</Button>
</li>
))}
</ul>
)}
</section>
<section className="flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-3">
<h3 className="tw-head font-medium">
{t.credits}
{credits && ` · ${t.available(available.length)}`}
</h3>
</div>
<p className="tw-label text-muted-foreground">{t.creditsNote}</p>
{!credits ? null : list.length === 0 ? (
<p className="tw-body text-muted-foreground">{t.noCredits}</p>
) : (
<ul className="flex flex-col gap-2">
{list.map((c) => (
<li
key={c.id}
className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2"
>
<div className="min-w-0">
<p className="tw-body">{c.title ?? t.credit}</p>
<p className="tw-label text-muted-foreground">
{status[c.status] ?? c.status}
{/* 到期日只对还能用的卡有意义 */}
{c.status === AVAILABLE && c.expires_at && ` · ${t.expires(c.expires_at.slice(0, 10))}`}
</p>
</div>
<Button
variant="outline"
size="sm"
disabled={c.status !== AVAILABLE || using}
onClick={() => setConfirming(c)}
>
{t.useEllipsis}
</Button>
</li>
))}
</ul>
)}
</section>
</>
)}

<DialogError error={error} />

Expand Down Expand Up @@ -260,26 +267,32 @@ 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);
return (
<div className="rounded-md border border-border px-3 py-2.5">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<p className="truncate tw-body font-medium" title={email ?? undefined}>
{broken ? t.loginInvalid : (email ?? t.signedIn)}
{planLabel(plan) && !broken && ` · ${planLabel(plan)}`}
</p>
<div className="flex min-w-0 items-center gap-2">
<p className="truncate tw-body font-medium" title={who || undefined}>
{who || (broken ? t.loginInvalid : t.signedIn)}
</p>
{broken && who && (
<StatusLabel tone="error" className="shrink-0">
{t.loginInvalid}
</StatusLabel>
)}
</div>
{broken ? (
<p className="tw-label text-muted-foreground">{oauth?.failure ? coreText(oauth.failure) : t.needsLogin}</p>
) : (
Expand Down
4 changes: 4 additions & 0 deletions src/upstreams/ChatgptLoginDialog.i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: "完成",
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading