From e479f41fb930f3eb464125566b81cb19dbd8cf4a Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 05:57:02 +0800 Subject: [PATCH 1/3] Upstreams: page header, vendor logos, 24h sparkline, kit states and motion Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/upstreams.rs | 25 +- src/App.tsx | 2 +- src/upstreams/BillingSection.tsx | 6 +- src/upstreams/ChatgptAccountSection.i18n.ts | 2 - src/upstreams/ChatgptAccountSection.tsx | 54 +- src/upstreams/ChatgptLoginDialog.tsx | 52 +- src/upstreams/ConnectionSection.i18n.ts | 6 +- src/upstreams/ConnectionSection.tsx | 49 +- src/upstreams/DeleteDialog.tsx | 22 +- src/upstreams/ModelsPanel.i18n.ts | 2 - src/upstreams/ModelsPanel.tsx | 115 +-- src/upstreams/ModelsSection.tsx | 22 +- src/upstreams/PriceSheetDialog.i18n.ts | 2 - src/upstreams/PriceSheetDialog.tsx | 111 +-- src/upstreams/PriceSheetTable.i18n.ts | 4 + src/upstreams/PriceSheetTable.tsx | 92 ++- src/upstreams/ProxyDialog.i18n.tsx | 2 + src/upstreams/ProxyDialog.tsx | 36 +- src/upstreams/ProxyTable.i18n.ts | 4 + src/upstreams/ProxyTable.tsx | 78 +- src/upstreams/QuotaBar.tsx | 34 + src/upstreams/ServicePicker.i18n.ts | 14 + src/upstreams/ServicePicker.tsx | 114 +++ src/upstreams/Sparkline.tsx | 53 ++ src/upstreams/TestDialogs.i18n.ts | 4 +- src/upstreams/TestDialogs.tsx | 116 +-- src/upstreams/UpstreamDialog.tsx | 56 +- src/upstreams/UpstreamTable.i18n.ts | 39 + src/upstreams/UpstreamTable.tsx | 468 +++++++---- ...amsPage.i18n.ts => UpstreamsPage.i18n.tsx} | 48 +- src/upstreams/UpstreamsPage.tsx | 727 ++++++++++-------- src/upstreams/ZaiLoginDialog.tsx | 42 +- src/upstreams/api.ts | 12 +- src/upstreams/data.ts | 231 ++++++ src/upstreams/parts.tsx | 287 +++++-- 35 files changed, 1990 insertions(+), 941 deletions(-) create mode 100644 src/upstreams/QuotaBar.tsx create mode 100644 src/upstreams/ServicePicker.i18n.ts create mode 100644 src/upstreams/ServicePicker.tsx create mode 100644 src/upstreams/Sparkline.tsx rename src/upstreams/{UpstreamsPage.i18n.ts => UpstreamsPage.i18n.tsx} (64%) create mode 100644 src/upstreams/data.ts diff --git a/src-tauri/src/upstreams.rs b/src-tauri/src/upstreams.rs index f2c33e45..c1605359 100644 --- a/src-tauri/src/upstreams.rs +++ b/src-tauri/src/upstreams.rs @@ -1,4 +1,4 @@ -//! 上游页的汇总:一行上的费用、延迟、额度一起取。 +//! 上游页的汇总:一行上的费用、延迟、额度、走势一起取。 //! //! 上游、代理、价目表的增删改与检测都是直接转发的端点,走 `crate::call`。 @@ -7,7 +7,8 @@ use tw_api::ep; use crate::AppState; use crate::error::Out; -/// 上游列表那几列统计:24 小时的请求与费用、首字节耗时、订阅额度。 +/// 上游列表那几列统计:一段时间里的请求与费用、首字节耗时、订阅额度,以及同一段 +/// 时间按上游分格的请求数(每一行的走势)。 /// /// **一起取。**列表上它们是同一行的几格,分几次 invoke 会让一行数字分几次 /// 跳变。拿不到的就是空的 —— 存储层不在的时候网关照常转发,列表也该照常打开。 @@ -16,12 +17,20 @@ pub struct UpstreamStats { costs: Vec, latency: Vec, quotas: Vec, + /// 按界面给的格宽、按上游分格。**稀疏的** —— 没有请求的格子不在里面,由界面补 + buckets: Vec, } +/// 格宽的下限。和概览同一条:再细就是把噪声当细节,而这一条查询还要乘上上游个数 +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 { let c = &state.control; Ok(UpstreamStats { @@ -41,6 +50,18 @@ pub async fn upstream_stats( .await .unwrap_or_default(), quotas: c.call::(&[], &()).await.unwrap_or_default(), + buckets: c + .call::( + &[], + &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(), }) } diff --git a/src/App.tsx b/src/App.tsx index a2f454b7..1cf202a4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1046,7 +1046,7 @@ function Shell({ first }: { first: boolean }) { ) ) : tab === "upstreams" ? ( ov ? ( - + ) : ( skeleton ) diff --git a/src/upstreams/BillingSection.tsx b/src/upstreams/BillingSection.tsx index 04e06e06..6a2930ad 100644 --- a/src/upstreams/BillingSection.tsx +++ b/src/upstreams/BillingSection.tsx @@ -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"; /** 「新建价目表…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */ @@ -97,7 +97,7 @@ export function BillingSection({ {perToken && sheet && (
{t.usedBy} - +
{loading && !usage ? ( -

{t.loading}

+
+ {[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)}`}
- +
); })}
- ) : ( + ) : usage ? (

{t.noQuota}

- )} + ) : null}
@@ -185,7 +199,7 @@ export function ChatgptAccountSection({

{t.creditsNote}

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

{t.noCredits}

) : (
    @@ -216,8 +230,7 @@ export function ChatgptAccountSection({ )} - {outcome &&

    {codes[outcome] ?? outcome}

    } - {error &&

    {error}

    } + !o && setConfirming(null)}> @@ -232,7 +245,16 @@ export function ChatgptAccountSection({ {common.cancel} - confirming && void use(confirming)} disabled={using}> + { + // 用完再关:结果和原因要等上游答复 + e.preventDefault(); + if (confirming) void use(confirming); + }} + > + {using && } {t.use} diff --git a/src/upstreams/ChatgptLoginDialog.tsx b/src/upstreams/ChatgptLoginDialog.tsx index df19bcd4..46a14f7e 100644 --- a/src/upstreams/ChatgptLoginDialog.tsx +++ b/src/upstreams/ChatgptLoginDialog.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; -import { CircleAlertIcon, CopyIcon, ExternalLinkIcon, SmartphoneIcon } from "lucide-react"; +import { CopyIcon, ExternalLinkIcon, SmartphoneIcon } from "lucide-react"; import { listen } from "@tauri-apps/api/event"; -import { Alert, AlertDescription, AlertTitle } from "@/ui/alert"; +import { Banner } from "@/ui/banner"; import { Button } from "@/ui/button"; import { Checkbox } from "@/ui/checkbox"; import { @@ -15,14 +15,14 @@ import { import { Field, FieldLabel } from "@/ui/field"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; -import { Spinner } from "@/ui/spinner"; +import { StatusLabel } from "@/ui/status-dot"; import type { ChatgptLoginMode, ChatgptLoginStatus, CoreEvent, Overview } from "@/types"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { chatgptLoginText } from "./ChatgptLoginDialog.i18n"; import { coreText, errorText, proxyKindLabel, shortUrl } from "./labels"; -import { FormItem } from "./parts"; +import { DialogError, FormItem } from "./parts"; import { freeName } from "./upstreamForm"; import { useSystemProxyLabel } from "@/connection/Remote"; import { useRemote } from "@/connection/useRemote"; @@ -74,7 +74,9 @@ export function ChatgptLoginDialog({ // 重新登录的人此前已经看过并同意了这些,不再拦一次 const [understood, setUnderstood] = useState(relogin != null); const [phase, setPhase] = useState({ at: "form" }); - const [busy, setBusy] = useState(false); + /** 正在发起哪一种登录。两条路各有一个按钮,转圈的是被点的那个 */ + const [starting, setStarting] = useState(null); + const busy = starting !== null; const [error, setError] = useState(null); const [copied, setCopied] = useState(false); // 卸载之后不要再写状态:等待期间用户可能直接关掉对话框。 @@ -132,7 +134,7 @@ export function ChatgptLoginDialog({ }, [waiting]); async function start(mode: ChatgptLoginMode) { - setBusy(true); + setStarting(mode); setError(null); try { const login = await api.startChatgptLogin(name.trim(), proxy, mode); @@ -150,7 +152,7 @@ export function ChatgptLoginDialog({ } catch (e) { setError(errorText(e)); } finally { - setBusy(false); + setStarting(null); } } @@ -170,7 +172,8 @@ export function ChatgptLoginDialog({ return ( !o && void cancel()}> - + {/* 点到外面不关:登录进行中时关掉就是放弃这一次登录。Esc、×、取消照常 */} + e.preventDefault()}> {relogin ? t.reloginTitle : t.title} @@ -181,18 +184,14 @@ export function ChatgptLoginDialog({ {phase.at === "form" && (
    {!relogin && ( - - - {t.noticeTitle} - +
    • {t.noticeOfficial}
    • {t.noticeHonest}
    • {t.noticeStorage}
    • {t.noticeRevoke}
    -
    -
    + )}
    @@ -245,10 +244,7 @@ export function ChatgptLoginDialog({ {phase.at === "browser" && (
    -
    - - {t.browserWaiting} -
    + {t.browserWaiting}

    {t.browserHint}

    -
    - - {t.deviceWaiting} -
    + {t.deviceWaiting} {/* Codex 也有这一句:拿着别人给的码去输,等于把自己的账号授权给对方 */}

    {t.deviceWarning}

    @@ -309,7 +302,7 @@ export function ChatgptLoginDialog({
    )} - {error &&

    {error}

    } + {phase.at === "done" ? ( @@ -322,8 +315,8 @@ export function ChatgptLoginDialog({ {phase.at === "form" && ( <> {remote ? ( - ) : ( @@ -332,13 +325,14 @@ export function ChatgptLoginDialog({ - diff --git a/src/upstreams/ConnectionSection.i18n.ts b/src/upstreams/ConnectionSection.i18n.ts index 644a8627..53d8f2c6 100644 --- a/src/upstreams/ConnectionSection.i18n.ts +++ b/src/upstreams/ConnectionSection.i18n.ts @@ -11,8 +11,6 @@ export const connectionSectionText = messages( autoUndetected: "自动识别(未识别,按原格式转发)", protocol: "接口协议", service: "服务类型", - chatgpt: "ChatGPT 账号(登录)", - zai: "Z.ai / BigModel 账号(登录)", name: "名称", namePlaceholder: "例如 relay-hk", baseUrl: "接口地址", @@ -29,6 +27,7 @@ export const connectionSectionText = messages( failWithError: "返回错误", fallBackDirect: "改为直连", check: "检测连接", + checking: "检测中", checkNote: "验证地址与凭据,并获取模型列表。不产生费用。", keyPlaceholder: "sk-…,或 ${变量名}", apiKey: "API 密钥", @@ -55,8 +54,6 @@ export const connectionSectionText = messages( autoUndetected: "Auto-detect (not detected, forwarded as is)", protocol: "Protocol", service: "Service", - chatgpt: "ChatGPT account (sign in)", - zai: "Z.ai / BigModel account (sign in)", name: "Name", namePlaceholder: "e.g. relay-hk", baseUrl: "Base URL", @@ -73,6 +70,7 @@ export const connectionSectionText = messages( failWithError: "Return an error", fallBackDirect: "Connect directly", check: "Check connection", + checking: "Checking", checkNote: "Verifies the URL and credentials and fetches the model list. No cost is incurred.", keyPlaceholder: "sk-…, or ${NAME}", apiKey: "API key", diff --git a/src/upstreams/ConnectionSection.tsx b/src/upstreams/ConnectionSection.tsx index 37fdbc5f..90e0a541 100644 --- a/src/upstreams/ConnectionSection.tsx +++ b/src/upstreams/ConnectionSection.tsx @@ -2,7 +2,9 @@ import { CircleAlertIcon, CircleCheckIcon, PlugIcon } from "lucide-react"; import { Button } from "@/ui/button"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; -import { Spinner } from "@/ui/spinner"; +import { Segmented } from "@/ui/segmented"; +import { StatusLabel } from "@/ui/status-dot"; +import { cn } from "@/lib/utils"; import { useText } from "@/i18n"; import type { Overview, ProviderPreview, ProviderTestResult, ProviderView } from "@/types"; import { connectionSectionText } from "./ConnectionSection.i18n"; @@ -18,8 +20,9 @@ import { protocolLabel, proxyKindLabel, } from "./labels"; -import { FormItem, Note, Segmented } from "./parts"; -import { CHATGPT, CUSTOM, PRESETS, ZAI, nameFromUrl, presetById } from "./presets"; +import { FormItem, Note } from "./parts"; +import { CHATGPT, ZAI, nameFromUrl, presetById } from "./presets"; +import { ServicePicker } from "./ServicePicker"; import { describeModelList, freeName, type UpstreamForm } from "./upstreamForm"; /** 「新建代理…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */ @@ -98,21 +101,7 @@ export function ConnectionSection({ ) : ( - pickPreset(e.target.value)} - > - {CUSTOM.label} - {t.chatgpt} - {t.zai} - {PRESETS.map((p) => ( - - {p.label} - - ))} - + )} @@ -226,13 +215,19 @@ export function ConnectionSection({
    - - {t.checkNote} + {testing ? ( + + {t.checking} + + ) : ( + {t.checkNote} + )}
    - {test && } + {test && !testing && }
    ); @@ -423,15 +418,15 @@ function OAuth({ } /** 「连接正常 · 认证通过 · 响应 312 ms · 经由 hk-socks · 发现 6 个模型」 */ -export function TestLine({ result }: { result: ProviderTestResult }) { +export function TestLine({ result, bordered = true }: { result: ProviderTestResult; bordered?: boolean }) { const t = useText(connectionSectionText); if (!result.ok) { return ( -
    +
    {t.failed} - {result.error && {coreText(result.error)}} + {result.error &&

    {coreText(result.error)}

    }
    ); @@ -443,10 +438,10 @@ export function TestLine({ result }: { result: ProviderTestResult }) { describeModelList(result.models), ].filter(Boolean); return ( -
    +
    {t.ok} - {parts.join(" · ")} + {parts.join(" · ")}
    ); } diff --git a/src/upstreams/DeleteDialog.tsx b/src/upstreams/DeleteDialog.tsx index 30ee1e7d..0bf0a698 100644 --- a/src/upstreams/DeleteDialog.tsx +++ b/src/upstreams/DeleteDialog.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { ArrowRightIcon, LayersIcon, SplitIcon } from "lucide-react"; import { AlertDialog, + AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, @@ -16,7 +17,7 @@ import { commonText } from "@/i18n/common.i18n"; import type { ReferenceView } from "@/types"; import { deleteDialogText } from "./DeleteDialog.i18n"; import { errorText } from "./labels"; -import { Note } from "./parts"; +import { DialogError } from "./parts"; /** 引用了要删的东西的一处 */ export type Referrer = @@ -27,6 +28,8 @@ export type Referrer = /** * 删除确认。**还被引用时不给删除按钮** —— 标题直接说「无法删除」,列出是谁 * 在用,每一处都能跳过去解除。 + * + * 删除失败时对话框留着,原因写在里面(`DialogError`),可以直接再点一次。 */ export function DeleteDialog({ what, @@ -94,14 +97,23 @@ export function DeleteDialog({ ))}
    )} - {error && {error}} + {blocked ? c.close : c.cancel} {!blocked && ( - + )} diff --git a/src/upstreams/ModelsPanel.i18n.ts b/src/upstreams/ModelsPanel.i18n.ts index 3940437a..fea24806 100644 --- a/src/upstreams/ModelsPanel.i18n.ts +++ b/src/upstreams/ModelsPanel.i18n.ts @@ -4,7 +4,6 @@ export const modelsPanelText = messages( { title: "模型", refetch: "重新获取模型列表", - loading: "正在读取", fetching: "正在获取模型列表", failed: "获取失败", unreachable: "未能连接上游。", @@ -32,7 +31,6 @@ export const modelsPanelText = messages( { title: "Models", refetch: "Fetch the model list again", - loading: "Loading", fetching: "Fetching the model list", failed: "Fetch failed", unreachable: "Could not reach the upstream.", diff --git a/src/upstreams/ModelsPanel.tsx b/src/upstreams/ModelsPanel.tsx index e191c1d1..4d8470ce 100644 --- a/src/upstreams/ModelsPanel.tsx +++ b/src/upstreams/ModelsPanel.tsx @@ -1,9 +1,12 @@ -import { type ReactNode, useEffect, useMemo, useState } from "react"; +import { type ReactNode, useMemo, useState } from "react"; import { ChevronRightIcon, CircleAlertIcon, RefreshCwIcon, SearchIcon } from "lucide-react"; import { cn } from "@/lib/utils"; +import { useResource } from "@/lib/resource"; import { Button } from "@/ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "@/ui/input-group"; +import { Skeleton } from "@/ui/skeleton"; import { Spinner } from "@/ui/spinner"; +import { StatusLabel } from "@/ui/status-dot"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import type { ModelRow, ProviderModelsView, ProviderView } from "@/types"; @@ -16,10 +19,14 @@ const FILTER_FROM = 10; /** * 点开「模型」一格看到的东西:这一家有哪些模型,是怎么知道的,没拿到的话 - * 为什么、该做什么。 + * 原因和下一步。 * * **只读,改动在编辑对话框里做** —— 启用范围、手动清单都要一次保存一个 * 配置版本,和上游其余设置走同一条路。这里给的是去那儿的入口。 + * + * 清单按上游缓存(`upstream-models:<名字>`):再点开一次先画上一次的,后台再读。 + * 概览里这一家的获取状态一变(开始问了、问完了)就重读 —— 开着面板等它问完, + * 也能看到结果。读的是 core 记下的答案,不联网。 */ export function ModelsPanel({ p, @@ -27,48 +34,34 @@ export function ModelsPanel({ onEdit, }: { p: ProviderView; - /** 按量计费:列出单价。别的计费方式不按单价算钱,列了也没意义 */ + /** 按量计费:列出单价。别的计费方式不按单价算费用,列了也没意义 */ perToken: boolean; /** 打开编辑对话框的「模型」一节 */ onEdit: () => void; }) { const t = useText(modelsPanelText); const c = useText(commonText); - const [view, setView] = useState(null); - const [failed, setFailed] = useState(null); + const r = useResource(`upstream-models:${p.name}`, () => api.providerModels(p.name), { + deps: [p.model_checked_at_ms, p.model_fetching, p.model_count], + }); const [refreshing, setRefreshing] = useState(false); + const [refreshError, setRefreshError] = useState(null); const [query, setQuery] = useState(""); const [showOff, setShowOff] = useState(false); - // 概览里这一家的获取状态一变(开始问了、问完了)就重读:打开着面板等它问完, - // 也能看到结果。读的是 core 记下的答案,不联网 - useEffect(() => { - let alive = true; - api - .providerModels(p.name) - .then((v) => { - if (!alive) return; - setView(v); - setFailed(null); - }) - .catch((e) => alive && setFailed(errorText(e))); - return () => { - alive = false; - }; - }, [p.name, p.model_checked_at_ms, p.model_fetching, p.model_count]); - async function refresh() { setRefreshing(true); + setRefreshError(null); try { - setView(await api.refreshProviderModels(p.name)); - setFailed(null); + r.mutate(await api.refreshProviderModels(p.name)); } catch (e) { - setFailed(errorText(e)); + setRefreshError(errorText(e)); } finally { setRefreshing(false); } } + const view = r.data; const fetching = refreshing || (view?.fetching ?? p.model_fetching); const models = view?.models ?? []; const q = query.trim().toLowerCase(); @@ -82,19 +75,23 @@ export function ModelsPanel({ const source = view?.source ?? p.model_source; const error = view?.error ?? p.model_error; const why = error ? coreText(error) : null; + const readError = refreshError ?? (r.error !== undefined && !view ? errorText(r.error) : null); return (
    {t.title}
    -
    {summary(source, models.length, on.length, view)}
    +
    + {view ? summary(source, models.length, on.length, view) : } +
    - {failed ? ( - + {readError ? ( + void r.reload()}> + {c.retry} + + } + /> ) : !view ? ( - + ) : source === "none" && (status === "pending" || fetching) ? ( - +
    + + {t.fetching} + +
    ) : ( <> - {/* 没从上游拿到清单:说为什么,指出该做什么。手动清单顶上时照样说 */} + {/* 没从上游拿到清单:说原因,指出下一步。手动清单顶上时照样说 */} {status === "failed" && ( -
    )} -
    +
    {shownOn.map((m) => ( ))} {off.length > 0 && ( <> - + {(showOff || q !== "") && shownOff.map((m) => )} @@ -195,8 +207,7 @@ export function ModelsPanel({ } /** 标题下那一行:多少个、从哪儿来、什么时候问的 */ -function summary(source: string, total: number, enabled: number, view: ProviderModelsView | null): string { - if (!view) return ""; +function summary(source: string, total: number, enabled: number, view: ProviderModelsView): string { const t = textOf(modelsPanelText); const count = enabled === total ? t.countAll(total) : t.countSome(total, enabled); if (source === "discovered") { @@ -224,26 +235,28 @@ function Row({ m, perToken }: { m: ModelRow; perToken: boolean }) { {m.id} {price && ( - + {price} )} - + {m.context_window ? contextWindow(m.context_window) : ""}
    ); } -function Waiting({ text }: { text: string }) { +/** 清单还没读到:几行和模型行一样高的占位 */ +function RowsSkeleton() { return ( -

    - - {text} -

    +
    + {[72, 56, 64, 44].map((w, i) => ( +
    + + +
    + ))} +
    ); } @@ -261,7 +274,7 @@ function Problem({ muted?: boolean; }) { return ( -
    +
    {!muted && }
    diff --git a/src/upstreams/ModelsSection.tsx b/src/upstreams/ModelsSection.tsx index c6f69968..3c6a2e1f 100644 --- a/src/upstreams/ModelsSection.tsx +++ b/src/upstreams/ModelsSection.tsx @@ -4,7 +4,10 @@ import { Badge } from "@/ui/badge"; import { Button } from "@/ui/button"; import { Checkbox } from "@/ui/checkbox"; import { InputGroup, InputGroupAddon, InputGroupInput } from "@/ui/input-group"; +import { Segmented } from "@/ui/segmented"; import { Spinner } from "@/ui/spinner"; +import { TableSkeleton } from "@/ui/states"; +import { StatusLabel } from "@/ui/status-dot"; import { Table, TableBody, @@ -20,7 +23,7 @@ import { coreText } from "@/i18n/core.i18n"; import { globMatch } from "./glob"; import { contextWindow, modelSourceLabel } from "./labels"; import { modelsSectionText } from "./ModelsSection.i18n"; -import { Boxed, FormItem, Note, Segmented } from "./parts"; +import { Boxed, FormItem, Note } from "./parts"; import type { UpstreamForm } from "./upstreamForm"; /** 这家上游有哪些模型,以及是怎么知道的 */ @@ -128,23 +131,24 @@ export function ModelsSection({ )} {catalog && (listed || models.length > 0) && ( - + {t.count(models.length)} {listed && catalog.checkedAtMs ? ` · ${t.fetchedAt(clock(catalog.checkedAtMs))}` : ""} )}
    -
    - {loading || waiting ? ( -

    - + {waiting ? ( + {t.fetching} -

    + + ) : loading ? ( + ) : !catalog ? ( {t.notFetched} ) : ( @@ -204,7 +208,7 @@ export function ModelsSection({ />
    - + {t.enabled(enabled.length, models.length)}
    @@ -240,7 +244,7 @@ export function ModelsSection({ {m} - + {contextWindow(price?.max_input_tokens)} {perToken && ( diff --git a/src/upstreams/PriceSheetDialog.i18n.ts b/src/upstreams/PriceSheetDialog.i18n.ts index 46f69365..a210eac4 100644 --- a/src/upstreams/PriceSheetDialog.i18n.ts +++ b/src/upstreams/PriceSheetDialog.i18n.ts @@ -12,7 +12,6 @@ export const priceSheetDialogText = messages( draftName: "草稿", multiplierPositive: "倍率须大于 0", enterName: "填写名称", - loading: "正在读取价目表", name: "名称", basis: "定价依据", multiplier: "倍率", @@ -67,7 +66,6 @@ export const priceSheetDialogText = messages( draftName: "Draft", multiplierPositive: "Multiplier must be greater than 0", enterName: "Enter a name", - loading: "Loading price sheet", name: "Name", basis: "Based on", multiplier: "Multiplier", diff --git a/src/upstreams/PriceSheetDialog.tsx b/src/upstreams/PriceSheetDialog.tsx index 5b7f588b..388d30ce 100644 --- a/src/upstreams/PriceSheetDialog.tsx +++ b/src/upstreams/PriceSheetDialog.tsx @@ -1,6 +1,5 @@ import { Fragment, useEffect, useMemo, useState } from "react"; import { ChevronRightIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon, XIcon } from "lucide-react"; -import { Alert, AlertDescription } from "@/ui/alert"; import { AlertDialog, AlertDialogAction, @@ -13,6 +12,7 @@ import { } from "@/ui/alert-dialog"; import { Badge } from "@/ui/badge"; import { Button } from "@/ui/button"; +import { Count } from "@/ui/count"; import { Dialog, DialogContent, @@ -23,7 +23,10 @@ import { } from "@/ui/dialog"; import { Input } from "@/ui/input"; import { InputGroup, InputGroupAddon, InputGroupInput } from "@/ui/input-group"; +import { Logo, upstreamGlyph } from "@/ui/logos"; +import { Segmented } from "@/ui/segmented"; import { Spinner } from "@/ui/spinner"; +import { TableSkeleton } from "@/ui/states"; import { Table, TableBody, @@ -32,13 +35,14 @@ import { TableHeader, TableRow, } from "@/ui/table"; +import { Toggle } from "@/ui/toggle"; import type { Overview, PriceFields, PriceSheetInput, ResolvedPrice, SheetRef } from "@/types"; import { cn } from "@/lib/utils"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { PRICE_COLUMNS, errorText, perMillion, priceSourceLabel } from "./labels"; -import { Boxed, FormItem, Note, Segmented } from "./parts"; +import { Boxed, DialogError, FormItem, Note } from "./parts"; import { priceSheetDialogText } from "./PriceSheetDialog.i18n"; import { defaultSheetUsers } from "./PriceSheetTable"; @@ -321,16 +325,17 @@ export function PriceSheetDialog({ } } + const [deleting, setDeleting] = useState(false); async function remove() { if (mode.kind !== "edit") return; - setSaving(true); + setDeleting(true); try { await api.deletePriceSheet(mode.name, configVersion); onDeleted?.(); } catch (e) { setError(errorText(e)); } finally { - setSaving(false); + setDeleting(false); setConfirmDelete(false); } } @@ -347,17 +352,18 @@ export function PriceSheetDialog({ return ( !open && onClose()}> - + {/* 能改的时候点到外面不关:改了一半的价格不该因为一次误点丢掉 */} + e.preventDefault()} + > {title} {readOnly ? t.descDefault : t.descCustom} {loading ? ( -

    - - {t.loading} -

    + ) : (
    {!readOnly && ( @@ -371,7 +377,7 @@ export function PriceSheetDialog({ setMultiplier(e.target.value)} @@ -449,7 +455,7 @@ export function PriceSheetDialog({
    )} - {draftError && {draftError}} + @@ -475,20 +481,26 @@ export function PriceSheetDialog({ {o ? ( - {r.model} - + ) : ( - + {r.model} {readOnly && !r.price && ( @@ -499,7 +511,7 @@ export function PriceSheetDialog({ )} {PRICE_COLUMNS.map((c) => ( - + {o ? ( -
    +
    {t.longContextNote} {o.input_above_200k == null ? ( + ); })}
    @@ -643,11 +653,7 @@ export function PriceSheetDialog({
    )} - {error && ( - - {error} - - )} + {mode.kind === "edit" && ( @@ -679,8 +685,7 @@ export function PriceSheetDialog({ - @@ -695,7 +700,17 @@ export function PriceSheetDialog({ {common.cancel} - + { + // 删完由调用方关掉整个对话框;失败时原因写在外面这张对话框里 + e.preventDefault(); + void remove(); + }} + > + {deleting && } {common.delete} @@ -706,10 +721,6 @@ export function PriceSheetDialog({ ); } -function Count({ n }: { n: number }) { - return {n.toLocaleString()}; -} - /** 表格里的单价输入。失焦前保留用户打的原样(「0.」这种中间态) */ function PriceInput({ value, @@ -725,7 +736,7 @@ function PriceInput({ setText(String(value))} onBlur={() => setText(null)} diff --git a/src/upstreams/PriceSheetTable.i18n.ts b/src/upstreams/PriceSheetTable.i18n.ts index d536eed1..a46e3776 100644 --- a/src/upstreams/PriceSheetTable.i18n.ts +++ b/src/upstreams/PriceSheetTable.i18n.ts @@ -8,10 +8,12 @@ export const priceSheetTableText = messages( multiplier: "倍率", overrides: "模型覆盖", usedBy: "使用上游", + actionsColumn: "操作", defaultSheet: "默认价目表", litellm: "LiteLLM 公开价格", notLoaded: "未加载", dataInfo: (date: string, models: number) => `数据日期 ${date} · ${models.toLocaleString()} 个模型`, + lastChecked: (at: string) => `最近检查 ${at}`, notUsed: "未被使用", defaultActions: "默认价目表的操作", actions: (name: string) => `${name} 的操作`, @@ -27,11 +29,13 @@ export const priceSheetTableText = messages( multiplier: "Multiplier", overrides: "Model overrides", usedBy: "Used by", + actionsColumn: "Actions", defaultSheet: "Default price sheet", litellm: "LiteLLM public prices", notLoaded: "Not loaded", dataInfo: (date: string, models: number) => `Data as of ${date} · ${models.toLocaleString()} ${models === 1 ? "model" : "models"}`, + lastChecked: (at: string) => `last checked ${at}`, notUsed: "Not in use", defaultActions: "Actions for the default price sheet", actions: (name: string) => `Actions for ${name}`, diff --git a/src/upstreams/PriceSheetTable.tsx b/src/upstreams/PriceSheetTable.tsx index addf8c86..b764e628 100644 --- a/src/upstreams/PriceSheetTable.tsx +++ b/src/upstreams/PriceSheetTable.tsx @@ -1,16 +1,13 @@ +import type { Resource } from "@/lib/resource"; +import { rowMotion, usePresentList } from "@/ui/motion"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/ui/table"; +import { Skeleton } from "@/ui/skeleton"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; +import { when } from "@/format"; import type { Overview, PricingStatus } from "@/types"; import { useText } from "@/i18n"; import { formatMultiplier } from "./labels"; -import { NameChips } from "./parts"; +import { UpstreamChips, keepInRow, openRow } from "./parts"; import { priceSheetTableText } from "./PriceSheetTable.i18n"; /** 按默认价目表计价的上游:没选价目表、而且按量计费 */ @@ -20,6 +17,10 @@ export function defaultSheetUsers(ov: Overview): string[] { .map((p) => p.name); } +/** + * 价目表列表:第一行是默认价目表(联网拉取的公开价格,只读),其后是自定义价目表。 + * 单击一行打开它:默认价目表是查看,自定义的是编辑。 + */ export function PriceSheetTable({ ov, status, @@ -29,76 +30,85 @@ export function PriceSheetTable({ onRemove, }: { ov: Overview; - status: PricingStatus | null; + status: Resource; onViewDefault: () => void; onEdit: (name: string) => void; onDuplicate: (name: string) => void; onRemove: (name: string) => void; }) { const t = useText(priceSheetTableText); - const defaultItems: MenuItems = [ - { kind: "item", label: t.viewPrices, onSelect: onViewDefault }, - ]; + const defaultItems: MenuItems = [{ kind: "item", label: t.viewPrices, onSelect: onViewDefault }]; + const shown = usePresentList(ov.price_sheets, (s) => s.name); + const s = status.data; return (
    - + {t.name} {t.basis} {t.multiplier} {t.overrides} {t.usedBy} - + + {t.actionsColumn} + - + {t.defaultSheet} - + {/* 这一格的小字最长(数据日期、模型数、最近检查):窗口窄时折行,不把整张表撑出横向滚动 */} + {t.litellm} - {status && ( -
    - {status.source === "empty" ? t.notLoaded : t.dataInfo(status.date, status.models)} -
    - )} +
    + {s ? ( + s.source === "empty" ? ( + t.notLoaded + ) : ( + <> + {t.dataInfo(s.date, s.models)} + {s.checked_at_ms != null && ` · ${t.lastChecked(when(s.checked_at_ms))}`} + + ) + ) : status.loading ? ( + + ) : ( + "—" + )} +
    — — - + - +
    - {ov.price_sheets.map((s) => { + {shown.map(({ item: sheet, key, presence }) => { const items: MenuItems = [ - { kind: "item", label: t.edit, onSelect: () => onEdit(s.name) }, - { kind: "item", label: t.duplicate, onSelect: () => onDuplicate(s.name) }, + { kind: "item", label: t.edit, onSelect: () => onEdit(sheet.name) }, + { kind: "item", label: t.duplicate, onSelect: () => onDuplicate(sheet.name) }, { kind: "sep" }, - { - kind: "item", - label: t.delete, - onSelect: () => onRemove(s.name), - danger: true, - }, + { kind: "item", label: t.delete, onSelect: () => onRemove(sheet.name), danger: true }, ]; return ( - - onEdit(s.name)} className="cursor-default"> - {s.name} + + onEdit(sheet.name), rowMotion(presence))}> + {sheet.name} {t.defaultSheet} - × {formatMultiplier(s.multiplier)} - {t.overrideCount(s.overrides)} + × {formatMultiplier(sheet.multiplier)} + {t.overrideCount(sheet.overrides)} - + - - + + diff --git a/src/upstreams/ProxyDialog.i18n.tsx b/src/upstreams/ProxyDialog.i18n.tsx index f2284c14..20d0c453 100644 --- a/src/upstreams/ProxyDialog.i18n.tsx +++ b/src/upstreams/ProxyDialog.i18n.tsx @@ -24,6 +24,7 @@ export const proxyDialogText = messages( user: "用户名", pass: "密码", check: "检测代理", + checking: "检测中", ok: (auth: boolean, ms: number) => `连接正常 · ${auth ? "认证通过 · " : ""}响应 ${ms.toLocaleString()} ms`, checkHint: "完成代理握手与认证。不产生费用。", @@ -51,6 +52,7 @@ export const proxyDialogText = messages( user: "Username", pass: "Password", check: "Check proxy", + checking: "Checking", ok: (auth: boolean, ms: number) => `Connected · ${auth ? "authenticated · " : ""}responded in ${ms.toLocaleString()} ms`, checkHint: "Completes the proxy handshake and authentication. Incurs no cost.", diff --git a/src/upstreams/ProxyDialog.tsx b/src/upstreams/ProxyDialog.tsx index baa3cb7c..7c23e91b 100644 --- a/src/upstreams/ProxyDialog.tsx +++ b/src/upstreams/ProxyDialog.tsx @@ -1,6 +1,5 @@ import { useState } from "react"; import { ActivityIcon } from "lucide-react"; -import { Alert, AlertDescription } from "@/ui/alert"; import { Button } from "@/ui/button"; import { Dialog, @@ -11,14 +10,15 @@ import { DialogTitle, } from "@/ui/dialog"; import { Input } from "@/ui/input"; -import { Spinner } from "@/ui/spinner"; +import { Segmented } from "@/ui/segmented"; +import { StatusLabel } from "@/ui/status-dot"; import { Switch } from "@/ui/switch"; import type { L1Result, Overview, ProxyAuthInput, ProxyInput, ProxyView } from "@/types"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { PROXY_KINDS, errorText, l1ErrorText } from "./labels"; -import { FormItem, Segmented, StatusDot } from "./parts"; +import { DialogError, FormItem } from "./parts"; import { proxyDialogText } from "./ProxyDialog.i18n"; import { plain } from "@/i18n/core.i18n"; @@ -110,7 +110,8 @@ export function ProxyDialog({ return ( !open && onClose()}> - + {/* 点到对话框外面不关:填了一半的表单不该因为一次误点丢掉。Esc、×、取消照常 */} + e.preventDefault()}> {editing ? t.editTitle : t.createTitle} @@ -202,15 +203,23 @@ export function ProxyDialog({ ))}
    - - {result ? ( + {testing ? ( + + {t.checking} + + ) : result ? ( result.ok ? ( - {t.ok(auth, result.total_ms)} + + {t.ok(auth, result.total_ms)} + ) : ( - {l1ErrorText(result)} + + {l1ErrorText(result)} + ) ) : ( {t.checkHint} @@ -218,19 +227,14 @@ export function ProxyDialog({
    - {error && ( - - {error} - - )} + {missing && {missing}} - diff --git a/src/upstreams/ProxyTable.i18n.ts b/src/upstreams/ProxyTable.i18n.ts index 60f53b0f..2f98ba97 100644 --- a/src/upstreams/ProxyTable.i18n.ts +++ b/src/upstreams/ProxyTable.i18n.ts @@ -8,6 +8,7 @@ export const proxyTableText = messages( auth: "认证", usedBy: "使用上游", connectivity: "连通性", + actionsColumn: "操作", edit: "编辑…", check: "检测代理", delete: "删除…", @@ -17,6 +18,7 @@ export const proxyTableText = messages( notChecked: "未检测", checking: "检测中", unreachable: "无法连接", + ms: (n: number) => `${n.toLocaleString()} ms`, }, { name: "Name", @@ -25,6 +27,7 @@ export const proxyTableText = messages( auth: "Authentication", usedBy: "Used by", connectivity: "Connectivity", + actionsColumn: "Actions", edit: "Edit…", check: "Check proxy", delete: "Delete…", @@ -34,5 +37,6 @@ export const proxyTableText = messages( notChecked: "Not checked", checking: "Checking", unreachable: "Unreachable", + ms: (n: number) => `${n.toLocaleString()} ms`, }, ); diff --git a/src/upstreams/ProxyTable.tsx b/src/upstreams/ProxyTable.tsx index bdb31cf5..40b7a484 100644 --- a/src/upstreams/ProxyTable.tsx +++ b/src/upstreams/ProxyTable.tsx @@ -1,31 +1,32 @@ +import { rowMotion, usePresentList } from "@/ui/motion"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; -import { Spinner } from "@/ui/spinner"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/ui/table"; -import type { L1Result, ProxyFault, ProxyView } from "@/types"; +import { StatusLabel } from "@/ui/status-dot"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; +import { Tip } from "@/ui/tip"; +import type { L1Result, ProviderView, ProxyFault, ProxyView } from "@/types"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { l1ErrorText, proxyFaultText, proxyKindLabel } from "./labels"; -import { NameChips, StatusDot } from "./parts"; +import { UpstreamChips, keepInRow, openRow } from "./parts"; import { proxyTableText } from "./ProxyTable.i18n"; /** 一个代理最近一次手动检测的结果。`running` = 正在检测;`at` = 什么时候测完的 */ export type ProxyCheck = { running: true } | { running: false; result: L1Result; at: number }; +/** + * 出站代理列表。**只读**:单击一行(或 Enter)编辑,行尾按钮和右键是同一份操作。 + */ export function ProxyTable({ proxies, + providers, checks, onEdit, onTest, onRemove, }: { proxies: ProxyView[]; + /** 「使用上游」一列画标志要用 */ + providers: ProviderView[]; checks: Record; onEdit: (name: string) => void; onTest: (name: string) => void; @@ -33,21 +34,24 @@ export function ProxyTable({ }) { const t = useText(proxyTableText); const common = useText(commonText); + const shown = usePresentList(proxies, (x) => x.name); return (
    - + {t.name} {t.kind} {t.address} {t.auth} {t.usedBy} {t.connectivity} - + + {t.actionsColumn} + - {proxies.map((x) => { + {shown.map(({ item: x, key, presence }) => { const items: MenuItems = [ { kind: "item", label: t.edit, onSelect: () => onEdit(x.name) }, { kind: "item", label: t.check, onSelect: () => onTest(x.name) }, @@ -55,8 +59,8 @@ export function ProxyTable({ { kind: "item", label: t.delete, onSelect: () => onRemove(x.name), danger: true }, ]; return ( - - onEdit(x.name)} className="cursor-default"> + + onEdit(x.name), rowMotion(presence))}> {x.name} {proxyKindLabel(x.kind)} {x.addr} @@ -64,12 +68,12 @@ export function ProxyTable({ {x.has_auth ? t.userPass : common.none} - + - + @@ -95,27 +99,37 @@ function Connectivity({ const t = useText(proxyTableText); if (check?.running) { return ( - - + {t.checking} - + ); } if (fault && (!check || fault.at_ms > check.at)) { + return ; + } + if (!check) { return ( - - {t.unreachable} - + + {t.notChecked} + ); } - if (!check) return {t.notChecked}; const r = check.result; - if (!r.ok) { - return ( - - {t.unreachable} + if (!r.ok) return ; + return ( + + {t.ms(r.total_ms)} + + ); +} + +function Unreachable({ reason }: { reason: string }) { + const t = useText(proxyTableText); + return ( + + + {t.unreachable} - ); - } - return {r.total_ms.toLocaleString()} ms; + + ); } diff --git a/src/upstreams/QuotaBar.tsx b/src/upstreams/QuotaBar.tsx new file mode 100644 index 00000000..493c75ad --- /dev/null +++ b/src/upstreams/QuotaBar.tsx @@ -0,0 +1,34 @@ +import { cn } from "@/lib/utils"; + +/** 额度用到这个比例就算紧张(琥珀) */ +export const QUOTA_WARN = 80; +/** 用满:这个窗口里已经用完(红) */ +export const QUOTA_FULL = 100; + +/** + * 订阅额度的一根条:已用的比例。 + * + * 平时是灰的 —— 这个界面只在说状态时用颜色:用到八成变琥珀(紧张),用满变红 + * (用完)。宽度变化走过去(`motion-bar`),额度随请求涨的时候不跳。 + */ +export function QuotaBar({ percent, label, className }: { percent: number; label: string; className?: string }) { + const v = Math.max(0, Math.min(100, percent)); + return ( +
    +
    = QUOTA_FULL ? "bg-destructive" : percent >= QUOTA_WARN ? "bg-warning" : "bg-foreground/50", + )} + style={{ width: `${v}%` }} + /> +
    + ); +} diff --git a/src/upstreams/ServicePicker.i18n.ts b/src/upstreams/ServicePicker.i18n.ts new file mode 100644 index 00000000..d052d2be --- /dev/null +++ b/src/upstreams/ServicePicker.i18n.ts @@ -0,0 +1,14 @@ +import { messages } from "@/i18n"; + +export const servicePickerText = messages( + { + chatgpt: "ChatGPT 账号", + zai: "Z.ai / BigModel 账号", + signIn: "登录", + }, + { + chatgpt: "ChatGPT account", + zai: "Z.ai / BigModel account", + signIn: "Sign in", + }, +); diff --git a/src/upstreams/ServicePicker.tsx b/src/upstreams/ServicePicker.tsx new file mode 100644 index 00000000..ac3ce8fa --- /dev/null +++ b/src/upstreams/ServicePicker.tsx @@ -0,0 +1,114 @@ +import type { ReactNode } from "react"; +import { CheckIcon, ChevronDownIcon, ServerIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/ui/dropdown-menu"; +import { useText } from "@/i18n"; +import { VendorTile } from "./parts"; +import { CHATGPT, CUSTOM, PRESETS, ZAI, presetById, type Preset } from "./presets"; +import { servicePickerText } from "./ServicePicker.i18n"; + +/** + * 新建上游时的「服务类型」:一个带标志的下拉。 + * + * 原生下拉画不了图标,而这一栏恰恰是认标志比认字快的地方。**仍然是下拉**(选一个 + * 值),不是一排卡片:选中之后表单照常往下填,这一栏只占一个字段的位置。 + * + * 两个账号类(ChatGPT、Z.ai)不是预设:选中就改走登录,这张表单让位(调用方处理), + * 所以它们放在分隔线下面,标着「登录」。 + */ +export function ServicePicker({ + id, + value, + onPick, +}: { + id?: string; + /** 当前的预设 id;`custom` 是自定义 */ + value: string; + onPick: (id: string) => void; +}) { + const t = useText(servicePickerText); + const current = presetById(value); + return ( + + + + + + + {[CUSTOM, ...PRESETS].map((p) => ( + + + + + + + ); +} + +function Option({ + tile, + label, + note, + on = false, + onSelect, +}: { + tile: ReactNode; + label: string; + note?: string; + on?: boolean; + onSelect: () => void; +}) { + return ( + + {tile} + {label} + {note && {note}} + + + ); +} + +/** 预设的标志。自定义没有厂商,画一个服务器 */ +function PresetTile({ preset }: { preset: Preset }) { + if (preset.id === CUSTOM.id) { + return ( + + + + ); + } + return ; +} diff --git a/src/upstreams/Sparkline.tsx b/src/upstreams/Sparkline.tsx new file mode 100644 index 00000000..c0f5b1ac --- /dev/null +++ b/src/upstreams/Sparkline.tsx @@ -0,0 +1,53 @@ +import { cn } from "@/lib/utils"; +import { SLOTS, type Slot } from "./data"; + +/** 柱高多少像素。和两行字(次数、费用)叠起来差不多高 */ +const HEIGHT = 20; + +/** + * 纵轴的下限:一小时里只有一两个请求时,柱子不该顶满。 + * + * 每一行按自己的峰值画 —— 看的是这一家一天里的形状(白天成片、夜里没有),量 + * 有多大写在右边的数字里。但只有一个请求的那一家要是也顶满,看起来就和一小时 + * 几十个的那家一样忙。 + */ +const MIN_PEAK = 4; + +/** 一根柱子 3px、间隔 1px,一共 `SLOTS` 根。读到之前的占位按这个宽度画 */ +export const SPARKLINE_WIDTH = SLOTS * 4 - 1; + +/** + * 一天的走势:一小时一根柱子,最右边是现在这一小时。 + * + * **没有请求的小时也占一格**,画成贴底的一道细线 —— 跳过的话空档被挤没,看起来 + * 就是一直在用。失败的那一截画在柱顶、用红色:失败集中在哪个小时一眼看得见。 + * + * 用普通的块元素画,不用 SVG:高度变化要能走过渡(`motion-bar`),而 WebKit + * 对 SVG 几何属性的过渡支持不齐。 + */ +export function Sparkline({ slots, className }: { slots: Slot[]; className?: string }) { + const peak = Math.max(MIN_PEAK, ...slots.map((s) => s.requests)); + return ( +
    + {slots.map((s) => { + if (s.requests === 0) return
    ; + const h = Math.max(2, Math.round((s.requests / peak) * HEIGHT)); + const bad = s.failed > 0 ? Math.min(h, Math.max(2, Math.round((s.failed / s.requests) * h))) : 0; + return ( +
    + {bad > 0 &&
    } +
    + ); + })} +
    + ); +} diff --git a/src/upstreams/TestDialogs.i18n.ts b/src/upstreams/TestDialogs.i18n.ts index 7e9c4428..b198ebec 100644 --- a/src/upstreams/TestDialogs.i18n.ts +++ b/src/upstreams/TestDialogs.i18n.ts @@ -13,7 +13,6 @@ export const testDialogsText = messages( title: "链路测速", allUpstreams: "全部上游", desc: "测量 DNS 解析、TCP 握手、TLS 握手各阶段耗时;经代理时包含代理握手。不产生费用。", - testing: "正在测速", empty: "尚无上游。", via: "经由", stages: "各阶段", @@ -28,6 +27,7 @@ export const testDialogsText = messages( noModels: "尚无可用模型。先为上游获取模型列表或填写手动清单。", upstreams: "上游", estimate: "费用预估", + quoting: "计算中", pricingDate: (date: string) => `价格数据 ${date}`, inputTokens: "输入 tokens", maxOutput: "输出上限", @@ -57,7 +57,6 @@ export const testDialogsText = messages( title: "Connection test", allUpstreams: "All upstreams", desc: "Measures how long DNS resolution, the TCP handshake and the TLS handshake take, including the proxy handshake when a proxy is used. Incurs no cost.", - testing: "Testing", empty: "No upstreams yet.", via: "Via", stages: "Stages", @@ -72,6 +71,7 @@ export const testDialogsText = messages( noModels: "No models available yet. Fetch an upstream's model list or enter a manual list first.", upstreams: "Upstreams", estimate: "Cost estimate", + quoting: "Calculating", pricingDate: (date: string) => `Prices as of ${date}`, inputTokens: "Input tokens", maxOutput: "Max output", diff --git a/src/upstreams/TestDialogs.tsx b/src/upstreams/TestDialogs.tsx index 16ac1ef3..1be64e78 100644 --- a/src/upstreams/TestDialogs.tsx +++ b/src/upstreams/TestDialogs.tsx @@ -1,6 +1,5 @@ import { useEffect, useMemo, useState } from "react"; import { ActivityIcon, ZapIcon } from "lucide-react"; -import { Alert, AlertDescription } from "@/ui/alert"; import { Button } from "@/ui/button"; import { Checkbox } from "@/ui/checkbox"; import { @@ -12,7 +11,9 @@ import { DialogTitle, } from "@/ui/dialog"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; -import { Spinner } from "@/ui/spinner"; +import { Skeleton } from "@/ui/skeleton"; +import { TableSkeleton } from "@/ui/states"; +import { StatusLabel } from "@/ui/status-dot"; import { Table, TableBody, @@ -44,7 +45,7 @@ import { plain, skipLabel, } from "./labels"; -import { Boxed, FormItem, Note } from "./parts"; +import { Boxed, DialogError, FormItem, Note, VendorTile } from "./parts"; import { testDialogsText } from "./TestDialogs.i18n"; import { formFromView, toInput } from "./upstreamForm"; @@ -89,14 +90,15 @@ export function TestConnectionDialog({ {name} · {t.connection.desc} - {result ? ( - - ) : ( -

    - - {t.connection.checking} -

    - )} +
    + {result ? ( + + ) : ( + + {t.connection.checking} + + )} +
    - @@ -342,10 +345,7 @@ export function SpeedTestDialog({
    {models == null ? ( -

    - - {t.speed.loadingModels} -

    + ) : models.length === 0 ? ( {t.speed.noModels} ) : ( @@ -389,6 +389,7 @@ export function SpeedTestDialog({ }) } /> + {p.name}
    @@ -403,7 +404,11 @@ export function SpeedTestDialog({
    {t.speed.estimate} - {quoting && } + {quoting && ( + + {t.speed.quoting} + + )}
    {quote && {t.speed.pricingDate(quote.pricing_date)}}
    @@ -420,14 +425,16 @@ export function SpeedTestDialog({ {runnable.map((i) => ( - {i.provider} - {i.input_tokens} - + + + + {i.input_tokens} + {i.max_output_tokens ?? ( {t.speed.noLimit} )} - + {i.cost_micros != null ? ( usd(i.cost_micros) ) : ( @@ -447,7 +454,7 @@ export function SpeedTestDialog({ - + {selectedQuote?.total_micros != null ? usd(selectedQuote.total_micros) : t.speed.totalUncalculable} @@ -477,22 +484,20 @@ export function SpeedTestDialog({ {results.map((r) => ( - - - {r.provider} + + + {!r.ok && r.error && ( -
    - {coreText(r.error)} -
    +
    {coreText(r.error)}
    )}
    - + {r.ttft_ms != null ? `${r.ttft_ms.toLocaleString()} ms` : "—"} - + {r.ok ? `${r.total_ms.toLocaleString()} ms` : "—"} - + {r.input_tokens != null && r.output_tokens != null ? `${r.input_tokens} → ${r.output_tokens}` : "—"} @@ -506,18 +511,14 @@ export function SpeedTestDialog({ )}
    - {error && ( - - {error} - - )} + - @@ -525,3 +526,14 @@ export function SpeedTestDialog({ ); } + +/** 测速结果表里的上游:标志加名字 */ +function UpstreamName({ ov, name }: { ov: Overview; name: string }) { + const p = ov.providers.find((x) => x.name === name); + return ( + + + {name} + + ); +} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 8fa931a9..f8b1cbdc 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -1,5 +1,4 @@ import { useEffect, useMemo, useState } from "react"; -import { Alert, AlertDescription } from "@/ui/alert"; import { Button } from "@/ui/button"; import { Dialog, @@ -9,7 +8,6 @@ import { DialogHeader, DialogTitle, } from "@/ui/dialog"; -import { Spinner } from "@/ui/spinner"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import type { @@ -26,7 +24,7 @@ import { ChatgptAccountSection } from "./ChatgptAccountSection"; import { ConnectionSection } from "./ConnectionSection"; import { coreText, errorText, plain, protocolLabel, shortUrl } from "./labels"; import { ModelsSection, catalogOf, inScope, type ModelCatalog } from "./ModelsSection"; -import { StepNav } from "./parts"; +import { DialogError, ProviderTile, StepNav } from "./parts"; import { PriceSheetDialog } from "./PriceSheetDialog"; import { ProxyDialog } from "./ProxyDialog"; import { upstreamDialogText } from "./UpstreamDialog.i18n"; @@ -298,20 +296,29 @@ export function UpstreamDialog({ return ( !open && onClose()}> - {/* 固定高度:切换分节时对话框不跳动,内容在中间滚动 */} - - - {editing ? t.titleEdit : t.titleNew} - {editing ? ( - - {editing.name} ·{" "} - {protocolLabel(editing.protocol)} - {/* 账号上游的地址是登录给的,改不了,写出来只是噪声 */} - {!account && ` · ${shortUrl(editing.base_url)}`} - - ) : ( - {t.desc} - )} + {/* + 固定高度:切换分节时对话框不跳动,内容在中间滚动。点到对话框外面不关 —— + 填了一半的表单不该因为一次误点丢掉;Esc、×、取消照常 + */} + e.preventDefault()} + > + + {editing && } +
    + {editing ? t.titleEdit : t.titleNew} + {editing ? ( + + {editing.name} ·{" "} + {protocolLabel(editing.protocol)} + {/* 账号上游的地址是登录给的,改不了,写出来只是噪声 */} + {!account && ` · ${shortUrl(editing.base_url)}`} + + ) : ( + {t.desc} + )} +
    - {error && ( - - {error} - - )} + {editing ? ( @@ -389,14 +392,14 @@ export function UpstreamDialog({ - ) : ( <> - {missing && {missing}} @@ -410,8 +413,7 @@ export function UpstreamDialog({ {t.next} ) : ( - )} diff --git a/src/upstreams/UpstreamTable.i18n.ts b/src/upstreams/UpstreamTable.i18n.ts index ac382447..9208f06a 100644 --- a/src/upstreams/UpstreamTable.i18n.ts +++ b/src/upstreams/UpstreamTable.i18n.ts @@ -1,5 +1,11 @@ import { messages } from "@/i18n"; +/** 成功率:整数写整数(100%),否则留一位(98.5%) */ +function rate(v: number): string { + const r = Math.round(v * 10) / 10; + return Number.isInteger(r) ? String(r) : r.toFixed(1); +} + export const upstreamTableText = messages( { upstream: "上游", @@ -7,19 +13,24 @@ export const upstreamTableText = messages( quota: "额度 / 计费", day: "24 小时", ttfb: "首字节 P50", + actionsColumn: "操作", disabled: "已停用", + disabledTip: "已停用的上游不参与转发。", circuitOpen: "熔断中", + circuitOpenTip: "此上游连续失败,暂不参与转发。", authRejected: "凭据被拒", authRejectedTip: (status: number) => `上游返回未授权(${status}),该上游的凭据可能已失效。`, needsLogin: "需要重新登录", needsLoginTip: "账号的登录已失效。重新登录之前,经此上游的请求都会失败。", + inFlight: (n: number) => `${n} 个请求进行中`, actions: (name: string) => `${name} 的操作`, check: "检测连接", linkTest: "链路测速", speedTest: "推理测速…", refreshModels: "刷新模型列表", account: "额度与重置卡…", + traffic: "查看流量", enable: "启用", disable: "停用", locate: "在配置文件中定位", @@ -27,10 +38,20 @@ export const upstreamTableText = messages( modelsOf: (name: string) => `${name} 的模型`, used: (percent: number) => `已用 ${percent}%`, quotaOf: (window: string) => `${window}额度`, + windowLine: (window: string, used: number, reset: string | null) => + reset ? `${window}额度:已用 ${used}%,${reset}重置` : `${window}额度:已用 ${used}%`, sheet: (name: string) => `价目表 ${name}`, defaultSheet: "默认", requests: (n: number) => `${n.toLocaleString()} 次`, unpriced: (n: number) => `${n} 次无法计价`, + dayRequests: (n: number) => `24 小时 ${n.toLocaleString()} 次请求`, + dayFailed: (n: number, success: number) => `失败 ${n.toLocaleString()} 次,成功率 ${rate(success)}%`, + dayNoFailures: "无失败", + dayCost: (cost: string) => `费用 ${cost}`, + unpricedTip: (n: number) => `${n.toLocaleString()} 次无法计价,未计入费用`, + ms: (n: number) => `${n.toLocaleString()} ms`, + latencyTip: (p95: number, samples: number) => + `P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} 个样本`, }, { upstream: "Upstream", @@ -38,20 +59,25 @@ export const upstreamTableText = messages( quota: "Quota / billing", day: "24 hours", ttfb: "TTFB P50", + actionsColumn: "Actions", disabled: "Disabled", + disabledTip: "A disabled upstream receives no requests.", circuitOpen: "Circuit open", + circuitOpenTip: "This upstream failed repeatedly and receives no requests for now.", authRejected: "Credential rejected", authRejectedTip: (status: number) => `The upstream returned an unauthorized response (${status}). The credential for this upstream may no longer be valid.`, needsLogin: "Sign in again", needsLoginTip: "The account's sign-in has expired. Until the account is signed in again, requests through this upstream will fail.", + inFlight: (n: number) => (n === 1 ? "1 request in progress" : `${n} requests in progress`), actions: (name: string) => `Actions for ${name}`, check: "Check connection", linkTest: "Connection test", speedTest: "Inference test…", refreshModels: "Refresh model list", account: "Usage limits and reset credits…", + traffic: "View traffic", enable: "Enable", disable: "Disable", locate: "Show in config file", @@ -59,9 +85,22 @@ export const upstreamTableText = messages( modelsOf: (name: string) => `Models for ${name}`, used: (percent: number) => `${percent}% used`, quotaOf: (window: string) => `${window} usage limit`, + windowLine: (window: string, used: number, reset: string | null) => + reset ? `${window} limit: ${used}% used, resets ${reset}` : `${window} limit: ${used}% used`, sheet: (name: string) => `Price sheet: ${name}`, defaultSheet: "default", requests: (n: number) => (n === 1 ? "1 request" : `${n.toLocaleString()} requests`), unpriced: (n: number) => `${n} unpriced`, + dayRequests: (n: number) => + n === 1 ? "1 request in 24 hours" : `${n.toLocaleString()} requests in 24 hours`, + dayFailed: (n: number, success: number) => + `${n.toLocaleString()} failed, ${rate(success)}% succeeded`, + dayNoFailures: "No failures", + dayCost: (cost: string) => `Cost ${cost}`, + unpricedTip: (n: number) => + n === 1 ? "1 request unpriced, not included in the cost" : `${n.toLocaleString()} requests unpriced, not included in the cost`, + ms: (n: number) => `${n.toLocaleString()} ms`, + latencyTip: (p95: number, samples: number) => + `P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} ${samples === 1 ? "sample" : "samples"}`, }, ); diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 5fe28d8c..f8e71c1a 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -1,25 +1,22 @@ -import { useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { cn } from "@/lib/utils"; +import type { Resource } from "@/lib/resource"; import { Badge } from "@/ui/badge"; +import { AnimatedNumber, rowMotion, usePresentList } from "@/ui/motion"; import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover"; -import { Progress } from "@/ui/progress"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/ui/table"; -import { resetAt } from "@/format"; +import { Skeleton } from "@/ui/skeleton"; +import { Spinner } from "@/ui/spinner"; +import { StatusLabel, type StatusTone } from "@/ui/status-dot"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; import { Tip } from "@/ui/tip"; +import { resetAt } from "@/format"; import { useNow } from "@/useNow"; -import { Spinner } from "@/ui/spinner"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; -import { usd, type ChatgptUsage, type Overview, type ProviderView } from "@/types"; +import { usd, type ChatgptUsage, type ProviderView, type QuotaWindow } from "@/types"; import type { UpstreamStats } from "./api"; +import { slotsByUpstream, type Slot } from "./data"; import { billingLabel, egressLabel, @@ -31,6 +28,9 @@ import { } from "./labels"; import { labelsText } from "./labels.i18n"; import { ModelsPanel } from "./ModelsPanel"; +import { ProviderTile, keepInRow, openRow } from "./parts"; +import { QUOTA_FULL, QuotaBar } from "./QuotaBar"; +import { SPARKLINE_WIDTH, Sparkline } from "./Sparkline"; import { upstreamTableText } from "./UpstreamTable.i18n"; export interface UpstreamActions { @@ -41,8 +41,10 @@ export interface UpstreamActions { refreshModels: (name: string) => void; /** 打开编辑对话框的「模型」一节:启用范围、手动清单 */ editModels: (name: string) => void; - /** ChatGPT 账号上游:额度与重置卡 */ + /** ChatGPT 账号上游:编辑对话框的「账号」一节(额度与重置卡) */ account: (name: string) => void; + /** 流量页,只看经这个上游的请求 */ + traffic: (name: string) => void; toggle: (p: ProviderView) => void; locate: (name: string) => void; remove: (name: string) => void; @@ -51,100 +53,102 @@ export interface UpstreamActions { /** * 上游列表。**只读** —— 改任何东西都走对话框,行上没有就地编辑的控件。 * - * 双击行、行尾按钮、右键打开的是同一份操作。 + * 单击一行(或 Enter)打开它的编辑对话框;行尾按钮和右键打开的是同一份操作。 + * + * 五列是定过的(lite#46):上游、模型、额度 / 计费、24 小时、首字节 P50。「24 小时」 + * 一格里多了一条按小时的走势:请求在一天里怎么分布、失败落在哪几个小时,一眼看得出, + * 数字留给右边和悬停。窗口窄到放不下时走势先让位(容器查询),数字照常在。 */ export function UpstreamTable({ - ov, + providers, stats, + since, accounts, + inFlight, + refreshing, + focus, actions, }: { - ov: Overview; - stats: UpstreamStats | null; + providers: ProviderView[]; + stats: Resource; + /** 走势第一格的起点(对齐到整点) */ + since: number; /** 账号类上游问来的账号信息,按上游名。还没问到的就没有 */ accounts: Record; + /** 此刻每个上游在途的请求数 */ + inFlight: ReadonlyMap; + /** 正在手动刷新模型清单的上游 */ + refreshing: ReadonlySet; + /** 从别的页定位到的那一行:滚进视野、亮一下。`at` 让同一个名字再定位一次也生效 */ + focus: { name: string; at: number } | null; actions: UpstreamActions; }) { const t = useText(upstreamTableText); // 额度的「多久后重置」随时间走:重画就行,不用再问 core const now = useNow(); + const shown = usePresentList(providers, (p) => p.name); + const slots = useMemo(() => slotsByUpstream(stats.data?.buckets, since), [stats.data, since]); + const [flash, setFlash] = useState(null); + useEffect(() => { + if (!focus) return; + document + .querySelector(`tr[data-row="${CSS.escape(focus.name)}"]`) + ?.scrollIntoView({ block: "nearest", inline: "nearest" }); + setFlash(focus.name); + // 和 `motion-row-in` 一样长:亮一下就退 + const h = setTimeout(() => setFlash(null), 900); + return () => clearTimeout(h); + }, [focus]); return ( -
    - - - {t.upstream} - {t.models} - {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} - {t.quota} - {t.day} - {t.ttfb} - - - - - {ov.providers.map((p) => { - const items = menu(p, actions); - return ( - - actions.edit(p.name)} - className="cursor-default" - > - - {/* - **状态只在异常时出现。**每行都写一遍「正常」是噪声;熔断和停用 - 跟在名称后面,扫一遍列表就能看到。 - */} -
    - - {p.name} - - {/* 订阅类账号:套餐决定了额度有多大,和名字放在一起看 */} - {planLabel(accounts[p.name]?.plan) && ( - {planLabel(accounts[p.name]?.plan)} - )} - {p.disabled ? ( - {t.disabled} - ) : ( - <> - {/* - 熔断看不见凭据的问题:4xx 不算失败,凭据坏掉的上游永远不会熔断。 - 这两个要自己说 - */} - {p.oauth?.needs_login && ( - - {t.needsLogin} - - )} - {p.auth_rejected != null && ( - - {t.authRejected} - - )} - {p.health === "open" && {t.circuitOpen}} - - )} -
    - {/* - 协议、地址、出站方式是同一件事的三个部分:这一家在哪、怎么连。 - 地址可能很长(带路径的中转):截断,悬停看全 - */} - -
    - actions.editModels(p.name)} /> - - - - - - -
    -
    - ); - })} -
    -
    + // 容器查询:表格那一栏窄了(默认窗口里约 860px,最窄约 580px),走势先收起来 +
    + + + + {t.upstream} + {t.models} + {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} + {t.quota} + {t.day} + {t.ttfb} + + {t.actionsColumn} + + + + + {shown.map(({ item: p, key, presence }) => { + const items = menu(p, actions); + return ( + + actions.edit(p.name), rowMotion(flash === p.name ? "enter" : presence))} + > + 0 && !p.disabled} + liveCount={inFlight.get(p.name) ?? 0} + /> + actions.editModels(p.name)} + /> + + + + + + + + + ); + })} + +
    +
    ); } @@ -160,6 +164,7 @@ function menu(p: ProviderView, a: UpstreamActions): MenuItems { ...(p.protocol === "chatgpt" ? ([{ kind: "item", label: t.account, onSelect: () => a.account(p.name) }] as MenuItems) : []), + { kind: "item", label: t.traffic, onSelect: () => a.traffic(p.name) }, { kind: "sep" }, { kind: "item", label: p.disabled ? t.enable : t.disable, onSelect: () => a.toggle(p) }, { kind: "item", label: t.locate, onSelect: () => a.locate(p.name) }, @@ -168,26 +173,100 @@ function menu(p: ProviderView, a: UpstreamActions): MenuItems { ]; } +/** + * 这一行的状态。**只在异常时出现**:每行都写一遍「正常」是噪声。 + * + * 熔断看不见凭据的问题(4xx 不算失败,凭据坏掉的上游永远不会熔断),所以凭据被拒、 + * 登录失效要自己说。几件同时成立时说最要紧的那一件,其余在悬停里。 + */ +export function problemsOf(p: ProviderView): { tone: StatusTone; label: string; tip: string }[] { + const t = textOf(upstreamTableText); + if (p.disabled) return [{ tone: "idle", label: t.disabled, tip: t.disabledTip }]; + const out: { tone: StatusTone; label: string; tip: string }[] = []; + if (p.oauth?.needs_login) out.push({ tone: "error", label: t.needsLogin, tip: t.needsLoginTip }); + if (p.auth_rejected != null) + out.push({ tone: "error", label: t.authRejected, tip: t.authRejectedTip(p.auth_rejected) }); + if (p.health === "open") out.push({ tone: "error", label: t.circuitOpen, tip: t.circuitOpenTip }); + return out; +} + +/** + * 名称一格:标志、名字、套餐与状态,下面一行是协议、地址、出站方式 —— 这一家 + * 在哪、怎么连。地址可能很长(带路径的中转):截断,悬停看全。 + */ +function NameCell({ + p, + account, + live, + liveCount, +}: { + p: ProviderView; + account?: ChatgptUsage; + live: boolean; + liveCount: number; +}) { + const t = useText(upstreamTableText); + const problems = problemsOf(p); + const problem = problems[0]; + const plan = planLabel(account?.plan); + const tile = ; + return ( + +
    + {live ? ( + + {tile} + + ) : ( + tile + )} +
    +
    + {p.name} + {/* 订阅类账号:套餐决定了额度有多大,和名字放在一起看 */} + {plan && {plan}} + {problem && ( + + {problems.map((x) => ( +

    {x.tip}

    + ))} +
    + } + > + + + {problem.label} + + + + )} +
    + +
    +
    + + ); +} + /** * 这一家在哪、怎么连。 * - * 账号类上游的地址永远是同一个,**写出来一行废话** —— 那一格 - * 留给邮箱:登了两个账号时,它是唯一能分辨哪行是哪个的东西。 + * 账号类上游的地址永远是同一个,**写出来一行废话** —— 那一格留给邮箱:登了两个 + * 账号时,它是唯一能分辨哪行是哪个的东西。 */ function Where({ p, account }: { p: ProviderView; account?: ChatgptUsage }) { const t = useText(upstreamTableText); - // 账号类上游的地址永远是同一个,协议名已经说了它在哪 const isAccount = p.protocol === "chatgpt"; const where = isAccount ? (account?.email ?? null) : shortUrl(p.base_url); + // 直连是默认,不用说 const egress = p.proxy === "direct" ? "" : ` · ${t.via(egressLabel(p.proxy))}`; - const full = [protocolLabel(p.protocol), isAccount ? account?.email : p.base_url] - .filter(Boolean) - .join(" · "); + const full = [protocolLabel(p.protocol), isAccount ? account?.email : p.base_url].filter(Boolean).join(" · "); return ( -
    +
    {protocolLabel(p.protocol)} {where && ` · ${where}`} - {/* 直连是默认,不用说 */} {egress}
    ); @@ -196,11 +275,10 @@ function Where({ p, account }: { p: ProviderView; account?: ChatgptUsage }) { /** * 有多少个模型,以及都有哪些。 * - * **整格是一个按钮,什么状态都能点开** —— 数目单独回答不了「我要的那个 - * 模型在不在里面」,而没拿到清单时,点开要能看到为什么、该做什么。不用 - * 为了看一眼进编辑对话框再点刷新。停用的上游不提供模型,状态一栏已经说了。 + * **整格是一个按钮,什么状态都能点开** —— 数目单独回答不了「要的那个模型在不在 + * 里面」,而没拿到清单时,点开要能看到原因和下一步。停用的上游不提供模型。 */ -function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { +function ModelsCell({ p, busy, onEdit }: { p: ProviderView; busy: boolean; onEdit: () => void }) { const t = useText(upstreamTableText); const l = useText(labelsText); const [open, setOpen] = useState(false); @@ -208,9 +286,9 @@ function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { return —; } const face = modelFace(p); - const busy = p.model_fetching || face.note === l.models.fetching; + const fetching = busy || p.model_fetching || face.note === l.models.fetching; return ( - + {/* 悬停时整块变底色,不画下划线 —— 鼠标正好压在字的下方,一条紧贴 @@ -218,10 +296,10 @@ function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { */} - - {busy && } + + {fetching && } {face.count ?? "—"} {face.note && ( @@ -248,92 +326,170 @@ function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { /** * 还剩多少可用。 * - * 报过额度的上游,答案是额度条 —— 那是这一家「今天还能不能接着用」的唯一答案。 - * **没报过额度就退回说计费方式**:画一根 0% 的空条等于说「一点没用」,而事实 - * 是不知道。 + * 报过额度的上游,答案是额度条 —— 那是这一家「今天还能不能接着用」的唯一答案, + * 画的是**最紧张的那个窗口**,其余窗口在悬停里。**没报过额度就退回说计费方式**: + * 画一根 0% 的空条等于说「一点没用」,而事实是不知道。 */ -function QuotaCell({ - p, - stats, - now, -}: { - p: ProviderView; - stats: UpstreamStats | null; - now: number; -}) { +function QuotaCell({ p, stats, now }: { p: ProviderView; stats: Resource; now: number }) { const t = useText(upstreamTableText); // **过了重置时刻的窗口不算数**:手上的百分比是重置之前的,下一个请求才会带来 // 新的。拿它画一根满格的条,说的是一件已经不成立的事 - const windows = (stats?.quotas.find((q) => q.provider === p.name)?.windows ?? []).filter( + const windows = (stats.data?.quotas.find((q) => q.provider === p.name)?.windows ?? []).filter( (w) => w.resets_at_ms == null || w.resets_at_ms > now, ); // 最紧张的那个窗口:先到的那条线决定什么时候用完 - const tight = windows.reduce<(typeof windows)[number] | null>( + const tight = windows.reduce( (a, w) => (!a || w.used_percent > a.used_percent ? w : a), null, ); if (tight && !p.disabled) { const reset = resetAt(tight.resets_at_ms, now); + const used = Math.round(tight.used_percent); return ( -
    - {/* **要说清楚这个数是用掉的还是剩下的**:一根填了一半的条,两种读法都成立 */} - {t.used(Math.round(tight.used_percent))} - - {reset ? `${quotaWindowLabel(tight.window)} · ${reset}` : quotaWindowLabel(tight.window)} - -
    - + }> +
    +
    + {/* **要说清楚这个数是用掉的还是剩下的**:一根填了一半的条,两种读法都成立 */} + = QUOTA_FULL && "text-destructive")}>{t.used(used)} + + {reset ? `${quotaWindowLabel(tight.window)} · ${reset}` : quotaWindowLabel(tight.window)} + +
    + +
    +
    ); } const billing = p.billing; return ( -
    +
    {billingLabel(billing)}
    {billing === "per-token" && ( -
    {t.sheet(p.pricing ?? t.defaultSheet)}
    +
    {t.sheet(p.pricing ?? t.defaultSheet)}
    )} ); } +/** 悬停在额度上:每个窗口一行 */ +function QuotaTip({ windows, now }: { windows: QuotaWindow[]; now: number }) { + const t = useText(upstreamTableText); + return ( +
    + {windows.map((w) => { + const reset = resetAt(w.resets_at_ms, now); + return ( +
    + {t.windowLine(quotaWindowLabel(w.window), Math.round(w.used_percent), reset)} +
    + ); + })} +
    + ); +} + /** - * 一天用了多少:次数在上,花了多少在下。 + * 一天用了多少:左边是按小时的走势,右边次数在上、费用在下。 * - * 分成两列时,看一行要左右扫两次才知道「这一家跑了多少、花了多少」—— 而这 - * 两个数只有放在一起才有意义。 + * 次数和费用分成两列时,看一行要左右扫两次才知道「这一家跑了多少、费用多少」—— + * 而这两个数只有放在一起才有意义。走势里失败的那一截是红的;失败多少、成功率、 + * 无法计价的次数在悬停里。 */ -function DayCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { +function DayCell({ + p, + stats, + slots, +}: { + p: ProviderView; + stats: Resource; + slots: Slot[] | undefined; +}) { const t = useText(upstreamTableText); - const cost = stats?.costs.find((c) => c.name === p.name); + if (stats.data === undefined) { + return ( + + {stats.loading ? ( + // 和读到之后一样宽:走势的位置先占上,数字到了列宽不跳 +
    + + +
    + ) : ( + — + )} +
    + ); + } + const cost = stats.data.costs.find((c) => c.name === p.name); if (!cost || cost.requests === 0) { return —; } - return ( - -
    {t.requests(cost.requests)}
    -
    - {usd(cost.cost_micros)} - {cost.unpriced_requests > 0 && ( - · {t.unpriced(cost.unpriced_requests)} - )} + const failed = slots?.reduce((n, s) => n + s.failed, 0) ?? 0; + const tip = ( +
    +
    {t.dayRequests(cost.requests)}
    +
    + {failed > 0 ? t.dayFailed(failed, (1 - failed / cost.requests) * 100) : t.dayNoFailures}
    +
    {t.dayCost(usd(cost.cost_micros))}
    + {cost.unpriced_requests > 0 &&
    {t.unpricedTip(cost.unpriced_requests)}
    } +
    + ); + return ( + + + {/* + 走势贴左、数字贴右,撑满这一格:各行的走势左边对齐、数字右边对齐, + 不随「201 次」「7 次」的宽窄左右错开 + */} +
    + {slots && } +
    + t.requests(Math.round(n))} /> + + usd(Math.round(n))} /> + {cost.unpriced_requests > 0 && · {t.unpriced(cost.unpriced_requests)}} + +
    +
    +
    ); } -function LatencyCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { - const lat = stats?.latency.find((l) => l.model === p.name); +/** 首字节 P50。P95 与样本数在悬停里:「800 ms」是 3 个样本还是 300 个,含义完全不同 */ +function LatencyCell({ p, stats }: { p: ProviderView; stats: Resource }) { + const t = useText(upstreamTableText); + if (stats.data === undefined) { + return ( + + {stats.loading ? : —} + + ); + } + const lat = stats.data.latency.find((l) => l.model === p.name); + if (!lat || lat.samples === 0) { + return —; + } return ( - - {lat && lat.samples > 0 ? `${lat.p50.toLocaleString()} ms` : "—"} + + + {t.ms(lat.p50)} + ); } + +/** 统计还没到时,一格里的占位:两行,和数字的位置一样 */ +function CellSkeleton({ short = false }: { short?: boolean }) { + return ( +
    + + {!short && } +
    + ); +} diff --git a/src/upstreams/UpstreamsPage.i18n.ts b/src/upstreams/UpstreamsPage.i18n.tsx similarity index 64% rename from src/upstreams/UpstreamsPage.i18n.ts rename to src/upstreams/UpstreamsPage.i18n.tsx index 25d62ff7..e1a3c83c 100644 --- a/src/upstreams/UpstreamsPage.i18n.ts +++ b/src/upstreams/UpstreamsPage.i18n.tsx @@ -1,8 +1,24 @@ +import type { ReactNode } from "react"; import { messages } from "@/i18n"; +/** + * 页头摘要里的几项写成「带一个数的句子」:数字是传进来的节点(会走动的 + * `AnimatedNumber`),语序由各语言自己定 —— 中文「24 小时 234 次请求」, + * 英文「234 requests in 24 h」。 + */ export const upstreamsPageText = messages( { - modelsError: (name: string, error: string) => `${name}:${error}`, + title: "上游", + hero: { + upstreams: (n: ReactNode, _count: number) => <>{n} 个上游, + healthy: (n: ReactNode) => <>{n} 正常, + attention: (n: ReactNode) => <>{n} 需处理, + disabled: (n: ReactNode) => <>{n} 已停用, + requests: (n: ReactNode, _count: number) => <>24 小时 {n} 次请求, + cost: (n: ReactNode) => <>费用 {n}, + }, + modelsFailed: (name: string) => `${name} 的模型列表获取失败`, + modelsFetched: (name: string, n: number) => `${name}:已获取 ${n} 个模型`, pricesUpdated: (changed: number) => `默认价目表已更新,${changed} 个模型的价格有变化`, pricesCurrent: "默认价目表已是最新", tabs: { upstreams: "上游", proxies: "代理", pricing: "价目表" }, @@ -19,9 +35,9 @@ export const upstreamsPageText = messages( "上游是网关转发请求的目标服务。新建上游并填写接口地址与凭据后,客户端请求即可经网关发出。", noProxies: "尚无代理", noProxiesDesc: "上游默认直连。需要经代理访问的上游,先新建代理,再在上游的连接设置中选择它。", - dataDate: (date: string) => `默认价目表数据日期 ${date}`, - lastChecked: (when: string) => `最近检查 ${when}`, - updateFailed: (error: string) => `更新失败:${error}`, + statsFailed: "24 小时统计读取失败", + statusFailed: "默认价目表状态读取失败", + updateFailedTitle: "默认价目表更新失败", unpricedTitle: (n: number) => `最近 7 天有 ${n.toLocaleString()} 次请求无法计价`, unpricedModels: "涉及模型", listSep: "、", @@ -30,6 +46,9 @@ export const upstreamsPageText = messages( more: (total: number, _shown: number) => ` 等 ${total} 项`, unpricedEnd: ",相关费用未计入统计。", setPrices: "设置价格", + disabledToast: (name: string) => `已停用上游 ${name}`, + enabledToast: (name: string) => `已启用上游 ${name}`, + saved: (name: string) => `已保存 ${name}`, /** 交给删除对话框、嵌在句子中间的名词 */ what: { upstream: "上游", proxy: "代理", sheet: "价目表" }, upstreamGone: "删除后,此上游的地址、凭据与设置将从配置文件中移除,可在版本历史中恢复。", @@ -37,7 +56,17 @@ export const upstreamsPageText = messages( sheetGone: "删除后,此价目表的倍率与模型覆盖将从配置文件中移除,可在版本历史中恢复。", }, { - modelsError: (name: string, error: string) => `${name}: ${error}`, + title: "Upstreams", + hero: { + upstreams: (n: ReactNode, count: number) => <>{n} {count === 1 ? "upstream" : "upstreams"}, + healthy: (n: ReactNode) => <>{n} healthy, + attention: (n: ReactNode) => <>{n} need attention, + disabled: (n: ReactNode) => <>{n} disabled, + requests: (n: ReactNode, count: number) => <>{n} {count === 1 ? "request" : "requests"} in 24 h, + cost: (n: ReactNode) => <>Cost {n}, + }, + modelsFailed: (name: string) => `Could not fetch the model list for ${name}`, + modelsFetched: (name: string, n: number) => `${name}: ${n === 1 ? "1 model" : `${n} models`} fetched`, pricesUpdated: (changed: number) => changed === 1 ? "Default price sheet updated; 1 model's price changed" @@ -58,9 +87,9 @@ export const upstreamsPageText = messages( noProxies: "No proxies", noProxiesDesc: "Upstreams connect directly by default. For an upstream that must be reached through a proxy, create the proxy first, then select it in the upstream's connection settings.", - dataDate: (date: string) => `Default price sheet data as of ${date}`, - lastChecked: (when: string) => `last checked ${when}`, - updateFailed: (error: string) => `update failed: ${error}`, + statsFailed: "Could not load the 24-hour statistics", + statusFailed: "Could not load the default price sheet's status", + updateFailedTitle: "The default price sheet could not be updated", unpricedTitle: (n: number) => n === 1 ? "1 request in the last 7 days was unpriced" @@ -71,6 +100,9 @@ export const upstreamsPageText = messages( more: (total: number, shown: number) => ` and ${total - shown} more`, unpricedEnd: ". Their cost is not included in the statistics.", setPrices: "Set prices", + disabledToast: (name: string) => `Upstream ${name} disabled`, + enabledToast: (name: string) => `Upstream ${name} enabled`, + saved: (name: string) => `${name} saved`, what: { upstream: "upstream", proxy: "proxy", sheet: "price sheet" }, upstreamGone: "Deleting removes this upstream's address, credentials and settings from the config file. They can be restored from version history.", diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index b0bb9800..4ab35015 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -1,28 +1,25 @@ -import { useCallback, useEffect, useRef, useState } from "react"; -import { listen } from "@tauri-apps/api/event"; -import { ActivityIcon, CircleAlertIcon, PlusIcon, RefreshCwIcon, ServerIcon, ZapIcon } from "lucide-react"; -import { toast } from "sonner"; -import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/ui/alert"; +import { useEffect, useMemo, useState, type ReactNode } from "react"; +import { ActivityIcon, NetworkIcon, PlusIcon, RefreshCwIcon, ServerIcon, ZapIcon } from "lucide-react"; +import { invalidate, type Resource } from "@/lib/resource"; +import { useNav, useNavParams } from "@/nav"; +import { Banner } from "@/ui/banner"; import { Button } from "@/ui/button"; -import { - Empty, - EmptyContent, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from "@/ui/empty"; -import { Spinner } from "@/ui/spinner"; +import { Count } from "@/ui/count"; +import { AnimatedNumber } from "@/ui/motion"; +import { notify, undoable, usePending } from "@/ui/notify"; +import { Page, PageHeader } from "@/ui/page"; +import { Skeleton } from "@/ui/skeleton"; +import { EmptyState } from "@/ui/states"; +import { StatusDot } from "@/ui/status-dot"; import { Switch } from "@/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import { useText } from "@/i18n"; -import type { ChatgptUsage, CoreEvent, Overview, PricingStatus } from "@/types"; -import { useCoreEvent } from "@/useCoreEvent"; +import { commonText } from "@/i18n/common.i18n"; +import { usd, type Overview, type PricingStatus, type ProviderView } from "@/types"; import { api, type UpstreamStats } from "./api"; import { ChatgptLoginDialog } from "./ChatgptLoginDialog"; -import { ZaiLoginDialog } from "./ZaiLoginDialog"; +import { patch, useAccounts, useInFlight, usePricingStatus, useUpstreamStats } from "./data"; import { DeleteDialog, type Referrer } from "./DeleteDialog"; -import { when } from "@/format"; import { coreText, errorText, plain } from "./labels"; import { PriceSheetDialog, type PriceSheetDialogMode } from "./PriceSheetDialog"; import { PriceSheetTable } from "./PriceSheetTable"; @@ -32,10 +29,17 @@ import { LinkTestDialog, SpeedTestDialog, TestConnectionDialog } from "./TestDia import { UpstreamDialog, type UpstreamDialogMode } from "./UpstreamDialog"; import { formFromView, toInput } from "./upstreamForm"; import { upstreamsPageText } from "./UpstreamsPage.i18n"; -import { UpstreamTable } from "./UpstreamTable"; +import { UpstreamTable, problemsOf } from "./UpstreamTable"; +import { ZaiLoginDialog } from "./ZaiLoginDialog"; export type UpstreamTab = "upstreams" | "proxies" | "pricing"; +/** + * 这次打开应用以来最后看的那个标签。切到别的页再回来,还停在那一个。 + * 不存盘:重新打开应用从上游开始。 + */ +let lastTab: UpstreamTab = "upstreams"; + type DialogState = | null | { kind: "upstream"; mode: UpstreamDialogMode } @@ -51,135 +55,80 @@ type DialogState = | { kind: "sheet"; mode: PriceSheetDialogMode } | { kind: "delete-sheet"; name: string }; -const DAY_MS = 24 * 3_600_000; - /** * 上游页:上游、代理、价目表三个标签。 * * 三者描述出站侧的三个方面 —— 请求发往哪个服务、经过哪条网络路径、按什么 * 价格结算 —— 而代理和价目表只被上游引用,所以放在同一页里,引用关系在 * 页内闭合。**列表只读**,新建与编辑都在对话框里完成,一次保存一个版本。 + * + * 页头的摘要说上游的整体状况:几个、几个正常、几个要处理,24 小时的请求与费用。 */ export default function UpstreamsPage({ ov, - initialTab = "upstreams", onChanged, onOpenConfigFile, - onNavigate, }: { ov: Overview; - initialTab?: UpstreamTab; /** 写入之后让外面立刻重读概览 */ onChanged: () => void; /** 打开配置文件,并定位到这个名字 */ onOpenConfigFile: (focus: string | null) => void; - /** 跳到别的页(路由、防护) */ - onNavigate: (tab: string) => void; }) { const t = useText(upstreamsPageText); + const c = useText(commonText); + const nav = useNav(); const configVersion = ov.config_version; - const [tab, setTab] = useState(initialTab); - const [stats, setStats] = useState(null); - const [status, setStatus] = useState(null); - const [checks, setChecks] = useState>({}); + const [tab, setTabState] = useState(lastTab); + const setTab = (next: UpstreamTab) => { + lastTab = next; + setTabState(next); + }; const [dialog, setDialog] = useState(null); - const [refreshingPrices, setRefreshingPrices] = useState(false); + const { stats, since } = useUpstreamStats(); + const pricing = usePricingStatus(configVersion); + const accounts = useAccounts(ov.providers, () => void stats.reload()); + const inFlight = useInFlight(); const proxies = ov.proxies; - const loadStats = useCallback(() => { - api - .upstreamStats(Date.now() - DAY_MS) - .then(setStats) - .catch(() => { - // 统计拿不到时这几列显示「—」,列表照常可用 - }); - }, []); - const loadStatus = useCallback(() => { - api - .pricingStatus() - .then(setStatus) - .catch((e) => toast.error(errorText(e))); - }, []); - /** - * 24 小时的请求数、费用和首字节耗时。 - * - * **请求落地之后重读**,不按时间轮询:这几个数只在请求落地时才变。随时间变的 - * 只有 24 小时这个窗口本身在往前滑 —— 长时间没有请求时没有事件叫醒它,窗口 - * 重新拿到焦点时补一次。 - */ - useEffect(() => { - loadStats(); - window.addEventListener("focus", loadStats); - return () => window.removeEventListener("focus", loadStats); - }, [loadStats]); - useCoreEvent(["request_finished", "request_failed", "request_cancelled"], loadStats); - - /** - * 订阅额度。**事件里就是完整的数**(和 `/quota` 同一份),收到直接换上: - * 额度变的那一刻就是这条事件到的那一刻。 + * 停用、启用是**乐观的**:先按新值画,写入回来、概览重读之后以概览为准。 + * 这里记的是「还没被概览证实的那几个」,概览对上了就撤掉。 */ + const [pendingDisabled, setPendingDisabled] = useState>({}); + const providers = useMemo( + () => + ov.providers.map((p) => + p.name in pendingDisabled ? { ...p, disabled: pendingDisabled[p.name]! } : p, + ), + [ov.providers, pendingDisabled], + ); useEffect(() => { - const un = listen("core-event", (e) => { - const ev = e.payload; - if (ev.kind !== "quota_seen") return; - setStats( - (s) => - s && { - ...s, - quotas: [ - ...s.quotas.filter((q) => q.provider !== ev.provider), - { provider: ev.provider, windows: ev.windows }, - ], - }, - ); + const stale = Object.keys(pendingDisabled).filter((n) => { + const p = ov.providers.find((x) => x.name === n); + return !p || p.disabled === pendingDisabled[n]; }); - return () => void un.then((f) => f()); - }, []); - - /** - * 账号类上游:**打开这一页时问一次它自己。** - * - * 一次问答同时回答三件事:登的是哪个账号、什么套餐、额度还剩多少。 - * 这三件都不在配置里 —— 额度平时是跟着真实流量白捡的,所以刚启动、 - * 或者这个账号今天还没被用过时,不问就什么都没有。 - * - * **每个上游只问一次。**问一次是一次真实调用;失败了也不再问 —— 连不上时 - * 反复重试,只会把错误刷满日志。 - */ - const [accounts, setAccounts] = useState>({}); - const askedUsage = useRef(new Set()); - 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(); + if (stale.length === 0) return; + setPendingDisabled((o) => { + const next = { ...o }; + for (const n of stale) delete next[n]; + return next; }); - }, [ov.providers, loadStats]); - useEffect(() => { - loadStatus(); - }, [loadStatus, configVersion]); + }, [ov.providers, pendingDisabled]); + + // 从别的页带着一个上游名打开:切到上游标签,那一行滚进视野、亮一下 + const [focus, setFocus] = useState<{ name: string; at: number } | null>(null); + useNavParams("upstreams", (p) => { + if (!p.upstream) return; + setTab("upstreams"); + setFocus({ name: p.upstream, at: Date.now() }); + }); /** * **打开这一页时补问模型清单**:还没有的、没问到的、过期的。 * * 不等、不管结果 —— core 立刻回话,答案随 `models_changed` 一家一家地到, * 概览跟着重读。一分钟内问过的它自己会跳过,来回切页面不会每次都打网络。 - * 以前要「编辑 → 模型 → 刷新」才看得到的东西,现在进页面就有。 */ useEffect(() => { api.refreshStaleModels().catch(() => { @@ -189,46 +138,70 @@ export default function UpstreamsPage({ const changed = () => { onChanged(); - loadStats(); + void stats.reload(); }; - async function toggle(name: string) { - const p = ov.providers.find((x) => x.name === name); - if (!p) return; - try { - await api.updateProvider(p.name, { - provider: { ...toInput(formFromView(p), true), disabled: !p.disabled }, - base_version: configVersion, - }); - changed(); - } catch (e) { - toast.error(errorText(e)); - } + async function toggle(p: ProviderView) { + const saved = ov.providers.find((x) => x.name === p.name); + if (!saved) return; + const next = !p.disabled; + // 撤销要基于这一次写入之后的版本,不然会被当成冲突 + let version = configVersion; + const write = (disabled: boolean) => + api + .updateProvider(saved.name, { + provider: { ...toInput(formFromView(saved), true), disabled }, + base_version: version, + }) + .then((w) => { + version = w.version; + }); + await undoable({ + message: next ? t.disabledToast(p.name) : t.enabledToast(p.name), + apply: () => { + setPendingDisabled((o) => ({ ...o, [p.name]: next })); + return () => setPendingDisabled((o) => ({ ...o, [p.name]: !next })); + }, + do: () => write(next), + undo: () => write(!next), + after: changed, + }); } + const [refreshing, setRefreshing] = useState>(() => new Set()); async function refreshModels(name: string) { + setRefreshing((s) => new Set(s).add(name)); try { const v = await api.refreshProviderModels(name); - if (v.error) toast.error(t.modelsError(name, coreText(v.error))); + if (v.error) notify.error(v.error, t.modelsFailed(name)); + else notify.success(t.modelsFetched(name, v.models.length)); + invalidate(`upstream-models:${name}`); changed(); } catch (e) { - toast.error(errorText(e)); + notify.error(e, t.modelsFailed(name)); + } finally { + setRefreshing((s) => { + const n = new Set(s); + n.delete(name); + return n; + }); } } + const [checks, setChecks] = useState>({}); async function testProxy(name: string) { const x = proxies.find((p) => p.name === name); if (!x) return; - setChecks((c) => ({ ...c, [name]: { running: true } })); + setChecks((prev) => ({ ...prev, [name]: { running: true } })); try { const result = await api.testProxy({ proxy: { name: x.name, kind: x.kind, addr: x.addr, auth: { mode: "keep" } }, current: x.name, }); - setChecks((c) => ({ ...c, [name]: { running: false, result, at: Date.now() } })); + setChecks((prev) => ({ ...prev, [name]: { running: false, result, at: Date.now() } })); } catch (e) { - setChecks((c) => ({ - ...c, + setChecks((prev) => ({ + ...prev, [name]: { running: false, result: { target: name, ok: false, segments: [], total_ms: 0, error: plain(errorText(e)) }, @@ -237,127 +210,164 @@ export default function UpstreamsPage({ })); } } + const [checkingAll, checkAll] = usePending(); - async function testAllProxies() { - // 逐个检测:并发时各自的握手耗时互相干扰 - for (const x of proxies) await testProxy(x.name); - } - - async function refreshPrices() { - setRefreshingPrices(true); - try { - const r = await api.refreshPricing(); - setStatus(r.status); - toast.success(r.changed > 0 ? t.pricesUpdated(r.changed) : t.pricesCurrent); - } catch (e) { - toast.error(errorText(e)); - loadStatus(); - } finally { - setRefreshingPrices(false); - } - } + const [updatingPrices, updatePrices] = usePending(); + const refreshPrices = () => + updatePrices(async () => { + try { + const r = await api.refreshPricing(); + pricing.mutate(r.status); + notify.success(r.changed > 0 ? t.pricesUpdated(r.changed) : t.pricesCurrent); + } catch (e) { + void pricing.reload(); + throw e; + } + }); + /** + * 自动更新的开关:先按新值画、转圈;写成了就记下新值(配置换了版本,状态随之重读), + * 失败拨回去并报错。 + */ + const [autoUpdate, setAutoUpdateState] = useState(null); async function setAutoUpdate(on: boolean) { + setAutoUpdateState(on); try { await api.setPriceAutoUpdate(on, configVersion); + pricing.mutate(patch((s) => ({ ...s, auto_update: on }))); onChanged(); - loadStatus(); } catch (e) { - toast.error(errorText(e)); + notify.error(e); + } finally { + setAutoUpdateState(null); } } + const createUpstream = () => setDialog({ kind: "upstream", mode: { kind: "create" } }); + const createProxy = () => setDialog({ kind: "proxy", mode: { kind: "create" } }); + + const actions = + tab === "upstreams" ? ( + <> + {providers.length > 0 && ( + <> + + + + )} + + + ) : tab === "proxies" ? ( + <> + {proxies.length > 0 && ( + + )} + + + ) : ( + <> + + + + + ); + return ( -
    - setTab(v as UpstreamTab)}> -
    - - - {t.tabs.upstreams} - - - {t.tabs.proxies} - - - {t.tabs.pricing} - - -
    - {tab === "upstreams" && ov.providers.length > 0 && ( - <> - - - - - )} - {tab === "proxies" && ( - <> - {proxies.length > 0 && ( - - )} - - - )} - {tab === "pricing" && ( - <> - - - - - )} -
    + setTab(v as UpstreamTab)} className="gap-0"> + + 0 ? : undefined} + actions={actions} + tabs={ + + + {t.tabs.upstreams} + + + {t.tabs.proxies} + + + {t.tabs.pricing} + + + } + /> - - {ov.providers.length === 0 ? ( - - - - - - {t.noUpstreams} - {t.noUpstreamsDesc} - - - {/* 服务类型在新建对话框的第一栏里选,这里不再平铺一排预设 */} - + } + > + {stats.error !== undefined ? errorText(stats.error) : null} + + {providers.length === 0 ? ( + } + title={t.noUpstreams} + description={t.noUpstreamsDesc} + action={ + - - + } + /> ) : ( setDialog({ kind: "upstream", mode: { kind: "edit", name } }), test: (name) => setDialog({ kind: "test", name }), @@ -368,7 +378,8 @@ export default function UpstreamsPage({ setDialog({ kind: "upstream", mode: { kind: "edit", name, section: "models" } }), account: (name) => setDialog({ kind: "upstream", mode: { kind: "edit", name, section: "account" } }), - toggle: (p) => void toggle(p.name), + traffic: (name) => nav.open("requests", { filter: { provider: name } }), + toggle: (p) => void toggle(p), locate: (name) => onOpenConfigFile(name), remove: (name) => setDialog({ kind: "delete-upstream", name }), }} @@ -376,17 +387,23 @@ export default function UpstreamsPage({ )} - + {proxies.length === 0 ? ( - - - {t.noProxies} - {t.noProxiesDesc} - - + } + title={t.noProxies} + description={t.noProxiesDesc} + action={ + + } + /> ) : ( setDialog({ kind: "proxy", mode: { kind: "edit", name } })} onTest={(name) => void testProxy(name)} @@ -395,66 +412,24 @@ export default function UpstreamsPage({ )} - - {status && ( -

    - {t.dataDate(status.date || "—")} - {status.checked_at_ms != null && ` · ${t.lastChecked(when(status.checked_at_ms))}`} - {status.error && · {t.updateFailed(coreText(status.error))}} -

    - )} - {status && status.unpriced_recent > 0 && ( - - - {t.unpricedTitle(status.unpriced_recent)} - - {t.unpricedModels}{" "} - {status.unpriced_models.slice(0, 4).map((u, i) => ( - - {i > 0 && t.listSep} - {u.model} - {t.provider(u.provider)} - - ))} - {status.unpriced_models.length > 4 && t.more(status.unpriced_models.length, 4)} - {t.unpricedEnd} - - - - - - )} + + void refreshPrices()} + onSetPrices={(prefill) => setDialog({ kind: "sheet", mode: { kind: "create", prefill } })} + /> setDialog({ kind: "sheet", mode: { kind: "default" } })} onEdit={(name) => setDialog({ kind: "sheet", mode: { kind: "edit", name } })} onDuplicate={(name) => setDialog({ kind: "sheet", mode: { kind: "duplicate", from: name } })} onRemove={(name) => setDialog({ kind: "delete-sheet", name })} /> -
    + {dialog?.kind === "upstream" && ( setDialog(null)} - onSaved={() => { + onSaved={(name) => { setDialog(null); + // 新建的那一行自己会滑进来;改动未必看得出来,说一声 + if (dialog.mode.kind === "edit") notify.success(t.saved(name)); changed(); }} onChanged={changed} @@ -488,7 +465,7 @@ export default function UpstreamsPage({ onClose={() => setDialog(null)} onShow={() => { setDialog(null); - onNavigate("routing"); + nav.open("routing"); }} /> )} @@ -507,7 +484,7 @@ export default function UpstreamsPage({ setDialog(null)} /> )} {dialog?.kind === "link" && ( - setDialog(null)} /> + setDialog(null)} /> )} {dialog?.kind === "speed" && ( setDialog(null)} /> @@ -518,8 +495,9 @@ export default function UpstreamsPage({ ov={ov} configVersion={configVersion} onClose={() => setDialog(null)} - onSaved={() => { + onSaved={(name) => { setDialog(null); + if (dialog.mode.kind === "edit") notify.success(t.saved(name)); changed(); }} /> @@ -548,10 +526,11 @@ export default function UpstreamsPage({ ov={ov} configVersion={configVersion} onClose={() => setDialog(null)} - onSaved={() => { + onSaved={(name) => { setDialog(null); + if (dialog.mode.kind === "edit") notify.success(t.saved(name)); + // 配置换了版本,价目表的状态(无法计价的次数)随之重读 changed(); - loadStatus(); }} onDeleted={() => { setDialog(null); @@ -577,7 +556,7 @@ export default function UpstreamsPage({ onShow={(r) => showUpstream(r, "billing")} /> )} -
    +
    ); function showUpstream(r: Referrer, section: "connection" | "billing") { @@ -587,6 +566,146 @@ export default function UpstreamsPage({ } } -function Count({ n }: { n: number }) { - return {n}; +/** + * 页头的摘要:几个上游、几个正常、几个要处理(凭据被拒、要重新登录、熔断)、 + * 几个停用,以及 24 小时的请求数和费用。数字变了走过去,不跳。 + * + * 24 小时的两个数**读到之前不画**(画一截骨架):从 0 滚到实际值像是在眼前涨了一截。 + */ +function Hero({ providers, stats }: { providers: ProviderView[]; stats: Resource }) { + const t = useText(upstreamsPageText); + const enabled = providers.filter((p) => !p.disabled); + const attention = enabled.filter((p) => problemsOf(p).length > 0).length; + const disabled = providers.length - enabled.length; + const day = stats.data + ? stats.data.costs.reduce( + (a, c) => ({ requests: a.requests + c.requests, cost: a.cost + c.cost_micros }), + { requests: 0, cost: 0 }, + ) + : null; + return ( + <> + {t.hero.upstreams(, providers.length)} + }>{t.hero.healthy()} + {attention > 0 && }>{t.hero.attention()}} + {disabled > 0 && }>{t.hero.disabled()}} + {day ? ( + <> + {t.hero.requests(, day.requests)} + {t.hero.cost( usd(Math.round(n))} />)} + + ) : ( + stats.loading && + )} + + ); +} + +/** 摘要里的一项:可选的状态点,加一句带数字的话。样子和 `SummaryItem` 一样 */ +function Fact({ lead, children }: { lead?: ReactNode; children: ReactNode }) { + return ( + + {lead} + {children} + + ); +} + +/** 摘要里的数:前景色、等宽,变化时走过去 */ +function Num({ value, format }: { value: number; format?: (n: number) => ReactNode }) { + return ; +} + +/** + * 价目表标签顶上的几条:默认价目表读不到状态、上一次更新失败、最近有请求无法计价。 + * 都是持续成立的事,用横幅,不用吐司。 + */ +function PricingNotices({ + ov, + status, + updating, + onUpdate, + onSetPrices, +}: { + ov: Overview; + status: Resource; + updating: boolean; + onUpdate: () => void; + onSetPrices: (prefill: { models: string[]; usedBy: string[] }) => void; +}) { + const t = useText(upstreamsPageText); + const c = useText(commonText); + const s = status.data; + const unpriced = s && s.unpriced_recent > 0 ? s : null; + return ( + <> + void status.reload()}> + {c.retry} + + } + > + {status.error !== undefined ? errorText(status.error) : null} + + + {c.retry} + + } + > + {s?.error ? coreText(s.error) : null} + + + onSetPrices({ + models: [...new Set(unpriced.unpriced_models.map((u) => u.model))], + // 只预选还在用默认价目表的上游。已选了自定义价目表的,改用新表 + // 会连带改掉它其余模型的价格 —— 那一家留给用户自己决定 + usedBy: [...new Set(unpriced.unpriced_models.map((u) => u.provider))].filter((n) => + ov.providers.some((p) => p.name === n && !p.pricing), + ), + }) + } + > + {t.setPrices} + + ) + } + > + {unpriced && ( + <> + {t.unpricedModels}{" "} + {unpriced.unpriced_models.slice(0, 4).map((u, i) => ( + + {i > 0 && t.listSep} + {u.model} + {t.provider(u.provider)} + + ))} + {unpriced.unpriced_models.length > 4 && t.more(unpriced.unpriced_models.length, 4)} + {t.unpricedEnd} + + )} + + + ); } diff --git a/src/upstreams/ZaiLoginDialog.tsx b/src/upstreams/ZaiLoginDialog.tsx index 86d2973a..59c4b3f6 100644 --- a/src/upstreams/ZaiLoginDialog.tsx +++ b/src/upstreams/ZaiLoginDialog.tsx @@ -1,8 +1,8 @@ import { useEffect, useRef, useState } from "react"; import { useSystemProxyLabel } from "@/connection/Remote"; -import { CircleAlertIcon, ExternalLinkIcon } from "lucide-react"; +import { ExternalLinkIcon } from "lucide-react"; import { listen } from "@tauri-apps/api/event"; -import { Alert, AlertDescription, AlertTitle } from "@/ui/alert"; +import { Banner } from "@/ui/banner"; import { Button } from "@/ui/button"; import { Checkbox } from "@/ui/checkbox"; import { @@ -17,14 +17,14 @@ import { Field, FieldLabel } from "@/ui/field"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { Segmented } from "@/ui/segmented"; -import { Spinner } from "@/ui/spinner"; +import { StatusLabel } from "@/ui/status-dot"; import type { CoreEvent, Overview, ZaiFamily, ZaiLoginStatus } from "@/types"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { zaiLoginText } from "./ZaiLoginDialog.i18n"; import { coreText, errorText, proxyKindLabel, shortUrl } from "./labels"; -import { FormItem } from "./parts"; +import { DialogError, FormItem } from "./parts"; import { ZAI_ENDPOINTS } from "./presets"; import { freeName } from "./upstreamForm"; @@ -156,7 +156,8 @@ export function ZaiLoginDialog({ return ( !o && void cancel()}> - + {/* 点到外面不关:登录进行中时关掉就是放弃这一次登录。Esc、×、取消照常 */} + e.preventDefault()}> {relogin ? t.reloginTitle : t.title} @@ -167,18 +168,14 @@ export function ZaiLoginDialog({ {phase.at === "form" && (
    {!relogin && ( - - - {t.noticeTitle} - -
      -
    • {t.noticeTheirPage}
    • -
    • {t.noticeKey}
    • -
    • {t.noticeHonest}
    • -
    • {t.noticeStorage}
    • -
    -
    -
    + +
      +
    • {t.noticeTheirPage}
    • +
    • {t.noticeKey}
    • +
    • {t.noticeHonest}
    • +
    • {t.noticeStorage}
    • +
    +
    )} -
    - - {t.waiting} -
    + {t.waiting}

    {t.hint}

    {phase.at === "form" && ( - )} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index f055a266..1806183a 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -11,6 +11,7 @@ import type { ChatgptLogin, ChatgptLoginMode, ChatgptLoginStatus, + CostBucketGroup, CostGroup, LatencyView, PriceQuery, @@ -26,14 +27,15 @@ import type { ZaiLoginStatus, } from "@/types"; +/** `upstream_stats`:一段时间里每个上游的请求与费用、首字节耗时、订阅额度和走势 */ export interface UpstreamStats { costs: CostGroup[]; latency: LatencyView[]; quotas: ProviderQuota[]; + /** 按 `bucketMs` 分格、按上游分开的请求数。**稀疏的**:没有请求的格子不在里面 */ + buckets: CostBucketGroup[]; } -/** 删除、开关这类不带正文的写入,要带上基于哪一版 */ - export const api = { createProvider: (save: ProviderSave) => call("CreateProvider", save), updateProvider: (name: string, save: ProviderSave) => call("UpdateProvider", save, name), @@ -47,7 +49,11 @@ export const api = { refreshProviderModels: (name: string) => call("RefreshProviderModels", null, name), /** 补问缺失、失败、过期的清单。**立刻回**,答案随 `models_changed` 到 */ refreshStaleModels: () => call("RefreshStaleModels", null), - upstreamStats: (sinceMs: number) => invoke("upstream_stats", { sinceMs }), + /** 起点和格宽都由界面给:格子对齐到本地整点(见 `bucketStart`) */ + upstreamStats: (sinceMs: number, bucketMs: number) => + invoke("upstream_stats", { sinceMs, bucketMs }), + /** 此刻在途的请求(开始事件的快照)。页面半路挂上时用它补齐 */ + inFlight: () => call("InFlight", null), createProxy: (save: ProxySave) => call("CreateProxy", save), updateProxy: (name: string, save: ProxySave) => call("UpdateProxy", save, name), diff --git a/src/upstreams/data.ts b/src/upstreams/data.ts new file mode 100644 index 00000000..31affe09 --- /dev/null +++ b/src/upstreams/data.ts @@ -0,0 +1,231 @@ +/** + * 上游页的几份数据:24 小时统计、默认价目表的状态、账号类上游的账号信息、在途请求。 + * + * 前三份走 `useResource`:切走再回来先画上一次的数,后台再取,不闪。在途请求是 + * 跟着事件流走的一份现状,不缓存。 + */ +import { useEffect, useMemo, useRef, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { bucketStart } from "@/format"; +import { useResource, type Resource } from "@/lib/resource"; +import type { ChatgptUsage, CoreEvent, CostBucketGroup, ProviderView } from "@/types"; +import { useNow } from "@/useNow"; +import { api, type UpstreamStats } from "./api"; + +export const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +/** 走势画几格:24 个整点,加上现在所在的这一小时 */ +export const SLOTS = 25; + +/** + * 「24 小时」从哪一刻算起:**对齐到整点**,和概览实时档的起点是同一个 + * (`windowStart` 的 live 分支)。两页上的「24 小时」数字对得上,走势的格子 + * 也不会随着看的时刻来回滑。 + */ +export function dayStart(now: number): number { + return bucketStart(now - DAY, HOUR); +} + +/** + * 每个上游 24 小时的请求、费用、首字节耗时、订阅额度和按小时的走势。 + * + * **请求落地之后重读**,不按时间轮询:这些数只在请求落地时才变。随时间变的只有 + * 窗口本身 —— 起点每过一个整点往前挪一格(`deps`),窗口重新拿到焦点时补一次。 + * 订阅额度的事件里就是完整的数,收到直接换上。 + */ +export function useUpstreamStats(): { stats: Resource; since: number } { + const now = useNow(60_000); + const since = dayStart(now); + const stats = useResource("upstream-stats", () => api.upstreamStats(since, HOUR), { + events: ["request_finished", "request_failed", "request_cancelled"], + deps: [since], + }); + const { mutate, reload } = stats; + + useEffect(() => { + const un = listen("core-event", (e) => { + const ev = e.payload; + if (ev.kind !== "quota_seen") return; + mutate( + patch((s) => ({ + ...s, + quotas: [ + ...s.quotas.filter((q) => q.provider !== ev.provider), + { provider: ev.provider, windows: ev.windows }, + ], + })), + ); + }); + return () => void un.then((f) => f()); + }, [mutate]); + + useEffect(() => { + const again = () => void reload(); + window.addEventListener("focus", again); + return () => window.removeEventListener("focus", again); + }, [reload]); + + return { stats, since }; +} + +/** 给 `mutate` 用:手里还没有数据时什么都不改(`mutate` 要的是一个新值,拿不出就原样还回去) */ +export function patch(f: (s: T) => T): (s: T | undefined) => T { + return (s) => (s === undefined ? (s as unknown as T) : f(s)); +} + +/** 一个小时格:请求数、其中失败的 */ +export interface Slot { + at: number; + requests: number; + failed: number; +} + +/** + * 把稀疏的格子按上游摊成定长的一排(`SLOTS` 格)。**没有请求的小时也要占一格**: + * 跳过的话,一天里的空档被两边挤没,走势看起来就是一直在用。 + */ +export function slotsByUpstream(buckets: CostBucketGroup[] | undefined, since: number): Map { + const out = new Map(); + for (const b of buckets ?? []) { + const i = Math.round((b.at_ms - since) / HOUR); + if (i < 0 || i >= SLOTS) continue; + let row = out.get(b.name); + if (!row) { + row = Array.from({ length: SLOTS }, (_, k) => ({ at: since + k * HOUR, requests: 0, failed: 0 })); + out.set(b.name, row); + } + row[i]!.requests += b.requests; + row[i]!.failed += b.failed; + } + return out; +} + +/** 默认价目表的状态。配置换了一版(改了价目表、开关了自动更新)就重读 */ +export function usePricingStatus(configVersion: string) { + return useResource("pricing-status", () => api.pricingStatus(), { deps: [configVersion] }); +} + +/** + * 账号类上游:**打开这一页时问一次它自己。** + * + * 一次问答同时回答三件事:登的是哪个账号、什么套餐、额度还剩多少。这三件都不在 + * 配置里 —— 额度平时是跟着真实流量白捡的,刚启动、或者这个账号今天还没被用过时, + * 不问就什么都没有。问一次是一次真实调用:**失败了也不重试**,连不上时反复问只会 + * 把错误刷满日志;单个账号问不到不影响别的。问完 core 也记下了额度,`onAnswered` + * 让统计从 core 再读一遍,免得这里和它各存一份。 + */ +export function useAccounts(providers: ProviderView[], onAnswered: () => void): Record { + const names = providers + .filter((p) => p.protocol === "chatgpt" && !p.disabled) + .map((p) => p.name) + .sort(); + const key = names.join("\n"); + const answered = useRef(onAnswered); + answered.current = onAnswered; + const r = useResource( + names.length > 0 ? "upstream-accounts" : null, + async () => { + const got = await Promise.all( + names.map((n) => + api + .chatgptUsage(n) + .then((u) => [n, u] as const) + .catch(() => null), + ), + ); + const found = got.filter((g) => g !== null); + if (found.length > 0) answered.current(); + return Object.fromEntries(found) as Record; + }, + { deps: [key] }, + ); + return r.data ?? NO_ACCOUNTS; +} + +const NO_ACCOUNTS: Record = {}; + +/** 在途请求记住多少条已经结束的 id(结束事件比快照先到时用来排除)。只是防御性的上限 */ +const ENDED_CAP = 512; + +/** + * 此刻每个上游有几个请求在途。 + * + * 开始事件里就有上游;换了上游(转移)以 `request_routed` 的最后一跳为准;三种结局 + * 都算结束。**页面半路挂上**时,已经在飞的那几个没有开始事件可听 —— 挂上时读一次 + * `/in-flight` 的快照补上(比快照先到的结束事件记下来,免得补回一个已经结束的)。 + * core 停了、重启了,在途的全部作废:它们不会再有结局。 + */ +export function useInFlight(): ReadonlyMap { + const live = useRef(new Map()); + const ended = useRef(new Set()); + const [tick, setTick] = useState(0); + + useEffect(() => { + let alive = true; + const bump = () => alive && setTick((n) => n + 1); + const seed = () => { + api + .inFlight() + .then((evs) => { + if (!alive) return; + for (const ev of evs) { + if (ev.kind !== "request_started" || ended.current.has(ev.id) || live.current.has(ev.id)) continue; + live.current.set(ev.id, ev.provider); + } + bump(); + }) + .catch(() => { + // 读不到快照:之后的开始事件照样记,只是漏掉此刻已经在飞的几个 + }); + }; + const end = (id: number) => { + live.current.delete(id); + ended.current.add(id); + if (ended.current.size > ENDED_CAP) { + const oldest = ended.current.values().next().value; + if (oldest !== undefined) ended.current.delete(oldest); + } + }; + const unEvents = listen("core-event", (e) => { + const ev = e.payload; + switch (ev.kind) { + case "request_started": + if (!ended.current.has(ev.id)) live.current.set(ev.id, ev.provider); + break; + case "request_routed": { + const last = ev.attempts[ev.attempts.length - 1]; + if (last && live.current.has(ev.id)) live.current.set(ev.id, last.provider); + break; + } + case "request_finished": + case "request_failed": + case "request_cancelled": + end(ev.id); + break; + default: + return; + } + bump(); + }); + const unState = listen("core-state", (e) => { + live.current.clear(); + bump(); + if (e.payload.startsWith("running:")) seed(); + }); + seed(); + return () => { + alive = false; + void unEvents.then((f) => f()); + void unState.then((f) => f()); + }; + }, []); + + return useMemo(() => { + const by = new Map(); + for (const provider of live.current.values()) by.set(provider, (by.get(provider) ?? 0) + 1); + return by; + // `tick` 是 `live` 这份可变状态的版本号 + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tick]); +} diff --git a/src/upstreams/parts.tsx b/src/upstreams/parts.tsx index b97d9fba..09513fce 100644 --- a/src/upstreams/parts.tsx +++ b/src/upstreams/parts.tsx @@ -1,36 +1,83 @@ /** * 上游页几张表和几个对话框共用的小件。 */ -import type { ReactNode } from "react"; +import type { KeyboardEvent, MouseEvent, ReactNode } from "react"; import { cn } from "@/lib/utils"; +import { Banner } from "@/ui/banner"; +import { Button } from "@/ui/button"; import { Label } from "@/ui/label"; +import { Logo, upstreamGlyph } from "@/ui/logos"; +import { StatusDot } from "@/ui/status-dot"; +import type { ProviderView } from "@/types"; -/** 状态点:正常、需要留意、失败、已停用 */ -export function StatusDot({ - tone, - children, +/** + * 上游的标志,放在一块小方片上:列表的每一行、编辑对话框的标题、服务类型的下拉。 + * + * **方片而不是光秃秃的图标**:各家标志的外形差得很远(一个圆、一个字母、一串 + * 笔画),放进同样大小的方片里一列才对得齐;认不出来的上游写首字母,同一块方片。 + * 标志一律单色,跟着文字色走(见 `@/ui/logos`)。 + * + * `live`:此刻有请求正经它转发 —— 角上一个跳动的点。 + */ +export function VendorTile({ + name, + baseUrl, + protocol, + size = "md", + muted = false, + live = false, + className, }: { - tone: "ok" | "warn" | "bad" | "off"; - children: ReactNode; + name: string; + baseUrl?: string | null; + protocol?: string | null; + /** `md` 28px(表格行);`sm` 20px(下拉、标签里) */ + size?: "sm" | "md"; + /** 停用的上游:整块退成次要色 */ + muted?: boolean; + live?: boolean; + className?: string; }) { + const id = upstreamGlyph({ name, baseUrl, protocol }); + const px = size === "md" ? 16 : 12; return ( - - - {children} + + {id ? ( + + ) : ( + {initial(name)} + )} + {live && } ); } -/** 一组名称标签(使用上游、引用它的上游)。空的时候说清是空的 */ +/** 名字里第一个字母或数字,大写 */ +function initial(name: string): string { + return Array.from(name.trim().replace(/^[^\p{L}\p{N}]+/u, ""))[0]?.toUpperCase() ?? "?"; +} + +/** 上游的标志:直接给一条 `ProviderView` */ +export function ProviderTile({ + p, + ...rest +}: { p: Pick } & Omit< + Parameters[0], + "name" | "baseUrl" | "protocol" +>) { + return ; +} + +/** 一组名称标签(使用某个代理、某张价目表的上游)。空的时候说清是空的 */ export function NameChips({ names, empty }: { names: string[]; empty: string }) { if (names.length === 0) { return {empty}; @@ -40,7 +87,7 @@ export function NameChips({ names, empty }: { names: string[]; empty: string }) {names.map((n) => ( {n} @@ -49,6 +96,97 @@ export function NameChips({ names, empty }: { names: string[]; empty: string }) ); } +/** + * 一组上游的名称标签,各带标志。名字是用户起的(`relay-hk`),标志说的是它 + * 实际连到哪一家 —— 在「使用上游」这种一列名字里,比名字本身更快认得出。 + */ +export function UpstreamChips({ + names, + providers, + empty, +}: { + names: string[]; + providers: Pick[]; + empty: string; +}) { + if (names.length === 0) { + return {empty}; + } + return ( + + {names.map((n) => { + const p = providers.find((x) => x.name === n); + const id = upstreamGlyph({ name: n, baseUrl: p?.base_url, protocol: p?.protocol }); + return ( + + {id ? ( + + ) : ( + + {initial(n)} + + )} + {n} + + ); + })} + + ); +} + +/** + * 只读列表的一行:**单击打开**它的对话框,键盘上 Enter / 空格同样打开。 + * + * edit(p.name), rowMotion(presence))}> + * + * 行里的按钮(模型数、行尾菜单)自己处理点击,外面挂 `keepInRow` 不让它冒泡成 + * 「打开这一行」。焦点来自键盘时左边描一道,鼠标点的不描(`focus-visible`)。 + */ +export function openRow(open: () => void, className?: string) { + return { + tabIndex: 0, + onClick: (e: MouseEvent) => { + // 选中文字不算点击:拖着选一段地址时不该弹出对话框 + if (window.getSelection()?.toString()) return; + if (e.defaultPrevented) return; + open(); + }, + onKeyDown: (e: KeyboardEvent) => { + if (e.target !== e.currentTarget) return; + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + open(); + } + }, + className: cn( + "cursor-default outline-none focus-visible:bg-muted/60 focus-visible:shadow-[inset_2px_0_0_0_var(--ring)]", + className, + ), + }; +} + +/** 行里自己能点的那一格:点击和按键不再冒泡成「打开这一行」 */ +export const keepInRow = { + onClick: (e: MouseEvent) => e.stopPropagation(), + onKeyDown: (e: KeyboardEvent) => e.stopPropagation(), +}; + +/** + * 对话框里的报错。**上游页所有对话框只用这一种**:一块红色的行内横幅,出现和 + * 消失都带动画(`Banner show`)。保存、检测、删除失败都在这里说;原因是 core + * 给的那一句,按消息码翻译过(调用方传 `errorText` 之后的文字)。 + */ +export function DialogError({ error, className }: { error: string | null; className?: string }) { + return ( + + {error} + + ); +} + /** 表单里的一项:标签在上,说明在下 */ export function FormItem({ label, @@ -78,49 +216,6 @@ export function FormItem({ ); } -// 挪到了 `@/ui/segmented`:全应用的单选都用它,不只是上游页 -export { Segmented } from "@/ui/segmented"; - -/** 单选的一行:圆点 + 标题 + 说明 */ -export function RadioRow({ - checked, - title, - desc, - onSelect, - disabled, -}: { - checked: boolean; - title: string; - desc: ReactNode; - onSelect: () => void; - disabled?: boolean; -}) { - return ( - - ); -} - /** 对话框顶部的分节导航。新建时按顺序走,编辑时随意切换 */ export function StepNav({ steps, @@ -142,20 +237,18 @@ export function StepNav({ return (
  • {i > 0 && } - +
  • ); })} @@ -180,7 +273,12 @@ export function Boxed({ className, children }: { className?: string; children: R ); } -/** 对话框里一段说明或提示 */ +/** + * 对话框里一段说明或提示。`warning` 给要留意的一句(会产生费用、会改掉别的设置)。 + * + * **报错不用它**:上游页的对话框报错一律 `DialogError`。`error` 这一档还留着,是因为 + * 路由页的几个对话框也从这里取 `Note`(它们归那一页自己迁)。 + */ export function Note({ tone = "muted", children, @@ -201,3 +299,46 @@ export function Note({

    ); } + +// 挪到了 `@/ui/segmented`:全应用的单选都用它。设置页、密钥页、路由页还从这里取 +export { Segmented } from "@/ui/segmented"; + +/** 单选的一行:圆点 + 标题 + 说明(路由页的分组对话框在用) */ +export function RadioRow({ + checked, + title, + desc, + onSelect, + disabled, +}: { + checked: boolean; + title: string; + desc: ReactNode; + onSelect: () => void; + disabled?: boolean; +}) { + return ( + + ); +} From 32ca9f0cd2597a387031e18156a89df0b8ce9caf Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 06:55:49 +0800 Subject: [PATCH 2/3] Upstreams: fit the smallest window, proxy rows like upstream rows, banner tones - Narrow window (820x560, English): the name column no longer collapses. The plan badge folds away and a row's problem shrinks to its dot (the tooltip still says what it is); the quota column narrows; "Selected models" under the model count becomes "Selected". - Secondary header actions (connection test, inference test, check all, update now) turn into icon buttons with a tooltip when the page is narrow, so the header summary stays at two lines. CSS container query on the page, no JS measuring and no flash. - Proxies: type, address and authentication move into a line under the name, like the upstream rows. Seven columns pushed the row menu out of view at the minimum window size. - Price sheets: shorter English column header so the table fits; the default price sheet dialog lists its upstreams as logo chips like everywhere else. - Banner tones: a failed read of the 24-hour statistics or of the price sheet status is a warning (the page keeps working); a failed price update is an error only when no prices were ever loaded. - Disabled upstreams: their 24-hour and latency figures are muted with the row. - The reset-credit confirmation uses the kit Banner instead of Alert; English hero plural for "need attention"; long proxy check failures wrap. - Tests for the hourly slots behind the sparkline. Co-Authored-By: Claude Opus 5.5 --- src/upstreams/ChatgptAccountSection.tsx | 12 ++- src/upstreams/PriceSheetDialog.i18n.ts | 2 - src/upstreams/PriceSheetDialog.tsx | 7 +- src/upstreams/PriceSheetTable.i18n.ts | 2 +- src/upstreams/ProxyDialog.tsx | 10 ++- src/upstreams/ProxyTable.i18n.ts | 15 ++-- src/upstreams/ProxyTable.tsx | 21 +++--- src/upstreams/UpstreamTable.tsx | 28 +++++-- src/upstreams/UpstreamsPage.i18n.tsx | 4 +- src/upstreams/UpstreamsPage.tsx | 99 ++++++++++++++++++------- src/upstreams/data.test.ts | 63 ++++++++++++++++ src/upstreams/labels.i18n.ts | 3 +- 12 files changed, 192 insertions(+), 74 deletions(-) create mode 100644 src/upstreams/data.test.ts diff --git a/src/upstreams/ChatgptAccountSection.tsx b/src/upstreams/ChatgptAccountSection.tsx index ddd8f080..6e5a68c5 100644 --- a/src/upstreams/ChatgptAccountSection.tsx +++ b/src/upstreams/ChatgptAccountSection.tsx @@ -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, @@ -12,6 +11,7 @@ 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"; @@ -238,11 +238,9 @@ export function ChatgptAccountSection({ {t.confirmTitle} {t.confirmDesc} - - - {t.notConsumedTitle} - {t.notConsumedDesc} - + + {t.notConsumedDesc} + {common.cancel} `显示前 ${shown} 个,共 ${matched.toLocaleString()} 个匹配。输入模型名称缩小范围。`, usedByTitle: "使用此价目表的上游", - names: (names: string[]) => names.join("、"), notUsed: "未被使用", noPerToken: "尚无按量计费的上游。", switchHint: (sheet: string) => `当前使用价目表「${sheet}」,选中后改用此价目表`, @@ -99,7 +98,6 @@ export const priceSheetDialogText = messages( truncated: (shown: number, matched: number) => `Showing the first ${shown} of ${matched.toLocaleString()} ${matched === 1 ? "match" : "matches"}. Type a model name to narrow the list.`, usedByTitle: "Upstreams using this price sheet", - names: (names: string[]) => names.join(", "), notUsed: "Not in use", noPerToken: "No upstreams are billed per token yet.", switchHint: (sheet: string) => diff --git a/src/upstreams/PriceSheetDialog.tsx b/src/upstreams/PriceSheetDialog.tsx index 388d30ce..30ad2811 100644 --- a/src/upstreams/PriceSheetDialog.tsx +++ b/src/upstreams/PriceSheetDialog.tsx @@ -42,7 +42,7 @@ import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { PRICE_COLUMNS, errorText, perMillion, priceSourceLabel } from "./labels"; -import { Boxed, DialogError, FormItem, Note } from "./parts"; +import { Boxed, DialogError, FormItem, Note, UpstreamChips } from "./parts"; import { priceSheetDialogText } from "./PriceSheetDialog.i18n"; import { defaultSheetUsers } from "./PriceSheetTable"; @@ -618,9 +618,8 @@ export function PriceSheetDialog({
    {t.usedByTitle} {readOnly ? ( - - {usedBy.length ? t.names(usedBy) : {t.notUsed}} - + // 和价目表列表「使用上游」那一列一样:名字带标志 + ) : perTokenProviders.length === 0 ? ( {t.noPerToken} ) : ( diff --git a/src/upstreams/PriceSheetTable.i18n.ts b/src/upstreams/PriceSheetTable.i18n.ts index a46e3776..a2238565 100644 --- a/src/upstreams/PriceSheetTable.i18n.ts +++ b/src/upstreams/PriceSheetTable.i18n.ts @@ -27,7 +27,7 @@ export const priceSheetTableText = messages( name: "Name", basis: "Based on", multiplier: "Multiplier", - overrides: "Model overrides", + overrides: "Overrides", usedBy: "Used by", actionsColumn: "Actions", defaultSheet: "Default price sheet", diff --git a/src/upstreams/ProxyDialog.tsx b/src/upstreams/ProxyDialog.tsx index 7c23e91b..a7719415 100644 --- a/src/upstreams/ProxyDialog.tsx +++ b/src/upstreams/ProxyDialog.tsx @@ -11,7 +11,7 @@ import { } from "@/ui/dialog"; import { Input } from "@/ui/input"; import { Segmented } from "@/ui/segmented"; -import { StatusLabel } from "@/ui/status-dot"; +import { StatusDot, StatusLabel } from "@/ui/status-dot"; import { Switch } from "@/ui/switch"; import type { L1Result, Overview, ProxyAuthInput, ProxyInput, ProxyView } from "@/types"; import { useText } from "@/i18n"; @@ -217,9 +217,11 @@ export function ProxyDialog({ {t.ok(auth, result.total_ms)} ) : ( - - {l1ErrorText(result)} - + // 失败的原因可能很长(卡在哪一步、为什么):折行写全,不截断 +

    + + {l1ErrorText(result)} +

    ) ) : ( {t.checkHint} diff --git a/src/upstreams/ProxyTable.i18n.ts b/src/upstreams/ProxyTable.i18n.ts index 2f98ba97..383ee2f3 100644 --- a/src/upstreams/ProxyTable.i18n.ts +++ b/src/upstreams/ProxyTable.i18n.ts @@ -2,17 +2,15 @@ import { messages } from "@/i18n"; export const proxyTableText = messages( { - name: "名称", - kind: "类型", - address: "地址", - auth: "认证", + proxy: "代理", usedBy: "使用上游", connectivity: "连通性", actionsColumn: "操作", edit: "编辑…", check: "检测代理", delete: "删除…", - userPass: "用户名与密码", + /** 名字下面那一行的最后一段:这个代理要用户名与密码 */ + withAuth: "需要认证", notUsed: "未被使用", actions: (name: string) => `${name} 的操作`, notChecked: "未检测", @@ -21,17 +19,14 @@ export const proxyTableText = messages( ms: (n: number) => `${n.toLocaleString()} ms`, }, { - name: "Name", - kind: "Type", - address: "Address", - auth: "Authentication", + proxy: "Proxy", usedBy: "Used by", connectivity: "Connectivity", actionsColumn: "Actions", edit: "Edit…", check: "Check proxy", delete: "Delete…", - userPass: "Username and password", + withAuth: "requires authentication", notUsed: "Not in use", actions: (name: string) => `Actions for ${name}`, notChecked: "Not checked", diff --git a/src/upstreams/ProxyTable.tsx b/src/upstreams/ProxyTable.tsx index 40b7a484..5ec65c13 100644 --- a/src/upstreams/ProxyTable.tsx +++ b/src/upstreams/ProxyTable.tsx @@ -5,7 +5,6 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { Tip } from "@/ui/tip"; import type { L1Result, ProviderView, ProxyFault, ProxyView } from "@/types"; import { useText } from "@/i18n"; -import { commonText } from "@/i18n/common.i18n"; import { l1ErrorText, proxyFaultText, proxyKindLabel } from "./labels"; import { UpstreamChips, keepInRow, openRow } from "./parts"; import { proxyTableText } from "./ProxyTable.i18n"; @@ -15,6 +14,9 @@ export type ProxyCheck = { running: true } | { running: false; result: L1Result; /** * 出站代理列表。**只读**:单击一行(或 Enter)编辑,行尾按钮和右键是同一份操作。 + * + * 和上游表一样,名字下面一行说它是什么、在哪(类型 · 地址 · 是否认证)。这三样 + * 原来各占一列,最小窗口里七列放不下,行尾菜单被挤到视野外。 */ export function ProxyTable({ proxies, @@ -33,16 +35,12 @@ export function ProxyTable({ onRemove: (name: string) => void; }) { const t = useText(proxyTableText); - const common = useText(commonText); const shown = usePresentList(proxies, (x) => x.name); return ( - {t.name} - {t.kind} - {t.address} - {t.auth} + {t.proxy} {t.usedBy} {t.connectivity} @@ -61,11 +59,12 @@ export function ProxyTable({ return ( onEdit(x.name), rowMotion(presence))}> - {x.name} - {proxyKindLabel(x.kind)} - {x.addr} - - {x.has_auth ? t.userPass : common.none} + +
    {x.name}
    +
    + {proxyKindLabel(x.kind)} · {x.addr} + {x.has_auth && ` · ${t.withAuth}`} +
    diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index f8e71c1a..744d6b58 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -7,7 +7,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; import { Skeleton } from "@/ui/skeleton"; import { Spinner } from "@/ui/spinner"; -import { StatusLabel, type StatusTone } from "@/ui/status-dot"; +import { StatusDot, StatusLabel, type StatusTone } from "@/ui/status-dot"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; import { Tip } from "@/ui/tip"; import { resetAt } from "@/format"; @@ -108,7 +108,7 @@ export function UpstreamTable({ {t.upstream} {t.models} {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} - {t.quota} + {t.quota} {t.day} {t.ttfb} @@ -221,10 +221,18 @@ function NameCell({ tile )}
    + {/* + 名字排第一。表格那一栏窄了(小窗口、英文)时,套餐标签先收起来,状态只留 + 一个点(悬停照样看得到是什么)—— 不然名字会被挤得一个字都不剩 + */}
    {p.name} {/* 订阅类账号:套餐决定了额度有多大,和名字放在一起看 */} - {plan && {plan}} + {plan && ( + + {plan} + + )} {problem && ( } > - - + + {problem.label} + )} @@ -440,7 +453,8 @@ function DayCell({
    ); return ( - + // 停用的上游:一天里的数照常给(它停用之前在用),但和整行一起退成次要色 + {/* 走势贴左、数字贴右,撑满这一格:各行的走势左边对齐、数字右边对齐, @@ -476,7 +490,7 @@ function LatencyCell({ p, stats }: { p: ProviderView; stats: Resource—; } return ( - + {t.ms(lat.p50)} diff --git a/src/upstreams/UpstreamsPage.i18n.tsx b/src/upstreams/UpstreamsPage.i18n.tsx index e1a3c83c..aaa9900f 100644 --- a/src/upstreams/UpstreamsPage.i18n.tsx +++ b/src/upstreams/UpstreamsPage.i18n.tsx @@ -12,7 +12,7 @@ export const upstreamsPageText = messages( hero: { upstreams: (n: ReactNode, _count: number) => <>{n} 个上游, healthy: (n: ReactNode) => <>{n} 正常, - attention: (n: ReactNode) => <>{n} 需处理, + attention: (n: ReactNode, _count: number) => <>{n} 需处理, disabled: (n: ReactNode) => <>{n} 已停用, requests: (n: ReactNode, _count: number) => <>24 小时 {n} 次请求, cost: (n: ReactNode) => <>费用 {n}, @@ -60,7 +60,7 @@ export const upstreamsPageText = messages( hero: { upstreams: (n: ReactNode, count: number) => <>{n} {count === 1 ? "upstream" : "upstreams"}, healthy: (n: ReactNode) => <>{n} healthy, - attention: (n: ReactNode) => <>{n} need attention, + attention: (n: ReactNode, count: number) => <>{n} {count === 1 ? "needs" : "need"} attention, disabled: (n: ReactNode) => <>{n} disabled, requests: (n: ReactNode, count: number) => <>{n} {count === 1 ? "request" : "requests"} in 24 h, cost: (n: ReactNode) => <>Cost {n}, diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 4ab35015..837bfb4e 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -13,6 +13,7 @@ import { EmptyState } from "@/ui/states"; import { StatusDot } from "@/ui/status-dot"; import { Switch } from "@/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; +import { Tip } from "@/ui/tip"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { usd, type Overview, type PricingStatus, type ProviderView } from "@/types"; @@ -251,14 +252,16 @@ export default function UpstreamsPage({ <> {providers.length > 0 && ( <> - - + } + label={t.linkTest} + onClick={() => setDialog({ kind: "link", provider: null })} + /> + } + label={t.speedTest} + onClick={() => setDialog({ kind: "speed", provider: null })} + /> )} + /> )} + } + label={t.updateNow} + pending={updatingPrices} + onClick={() => void refreshPrices()} + /> + + + + + ); +} + /** 摘要里的一项:可选的状态点,加一句带数字的话。样子和 `SummaryItem` 一样 */ function Fact({ lead, children }: { lead?: ReactNode; children: ReactNode }) { return ( @@ -618,7 +662,8 @@ function Num({ value, format }: { value: number; format?: (n: number) => ReactNo /** * 价目表标签顶上的几条:默认价目表读不到状态、上一次更新失败、最近有请求无法计价。 - * 都是持续成立的事,用横幅,不用吐司。 + * 都是持续成立的事,用横幅,不用吐司。读不到状态和「上游」标签读不到统计一样是 + * 琥珀:列表照常能用,只是少了几个数。 */ function PricingNotices({ ov, @@ -642,7 +687,7 @@ function PricingNotices({ void status.reload()}> @@ -652,10 +697,14 @@ function PricingNotices({ > {status.error !== undefined ? errorText(status.error) : null} + {/* + 更新失败时仍按上一次拉到的价格计价(琥珀);**一次都没拉到过**才是真坏了 —— + 那时按量计费的请求全都无法计价(红) + */} diff --git a/src/upstreams/data.test.ts b/src/upstreams/data.test.ts new file mode 100644 index 00000000..f5193026 --- /dev/null +++ b/src/upstreams/data.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import type { CostBucketGroup } from "@/types"; +import { HOUR, SLOTS, dayStart, slotsByUpstream } from "./data"; + +function bucket(name: string, at: number, requests: number, failed = 0): CostBucketGroup { + return { + at_ms: at, + name, + requests, + failed, + cost_micros_exact: 0, + cost_micros_estimated: 0, + input_tokens: 0, + output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, + }; +} + +describe("dayStart", () => { + it("starts a day back, on a whole local hour", () => { + const now = new Date(2026, 8, 25, 16, 42, 7).getTime(); + expect(dayStart(now)).toBe(new Date(2026, 8, 24, 16).getTime()); + }); + + it("does not move while the hour lasts", () => { + expect(dayStart(new Date(2026, 8, 25, 16, 0, 1).getTime())).toBe( + dayStart(new Date(2026, 8, 25, 16, 59, 59).getTime()), + ); + }); +}); + +describe("slotsByUpstream", () => { + const since = new Date(2026, 8, 24, 16).getTime(); + + it("gives every hour a slot, with requests or not, ending at the current hour", () => { + const row = slotsByUpstream([bucket("a", since + 3 * HOUR, 5, 1)], since).get("a")!; + expect(row).toHaveLength(SLOTS); + expect(row[0]!.at).toBe(since); + expect(row[SLOTS - 1]!.at).toBe(since + (SLOTS - 1) * HOUR); + expect(row[3]).toEqual({ at: since + 3 * HOUR, requests: 5, failed: 1 }); + expect(row.filter((s) => s.requests > 0)).toHaveLength(1); + }); + + it("keeps upstreams apart and leaves out buckets outside the window", () => { + const by = slotsByUpstream( + [ + bucket("a", since, 1), + bucket("b", since, 2), + bucket("a", since - HOUR, 9), + bucket("a", since + SLOTS * HOUR, 9), + ], + since, + ); + expect(by.get("a")!.reduce((n, s) => n + s.requests, 0)).toBe(1); + expect(by.get("b")![0]!.requests).toBe(2); + }); + + it("has no row for an upstream without requests in the window", () => { + expect(slotsByUpstream(undefined, since).size).toBe(0); + expect(slotsByUpstream([bucket("a", since - 2 * HOUR, 3)], since).has("a")).toBe(false); + }); +}); diff --git a/src/upstreams/labels.i18n.ts b/src/upstreams/labels.i18n.ts index b618e70e..935c86af 100644 --- a/src/upstreams/labels.i18n.ts +++ b/src/upstreams/labels.i18n.ts @@ -89,7 +89,8 @@ export const labelsText = messages( noList: "No list provided", notFetched: "Not fetched", fetching: "Fetching", - scoped: "Selected models", + // 模型数下面的一个词:「5 / Selected」。对话框里那一项叫 Selected models + scoped: "Selected", }, quotaWindows: { "5h": "5h", "7d": "7d", weekly: "Weekly" }, l1Steps: { From 37564100559e3d172ff3b89499263cf37cdefeb9 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 07:18:18 +0800 Subject: [PATCH 3/3] Upstreams: sparkline in the Keys page's style, one page breakpoint, dead parts - The 24-hour sparkline now looks like the one on the Keys page (#190): 2px chart-coloured bars, 16px tall, the current hour emphasised, a faint baseline for empty hours. What stays specific to upstreams: failures are a red cap on the hour they happened in, and a single request does not fill the bar. - Every narrow-window rule on the page (sparkline, plan badge, problem dot, quota width, icon-only header actions) keys off the page container at the Keys page's breakpoint (48rem) instead of a table-level container. - Removed NameChips and RadioRow (no callers left after #191) and Note's error tone (dialog errors are DialogError). Co-Authored-By: Claude Opus 5.5 --- src/upstreams/Sparkline.tsx | 54 ++++++++-------- src/upstreams/UpstreamTable.tsx | 109 ++++++++++++++++---------------- src/upstreams/UpstreamsPage.tsx | 6 +- src/upstreams/parts.tsx | 75 ++-------------------- 4 files changed, 90 insertions(+), 154 deletions(-) diff --git a/src/upstreams/Sparkline.tsx b/src/upstreams/Sparkline.tsx index c0f5b1ac..1707281b 100644 --- a/src/upstreams/Sparkline.tsx +++ b/src/upstreams/Sparkline.tsx @@ -1,9 +1,6 @@ import { cn } from "@/lib/utils"; import { SLOTS, type Slot } from "./data"; -/** 柱高多少像素。和两行字(次数、费用)叠起来差不多高 */ -const HEIGHT = 20; - /** * 纵轴的下限:一小时里只有一两个请求时,柱子不该顶满。 * @@ -13,41 +10,48 @@ const HEIGHT = 20; */ const MIN_PEAK = 4; -/** 一根柱子 3px、间隔 1px,一共 `SLOTS` 根。读到之前的占位按这个宽度画 */ -export const SPARKLINE_WIDTH = SLOTS * 4 - 1; +/** 一根柱子 2px、间隔 1px,一共 `SLOTS` 根。读到之前的占位按这个宽度画 */ +export const SPARKLINE_WIDTH = SLOTS * 3 - 1; /** * 一天的走势:一小时一根柱子,最右边是现在这一小时。 * - * **没有请求的小时也占一格**,画成贴底的一道细线 —— 跳过的话空档被挤没,看起来 - * 就是一直在用。失败的那一截画在柱顶、用红色:失败集中在哪个小时一眼看得见。 + * **和密钥页的小柱图同一个样子**(柱宽、高度、配色、空格子的底线),两页并排看是 + * 同一套东西;多出来的一样是失败:这一小时里失败的那一截画在柱顶、用红色 —— + * 上游好不好,看的就是失败落在哪几个小时。 * - * 用普通的块元素画,不用 SVG:高度变化要能走过渡(`motion-bar`),而 WebKit - * 对 SVG 几何属性的过渡支持不齐。 + * **没有请求的小时也占一格**,画成一道很淡的底线:跳过的话空档被挤没,看起来就是 + * 一直在用。用普通的块元素画,不用 SVG:高度变化要能走过渡(`motion-bar`),而 + * WebKit 对 SVG 几何属性的过渡支持不齐。 */ export function Sparkline({ slots, className }: { slots: Slot[]; className?: string }) { const peak = Math.max(MIN_PEAK, ...slots.map((s) => s.requests)); + const last = slots.length - 1; return ( -
    - {slots.map((s) => { - if (s.requests === 0) return
    ; - const h = Math.max(2, Math.round((s.requests / peak) * HEIGHT)); - const bad = s.failed > 0 ? Math.min(h, Math.max(2, Math.round((s.failed / s.requests) * h))) : 0; + + {slots.map((s, i) => { + if (s.requests === 0) return ; + const share = s.requests / peak; + const bad = s.failed / s.requests; return ( -
    - {bad > 0 &&
    } -
    + {bad > 0 && ( + + )} + ); })} -
    +
    ); } diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 744d6b58..c5b2dea1 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -57,7 +57,7 @@ export interface UpstreamActions { * * 五列是定过的(lite#46):上游、模型、额度 / 计费、24 小时、首字节 P50。「24 小时」 * 一格里多了一条按小时的走势:请求在一天里怎么分布、失败落在哪几个小时,一眼看得出, - * 数字留给右边和悬停。窗口窄到放不下时走势先让位(容器查询),数字照常在。 + * 数字留给右边和悬停。窗口窄到放不下时走势先让位(页面的容器查询),数字照常在。 */ export function UpstreamTable({ providers, @@ -100,55 +100,54 @@ export function UpstreamTable({ return () => clearTimeout(h); }, [focus]); return ( - // 容器查询:表格那一栏窄了(默认窗口里约 860px,最窄约 580px),走势先收起来 -
    -
    - - - {t.upstream} - {t.models} - {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} - {t.quota} - {t.day} - {t.ttfb} - - {t.actionsColumn} - - - - - {shown.map(({ item: p, key, presence }) => { - const items = menu(p, actions); - return ( - - actions.edit(p.name), rowMotion(flash === p.name ? "enter" : presence))} - > - 0 && !p.disabled} - liveCount={inFlight.get(p.name) ?? 0} - /> - actions.editModels(p.name)} - /> - - - - - - - - - ); - })} - -
    -
    + // 窄窗口的几处让位(走势、套餐标签、状态文字)看的是页面这个容器(`@container/page`, + // 和密钥页同一个断点):默认窗口里内容约 860px,最窄约 580px + + + + {t.upstream} + {t.models} + {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} + {t.quota} + {t.day} + {t.ttfb} + + {t.actionsColumn} + + + + + {shown.map(({ item: p, key, presence }) => { + const items = menu(p, actions); + return ( + + actions.edit(p.name), rowMotion(flash === p.name ? "enter" : presence))} + > + 0 && !p.disabled} + liveCount={inFlight.get(p.name) ?? 0} + /> + actions.editModels(p.name)} + /> + + + + + + + + + ); + })} + +
    ); } @@ -229,7 +228,7 @@ function NameCell({ {p.name} {/* 订阅类账号:套餐决定了额度有多大,和名字放在一起看 */} {plan && ( - + {plan} )} @@ -247,11 +246,11 @@ function NameCell({ {problem.label} - +
    )} @@ -428,7 +427,7 @@ function DayCell({ {stats.loading ? ( // 和读到之后一样宽:走势的位置先占上,数字到了列宽不跳
    - +
    ) : ( @@ -461,7 +460,7 @@ function DayCell({ 不随「201 次」「7 次」的宽窄左右错开 */}
    - {slots && } + {slots && }
    t.requests(Math.round(n))} /> diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 837bfb4e..fde1d9dc 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -315,7 +315,7 @@ export default function UpstreamsPage({ return ( setTab(v as UpstreamTab)} className="gap-0"> - {/* 具名容器:页头的次要操作按这一页有多宽决定写不写字(见 `HeaderAction`) */} + {/* 具名容器:窄了之后页头的次要操作只画图标、表格收起走势(和密钥页同一个断点) */} - @@ -635,7 +635,7 @@ function HeaderAction({ size="icon-sm" pending={pending} aria-label={label} - className="hidden @max-[46rem]/page:inline-flex" + className="hidden @max-3xl/page:inline-flex" onClick={onClick} > {!pending && icon} diff --git a/src/upstreams/parts.tsx b/src/upstreams/parts.tsx index 09513fce..56800bf1 100644 --- a/src/upstreams/parts.tsx +++ b/src/upstreams/parts.tsx @@ -77,25 +77,6 @@ export function ProviderTile({ return ; } -/** 一组名称标签(使用某个代理、某张价目表的上游)。空的时候说清是空的 */ -export function NameChips({ names, empty }: { names: string[]; empty: string }) { - if (names.length === 0) { - return {empty}; - } - return ( - - {names.map((n) => ( - - {n} - - ))} - - ); -} - /** * 一组上游的名称标签,各带标志。名字是用户起的(`relay-hk`),标志说的是它 * 实际连到哪一家 —— 在「使用上游」这种一列名字里,比名字本身更快认得出。 @@ -276,69 +257,21 @@ export function Boxed({ className, children }: { className?: string; children: R /** * 对话框里一段说明或提示。`warning` 给要留意的一句(会产生费用、会改掉别的设置)。 * - * **报错不用它**:上游页的对话框报错一律 `DialogError`。`error` 这一档还留着,是因为 - * 路由页的几个对话框也从这里取 `Note`(它们归那一页自己迁)。 + * **报错不用它**:对话框里的报错一律 `DialogError`。 */ export function Note({ tone = "muted", children, }: { - tone?: "muted" | "warning" | "error"; + tone?: "muted" | "warning"; children: ReactNode; }) { return ( -

    +

    {children}

    ); } -// 挪到了 `@/ui/segmented`:全应用的单选都用它。设置页、密钥页、路由页还从这里取 +// 挪到了 `@/ui/segmented`:全应用的单选都用它。设置里「外观」「提醒」两节还从这里取 export { Segmented } from "@/ui/segmented"; - -/** 单选的一行:圆点 + 标题 + 说明(路由页的分组对话框在用) */ -export function RadioRow({ - checked, - title, - desc, - onSelect, - disabled, -}: { - checked: boolean; - title: string; - desc: ReactNode; - onSelect: () => void; - disabled?: boolean; -}) { - return ( - - ); -}