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
4 changes: 2 additions & 2 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2"
# 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制
# 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从
# 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.7.0" }
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.8.1" }

anyhow = "1"
libc = "0.2"
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,8 @@ export interface ChatgptLoginStatus {

/** 账号的订阅额度 */
export interface ChatgptUsage {
/** 登的是哪个账号。core 只给邮箱,用户 ID 和账户 ID 不往外带 */
email?: string | null;
plan?: string | null;
windows: QuotaWindow[];
/** 可用的额度重置卡张数。账号没有这一项时没有 */
Expand Down
26 changes: 19 additions & 7 deletions src/upstreams/ChatgptAccountSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { Spinner } from "@/ui/spinner";
import { resetIn } from "@/format";
import type { ChatgptUsage, Overview, ProviderView, ResetCredits, ResetCreditView } from "@/types";
import { api } from "./api";
import { errorText, proxyKindLabel, quotaWindowLabel } from "./labels";
import { errorText, planLabel, proxyKindLabel, quotaWindowLabel } from "./labels";
import { FormItem } from "./parts";
import type { UpstreamForm } from "./upstreamForm";

Expand Down Expand Up @@ -140,7 +140,12 @@ export function ChatgptAccountSection({
</FormItem>
</div>

<LoginBox editing={editing} plan={usage?.plan ?? null} onRelogin={onRelogin} />
<LoginBox
editing={editing}
email={usage?.email ?? null}
plan={usage?.plan ?? null}
onRelogin={onRelogin}
/>

<section className="flex flex-col gap-2">
<div className="flex items-baseline justify-between gap-3">
Expand All @@ -161,7 +166,7 @@ export function ChatgptAccountSection({
<div className="flex items-baseline justify-between tw-body">
<span>{quotaWindowLabel(w.window)}窗口</span>
<span className="tabular-nums text-muted-foreground">
{Math.round(w.used_percent)}%{reset && ` · ${reset}重置`}
已用 {Math.round(w.used_percent)}%{reset && ` · ${reset}重置`}
</span>
</div>
<Progress value={Math.min(100, w.used_percent)} />
Expand Down Expand Up @@ -244,13 +249,20 @@ export function ChatgptAccountSection({
);
}

/** 登录状态:**凭据失效时这里是唯一的出路**,所以它自己就带着重新登录 */
/**
* 登录状态。
*
* 先说**登的是哪个账号** —— 上游的名字是用户自己取的,说明不了这一条。
* **凭据失效时这里是唯一的出路**,所以它自己就带着重新登录。
*/
function LoginBox({
editing,
email,
plan,
onRelogin,
}: {
editing: ProviderView;
email: string | null;
plan: string | null;
onRelogin: () => void;
}) {
Expand All @@ -262,9 +274,9 @@ function LoginBox({
<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="tw-body font-medium">
{broken ? "登录已失效" : "已登录"}
{plan && !broken && ` · ${plan}`}
<p className="truncate tw-body font-medium" title={email ?? undefined}>
{broken ? "登录已失效" : (email ?? "已登录")}
{planLabel(plan) && !broken && ` · ${planLabel(plan)}`}
</p>
<p className="tw-label text-muted-foreground">
{broken
Expand Down
145 changes: 121 additions & 24 deletions src/upstreams/UpstreamTable.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { useEffect, useState } from "react";
import { Badge } from "@/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover";
import { Progress } from "@/ui/progress";
import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu";
import {
Expand All @@ -10,9 +12,17 @@ import {
TableRow,
} from "@/ui/table";
import { resetIn } from "@/format";
import { usd, type Overview, type ProviderView } from "@/types";
import type { UpstreamStats } from "./api";
import { billingLabel, egressLabel, protocolLabel, quotaWindowLabel, shortUrl } from "./labels";
import { usd, type ChatgptUsage, type Overview, type ProviderModelsView, type ProviderView } from "@/types";
import { api, type UpstreamStats } from "./api";
import {
billingLabel,
egressLabel,
modelSourceNote,
planLabel,
protocolLabel,
quotaWindowLabel,
shortUrl,
} from "./labels";

export interface UpstreamActions {
edit: (name: string) => void;
Expand All @@ -35,10 +45,13 @@ export interface UpstreamActions {
export function UpstreamTable({
ov,
stats,
accounts,
actions,
}: {
ov: Overview;
stats: UpstreamStats | null;
/** 账号类上游问来的账号信息,按上游名。还没问到的就没有 */
accounts: Record<string, ChatgptUsage>;
actions: UpstreamActions;
}) {
return (
Expand Down Expand Up @@ -74,6 +87,10 @@ export function UpstreamTable({
{p.name}
</span>
{p.trust === "official" && <Badge variant="secondary">官方端点</Badge>}
{/* 订阅类账号:套餐决定了额度有多大,和名字放在一起看 */}
{planLabel(accounts[p.name]?.plan) && (
<Badge variant="outline">{planLabel(accounts[p.name]?.plan)}</Badge>
)}
{p.disabled ? (
<Badge variant="outline">已停用</Badge>
) : p.health === "open" ? (
Expand All @@ -84,16 +101,7 @@ export function UpstreamTable({
协议、地址、出站方式是同一件事的三个部分:这一家在哪、怎么连。
地址可能很长(带路径的中转):截断,悬停看全
*/}
<div
className="max-w-96 truncate tw-label text-muted-foreground"
title={`${protocolLabel(p.protocol)} · ${p.base_url}${
p.proxy === "direct" ? "" : ` · 经 ${egressLabel(p.proxy)}`
}`}
>
{protocolLabel(p.protocol)} · {shortUrl(p.base_url)}
{/* 直连是默认,不用说 */}
{p.proxy !== "direct" && ` · 经 ${egressLabel(p.proxy)}`}
</div>
<Where p={p} account={accounts[p.name]} />
</TableCell>
<ModelsCell p={p} />
<QuotaCell p={p} stats={stats} />
Expand Down Expand Up @@ -129,19 +137,107 @@ function menu(p: ProviderView, a: UpstreamActions): MenuItems {
];
}

/**
* 这一家在哪、怎么连。
*
* 账号类上游的地址永远是同一个,**写出来一行废话** —— 那一格
* 留给邮箱:登了两个账号时,它是唯一能分辨哪行是哪个的东西。
*/
function Where({ p, account }: { p: ProviderView; account?: ChatgptUsage }) {
// 账号类上游的地址永远是同一个,名字后面的「官方端点」已经说了它在哪
const isAccount = p.protocol === "chatgpt";
const where = isAccount ? (account?.email ?? null) : shortUrl(p.base_url);
const egress = p.proxy === "direct" ? "" : ` · 经 ${egressLabel(p.proxy)}`;
const full = [protocolLabel(p.protocol), isAccount ? account?.email : p.base_url]
.filter(Boolean)
.join(" · ");
return (
<div className="max-w-96 truncate tw-label text-muted-foreground" title={`${full}${egress}`}>
{protocolLabel(p.protocol)}
{where && ` · ${where}`}
{/* 直连是默认,不用说 */}
{egress}
</div>
);
}

/**
* 有多少个模型,以及都有哪些。
*
* 数目单独回答不了「我要的那个模型在不在里面」,而一个二十几项的清单
* 又放不进一格。**点数字就展开**,不用为了看一眼进编辑对话框。
*/
function ModelsCell({ p }: { p: ProviderView }) {
const sub =
p.model_source === "manual"
? "手动清单"
: p.model_source === "none"
? "未获取"
: p.models_only
? "指定范围"
: null;
const [open, setOpen] = useState(false);
const [list, setList] = useState<ProviderModelsView | null>(null);
const [failed, setFailed] = useState(false);
const none = p.disabled || p.model_source === "none";
const sub = modelSourceNote(p);

// 展开才去读:一页上十几家上游,没人看的清单不该占着一次调用
useEffect(() => {
if (!open || list || failed) return;
let alive = true;
api
.providerModels(p.name)
.then((v) => alive && setList(v))
.catch(() => alive && setFailed(true));
return () => {
alive = false;
};
}, [open, list, failed, p.name]);

if (none) {
return (
<TableCell className="text-right tabular-nums">
{/* 停用时 core 报 0 —— 那不是「没有模型」,状态一栏已经说了停用 */}
—{sub && <div className="tw-label text-muted-foreground">{sub}</div>}
</TableCell>
);
}

const models = list?.models ?? [];
const shown = models.filter((m) => m.enabled);
const hidden = models.length - shown.length;
return (
<TableCell className="text-right tabular-nums">
{/* 停用时 core 报 0 —— 那不是「没有模型」,状态一栏已经说了停用 */}
{p.disabled || p.model_source === "none" ? "—" : p.model_count}
<Popover open={open} onOpenChange={setOpen}>
{/*
悬停时变成一个块,不画下划线 —— 鼠标正好压在字的下方,
一条紧贴基线的线它自己就把它挡了
*/}
<PopoverTrigger className="-mr-1.5 rounded px-1.5 py-0.5 tabular-nums transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted aria-expanded:bg-muted aria-expanded:text-foreground">
{p.model_count}
</PopoverTrigger>
<PopoverContent align="end" className="w-64">
<div className="flex items-baseline justify-between gap-2">
<span className="tw-body font-medium">模型清单</span>
{sub && <span className="tw-label text-muted-foreground">{sub}</span>}
</div>
{failed ? (
<p className="tw-label text-muted-foreground">暂时读不到模型清单。</p>
) : !list ? (
<p className="tw-label text-muted-foreground">正在读取</p>
) : (
<>
<ul className="max-h-64 overflow-y-auto text-left font-mono tw-label">
{shown.map((m) => (
<li key={m.id} className="truncate py-0.5" title={m.id}>
{m.id}
</li>
))}
</ul>
{/* 范围外的不列,但要说有——否则这份清单看起来就是它全部的模型 */}
{hidden > 0 && (
<p className="tw-label text-muted-foreground">
另有 {hidden} 个不在启用范围内
</p>
)}
{list.error && <p className="tw-label text-warning">{list.error}</p>}
</>
)}
</PopoverContent>
</Popover>
{sub && <div className="tw-label text-muted-foreground">{sub}</div>}
</TableCell>
);
Expand All @@ -166,7 +262,8 @@ function QuotaCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null
return (
<TableCell>
<div className="flex items-baseline justify-between gap-2">
<span className="tabular-nums">{Math.round(tight.used_percent)}%</span>
{/* **要说清楚这个数是用掉的还是剩下的**:一根填了一半的条,两种读法都成立 */}
<span className="tabular-nums">已用 {Math.round(tight.used_percent)}%</span>
<span className="tw-label text-muted-foreground">
{reset ? `${quotaWindowLabel(tight.window)} · ${reset}` : quotaWindowLabel(tight.window)}
</span>
Expand Down
39 changes: 37 additions & 2 deletions src/upstreams/UpstreamsPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { ActivityIcon, CircleAlertIcon, PlusIcon, RefreshCwIcon, ServerIcon, ZapIcon } from "lucide-react";
import { toast } from "sonner";
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/ui/alert";
Expand All @@ -14,7 +14,7 @@ import {
import { Spinner } from "@/ui/spinner";
import { Switch } from "@/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs";
import type { Overview, PricingStatus } from "@/types";
import type { ChatgptUsage, Overview, PricingStatus } from "@/types";
import { api, type UpstreamStats } from "./api";
import { ChatgptLoginDialog } from "./ChatgptLoginDialog";
import { DeleteDialog, type Referrer } from "./DeleteDialog";
Expand Down Expand Up @@ -100,6 +100,40 @@ export default function UpstreamsPage({
const t = setInterval(loadStats, 30_000);
return () => clearInterval(t);
}, [loadStats]);

/**
* 账号类上游:**打开这一页时问一次它自己。**
*
* 一次问答同时回答三件事:登的是哪个账号、什么套餐、额度还剩多少。
* 这三件都不在配置里 —— 额度平时是跟着真实流量白捡的,所以刚启动、
* 或者这个账号今天还没被用过时,不问就什么都没有。
*
* **每个上游只问一次。**问一次是一次真实调用;失败了也不再问 —— 连不上时
* 三十秒重试一轮,只会把错误刷满日志。
*/
const [accounts, setAccounts] = useState<Record<string, ChatgptUsage>>({});
const askedUsage = useRef(new Set<string>());
useEffect(() => {
const fresh = ov.providers.filter(
(p) => p.protocol === "chatgpt" && !p.disabled && !askedUsage.current.has(p.name),
);
if (fresh.length === 0) return;
fresh.forEach((p) => askedUsage.current.add(p.name));
void Promise.all(
fresh.map((p) =>
api
.chatgptUsage(p.name)
.then((u) => [p.name, u] as const)
.catch(() => null),
),
).then((rs) => {
const got = rs.filter((r) => r !== null);
if (got.length === 0) return;
setAccounts((a) => ({ ...a, ...Object.fromEntries(got) }));
// 额度 core 那边也记下了,从它再读一遍,免得这里和它各存一份
loadStats();
});
}, [ov.providers, loadStats]);
useEffect(() => {
loadStatus();
}, [loadStatus, configVersion]);
Expand Down Expand Up @@ -277,6 +311,7 @@ export default function UpstreamsPage({
<UpstreamTable
ov={ov}
stats={stats}
accounts={accounts}
actions={{
edit: (name) => setDialog({ kind: "upstream", mode: { kind: "edit", name } }),
test: (name) => setDialog({ kind: "test", name }),
Expand Down
25 changes: 25 additions & 0 deletions src/upstreams/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,31 @@ export function modelSourceLabel(source: string): string {
}

/** 订阅额度窗口:`5h` / `7d` / `weekly` */
/** 模型清单是怎么来的。自动获取、范围也没限制时不用说 */
export function modelSourceNote(p: ProviderView): string | null {
if (p.model_source === "manual") return "手动清单";
if (p.model_source === "none") return "未获取";
return p.models_only ? "指定范围" : null;
}

/**
* 订阅类型。**认不出来的原样显示** —— OpenAI 随时会多出一个
* 新名字,把它显示成「未知」比直接写出那个词更差。
*/
export function planLabel(plan: string | null | undefined): string | null {
if (!plan) return null;
const known: Record<string, string> = {
free: "Free",
plus: "Plus",
pro: "Pro",
team: "Team",
business: "Business",
enterprise: "Enterprise",
edu: "Edu",
};
return known[plan.toLowerCase()] ?? plan;
}

export function quotaWindowLabel(window: string): string {
switch (window) {
case "5h":
Expand Down
Loading