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
25 changes: 23 additions & 2 deletions src-tauri/src/upstreams.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! 上游页的汇总:一行上的费用、延迟、额度一起取。
//! 上游页的汇总:一行上的费用、延迟、额度、走势一起取。
//!
//! 上游、代理、价目表的增删改与检测都是直接转发的端点,走 `crate::call`。

Expand All @@ -7,7 +7,8 @@ use tw_api::ep;
use crate::AppState;
use crate::error::Out;

/// 上游列表那几列统计:24 小时的请求与费用、首字节耗时、订阅额度。
/// 上游列表那几列统计:一段时间里的请求与费用、首字节耗时、订阅额度,以及同一段
/// 时间按上游分格的请求数(每一行的走势)。
///
/// **一起取。**列表上它们是同一行的几格,分几次 invoke 会让一行数字分几次
/// 跳变。拿不到的就是空的 —— 存储层不在的时候网关照常转发,列表也该照常打开。
Expand All @@ -16,12 +17,20 @@ pub struct UpstreamStats {
costs: Vec<tw_api::CostGroup>,
latency: Vec<tw_api::LatencyView>,
quotas: Vec<tw_api::ProviderQuota>,
/// 按界面给的格宽、按上游分格。**稀疏的** —— 没有请求的格子不在里面,由界面补
buckets: Vec<tw_api::CostBucketGroup>,
}

/// 格宽的下限。和概览同一条:再细就是把噪声当细节,而这一条查询还要乘上上游个数
const MIN_BUCKET_MS: i64 = 60_000;

#[tauri::command]
pub async fn upstream_stats(
state: tauri::State<'_, AppState>,
// 时间窗的起点和一格多宽,**都由界面给**:格子要对齐到本地的整点,而本地时区
// 只有界面知道(见 `dashboard` 的同名参数)
since_ms: i64,
bucket_ms: i64,
) -> Out<UpstreamStats> {
let c = &state.control;
Ok(UpstreamStats {
Expand All @@ -41,6 +50,18 @@ pub async fn upstream_stats(
.await
.unwrap_or_default(),
quotas: c.call::<ep::Quota>(&[], &()).await.unwrap_or_default(),
buckets: c
.call::<ep::CostBucketsBy>(
&[],
&tw_api::BucketGroupQuery {
from_ms: Some(since_ms),
to_ms: None,
bucket_ms: Some(bucket_ms.max(MIN_BUCKET_MS)),
dim: tw_api::CostDim::Provider,
},
)
.await
.unwrap_or_default(),
})
}

Expand Down
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,7 @@ function Shell({ first }: { first: boolean }) {
)
) : tab === "upstreams" ? (
ov ? (
<UpstreamsPage ov={ov} onChanged={changed} onOpenConfigFile={openConfigFile} onNavigate={go} />
<UpstreamsPage ov={ov} onChanged={changed} onOpenConfigFile={openConfigFile} />
) : (
skeleton
)
Expand Down
6 changes: 3 additions & 3 deletions src/upstreams/BillingSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { useText } from "@/i18n";
import type { Overview, ResolvedPrice } from "@/types";
import { billingSectionText } from "./BillingSection.i18n";
import { BILLINGS, PRICE_COLUMNS, perMillion, priceSourceLabel } from "./labels";
import { Boxed, FormItem, NameChips, Note } from "./parts";
import { Boxed, FormItem, Note, UpstreamChips } from "./parts";
import type { UpstreamForm } from "./upstreamForm";

/** 「新建价目表…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */
Expand Down Expand Up @@ -97,7 +97,7 @@ export function BillingSection({
{perToken && sheet && (
<div className="flex items-center gap-2.5 rounded-lg border border-border px-3 py-2.5">
<span className="shrink-0 tw-label text-muted-foreground">{t.usedBy}</span>
<NameChips names={users} empty="" />
<UpstreamChips names={users} providers={ov.providers} empty="" />
<div className="flex-1" />
<Button variant="outline" size="sm" onClick={() => onEditSheet(sheet.name)}>
<PencilIcon />
Expand Down Expand Up @@ -136,7 +136,7 @@ export function BillingSection({
<TableRow key={m}>
<TableCell className="font-mono">{m}</TableCell>
{PRICE_COLUMNS.map((c) => (
<TableCell key={c.key} className="text-right tabular-nums">
<TableCell key={c.key} className="text-right tw-num">
{perMillion(r?.price?.[c.key])}
</TableCell>
))}
Expand Down
2 changes: 0 additions & 2 deletions src/upstreams/ChatgptAccountSection.i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const chatgptAccountText = messages(
systemProxy: "系统代理",
quota: "订阅额度",
reload: "重新读取",
loading: "正在读取",
window: (label: string) => `${label}窗口`,
used: (percent: number) => `已用 ${percent}%`,
resets: (when: string) => `${when}重置`,
Expand Down Expand Up @@ -66,7 +65,6 @@ export const chatgptAccountText = messages(
systemProxy: "System proxy",
quota: "Usage limits",
reload: "Reload",
loading: "Loading",
window: (label: string) => `${label} window`,
used: (percent: number) => `${percent}% used`,
resets: (when: string) => `resets ${when}`,
Expand Down
66 changes: 43 additions & 23 deletions src/upstreams/ChatgptAccountSection.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from "react";
import { useSystemProxyLabel } from "@/connection/Remote";
import { CircleAlertIcon, RefreshCwIcon } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/ui/alert";
import { RefreshCwIcon } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
Expand All @@ -12,10 +11,12 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/ui/alert-dialog";
import { Banner } from "@/ui/banner";
import { Button } from "@/ui/button";
import { Input } from "@/ui/input";
import { NativeSelect, NativeSelectOption } from "@/ui/native-select";
import { Progress } from "@/ui/progress";
import { notify } from "@/ui/notify";
import { Skeleton } from "@/ui/skeleton";
import { Spinner } from "@/ui/spinner";
import { resetAt, resetIn } from "@/format";
import { useNow } from "@/useNow";
Expand All @@ -25,7 +26,8 @@ import { commonText } from "@/i18n/common.i18n";
import { api } from "./api";
import { chatgptAccountText } from "./ChatgptAccountSection.i18n";
import { coreText, errorText, planLabel, proxyKindLabel, quotaWindowLabel } from "./labels";
import { FormItem } from "./parts";
import { DialogError, FormItem } from "./parts";
import { QuotaBar } from "./QuotaBar";
import type { UpstreamForm } from "./upstreamForm";

/** 卡的状态词表由上游给,只有这一个能用 */
Expand Down Expand Up @@ -68,7 +70,6 @@ export function ChatgptAccountSection({
const [error, setError] = useState<string | null>(null);
const [confirming, setConfirming] = useState<ResetCreditView | null>(null);
const [using, setUsing] = useState(false);
const [outcome, setOutcome] = useState<string | null>(null);

const load = useCallback(async () => {
setLoading(true);
Expand Down Expand Up @@ -96,7 +97,10 @@ export function ChatgptAccountSection({
// 幂等键按这一次操作生成:重试时不会再扣一张
const key = `${name}:${credit.id}:${Date.now()}`;
const r = await api.useChatgptReset(name, credit.id, key);
setOutcome(r.code);
// 结果是一句话:重置了(额度条随之变回去),或者没有用卡的原因
const said = codes[r.code] ?? r.code;
if (r.code === "reset") notify.success(said);
else notify.info(said);
await load();
} catch (e) {
setError(errorText(e));
Expand Down Expand Up @@ -147,34 +151,44 @@ export function ChatgptAccountSection({
<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()} disabled={loading}>
{loading ? <Spinner /> : <RefreshCwIcon />}
<Button variant="ghost" size="sm" onClick={() => void load()} pending={loading}>
{!loading && <RefreshCwIcon />}
{t.reload}
</Button>
</div>
{loading && !usage ? (
<p className="tw-body text-muted-foreground">{t.loading}</p>
<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">
<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="tabular-nums text-muted-foreground">
<span className="tw-num text-muted-foreground">
{t.used(Math.round(w.used_percent))}
{reset && ` · ${t.resets(reset)}`}
</span>
</div>
<Progress value={Math.min(100, w.used_percent)} />
<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">
Expand All @@ -185,7 +199,7 @@ export function ChatgptAccountSection({
</h3>
</div>
<p className="tw-label text-muted-foreground">{t.creditsNote}</p>
{list.length === 0 ? (
{!credits ? null : list.length === 0 ? (
<p className="tw-body text-muted-foreground">{t.noCredits}</p>
) : (
<ul className="flex flex-col gap-2">
Expand Down Expand Up @@ -216,23 +230,29 @@ export function ChatgptAccountSection({
)}
</section>

{outcome && <p className="tw-body">{codes[outcome] ?? outcome}</p>}
{error && <p className="tw-body text-destructive">{error}</p>}
<DialogError error={error} />

<AlertDialog open={confirming != null} onOpenChange={(o) => !o && setConfirming(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t.confirmTitle}</AlertDialogTitle>
<AlertDialogDescription>{t.confirmDesc}</AlertDialogDescription>
</AlertDialogHeader>
<Alert variant="warning">
<CircleAlertIcon />
<AlertTitle>{t.notConsumedTitle}</AlertTitle>
<AlertDescription>{t.notConsumedDesc}</AlertDescription>
</Alert>
<Banner layout="inline" tone="warning" title={t.notConsumedTitle}>
{t.notConsumedDesc}
</Banner>
<AlertDialogFooter>
<AlertDialogCancel>{common.cancel}</AlertDialogCancel>
<AlertDialogAction onClick={() => confirming && void use(confirming)} disabled={using}>
<AlertDialogAction
disabled={using}
aria-busy={using || undefined}
onClick={(e) => {
// 用完再关:结果和原因要等上游答复
e.preventDefault();
if (confirming) void use(confirming);
}}
>
{using && <Spinner data-icon="inline-start" aria-hidden />}
{t.use}
</AlertDialogAction>
</AlertDialogFooter>
Expand Down
Loading
Loading