From 0137334222f3f773685e03440e976cf561335eb5 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sat, 19 Sep 2026 15:50:38 +0800 Subject: [PATCH] feat: open any upstream's models from its row, and fetch missing lists without being asked The model column showed "not fetched" for upstreams core had not asked yet, upstreams whose key was refused and upstreams that offer no list, and it kept showing it after core had fetched them: a background fetch finished without an event, so the page kept what it read at startup. Seeing an upstream's models meant edit, then models, then refresh. - The model cell is a button in every state but disabled. Its second line says fetching, failed (in the warning colour), no list, manual list or narrowed range, and a spinner shows while a fetch runs. - It opens a panel: models in range with price and context window, the ones out of range folded below, a filter past ten models, when and where the list came from, and a refresh button. A failure shows the reason with retry and edit; an upstream without a list points to the manual list. Every edit entry opens the upstream dialog on its model section. - Opening the upstream page asks core to fetch lists that are missing, failed or out of date, and models_changed reloads the overview, so counts appear as each answer lands. - The dialog's model section follows the fetch state: it reloads when an answer lands, waits instead of asking for a manual list while one is being fetched, and its badge says failed or no list instead of "not fetched". Pins ThinkWatch-Core v0.8.2 (ThinkWatch-Core#47), which reports the fetch status, the models_changed event and POST /models/refresh. Co-Authored-By: Claude Opus 5 --- src-tauri/Cargo.lock | 4 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/control.rs | 5 + src-tauri/src/lib.rs | 1 + src-tauri/src/upstreams.rs | 8 + src/App.tsx | 4 +- src/types.ts | 26 +++ src/upstreams/ModelsPanel.tsx | 278 +++++++++++++++++++++++++++++ src/upstreams/ModelsSection.tsx | 33 +++- src/upstreams/UpstreamDialog.tsx | 21 ++- src/upstreams/UpstreamTable.tsx | 113 +++++------- src/upstreams/UpstreamsPage.tsx | 15 ++ src/upstreams/api.ts | 3 + src/upstreams/labels.test.ts | 57 ++++++ src/upstreams/labels.ts | 49 ++++- src/upstreams/upstreamForm.test.ts | 2 + src/useRequests.ts | 7 + 17 files changed, 532 insertions(+), 96 deletions(-) create mode 100644 src/upstreams/ModelsPanel.tsx create mode 100644 src/upstreams/labels.test.ts diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 9f5e1159..5d66e151 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4982,8 +4982,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.8.1" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.8.1#efdeb9381744f0a6371eaf807f2b32d177714e99" +version = "0.8.2" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.8.2#afee6593ff539efac541a2fa52247d622cf17ab8" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index f19cc943..bbcf7b1d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2" # 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制 # 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从 # 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。 -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.8.1" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.8.2" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 95005e3e..54edc5cc 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -568,6 +568,11 @@ impl ControlClient { .await } + /// 补问缺失、失败、过期的模型清单。**立刻回**:答案随 `models_changed` 到 + pub async fn refresh_stale_models(&self) -> Result { + self.post_json("/models/refresh", &()).await + } + // ───────────────────────────────────────── ChatGPT 账号 /// 开始一次登录。回来的地址要在浏览器里打开,core 在本机等回调 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f489c388..fab9cf73 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1258,6 +1258,7 @@ pub fn run() { upstreams::preview_provider, upstreams::provider_models, upstreams::refresh_provider_models, + upstreams::refresh_stale_models, upstreams::upstream_stats, upstreams::create_proxy, upstreams::update_proxy, diff --git a/src-tauri/src/upstreams.rs b/src-tauri/src/upstreams.rs index 5f8811aa..3db158f1 100644 --- a/src-tauri/src/upstreams.rs +++ b/src-tauri/src/upstreams.rs @@ -85,6 +85,14 @@ pub async fn refresh_provider_models( .map_err(text) } +/// 打开上游页时补问模型清单:还没有的、没问到的、过期的。不等上游回话。 +#[tauri::command] +pub async fn refresh_stale_models( + state: tauri::State<'_, AppState>, +) -> Out { + state.control.refresh_stale_models().await.map_err(text) +} + /// 上游列表那几列统计:24 小时的请求与费用、首字节耗时、订阅额度。 /// /// **一起取。**列表上它们是同一行的几格,分几次 invoke 会让一行数字分几次 diff --git a/src/App.tsx b/src/App.tsx index 70e93e67..c7bb1d5c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -295,6 +295,7 @@ export default function App() { seeded, settled, health, + models, locallyAnswered, rejected, configVersion, @@ -644,6 +645,7 @@ export default function App() { * * · 配置换了一份(`configVersion` 跟着 `config_reloaded` 走) * · 某家上游熔断了或恢复了(`health`,core 现在会报) + * · 某家上游的模型清单开始获取或获取完了(`models`) * · 守护状态变了 —— 重启之后监听地址和 pid 都可能不一样 * · 用户自己刚改完东西(`nudge`) */ @@ -691,7 +693,7 @@ export default function App() { alive = false; if (timer) clearTimeout(timer); }; - }, [configVersion, nudge, health, core, setStatus, setOv]); + }, [configVersion, nudge, health, models, core, setStatus, setOv]); const c = describeCore(core); /** 连上过、又断了。**只在这时候挂那条带子** */ diff --git a/src/types.ts b/src/types.ts index 16ebab9e..f526e62f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -106,6 +106,11 @@ export type CoreEvent = * 列表上都看得见。没有它,界面只能定时重读整份配置概览才能发现。 */ | { kind: "health_changed"; id: number; provider: string; state: "open" | "closed"; at_ms: number } + /** + * 某家上游的模型清单开始获取了,或者获取完了。后台获取(启动时、每天、 + * 改了地址或凭据之后)不挂在任何一次调用上,界面靠它知道要重读概览。 + */ + | { kind: "models_changed"; id: number; provider: string; at_ms: number } /** * 出站脱敏动手了。 * @@ -308,6 +313,7 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { case "scan_alert": case "clients_changed": case "health_changed": + case "models_changed": // 都不进请求列表。配置事件、扫描告警、熔断状态说的都是「现在 // 什么情况」,而这张表装的是「刚才发生过什么」。App 单独接。 break; @@ -894,6 +900,13 @@ export interface ProviderView { models_only?: string[] | null; /** `discovered` / `manual` / `none` */ model_source: string; + /** 最近一次向上游获取清单的结果。停用的上游不去获取,一直是 `pending` */ + model_status: ModelStatus; + /** 正在获取。上一次的结果照常有效 */ + model_fetching: boolean; + model_checked_at_ms?: number | null; + /** `no_list` / `failed` 的原因 */ + model_error?: string | null; /** 现在能服务的模型数,已按启用范围过滤。停用时是 0 */ model_count: number; disabled: boolean; @@ -1564,10 +1577,23 @@ export interface ProviderPreview { } /** 一个上游的模型清单 */ +/** + * 获取模型清单的结果:还没获取、上游列出了、上游不提供清单、没问到。 + * **和清单来源不是一回事** —— 没问到时清单可能来自手动清单。 + */ +export type ModelStatus = "pending" | "listed" | "no_list" | "failed"; + +/** 打开上游页时补问:开始获取的是哪几家 */ +export interface ModelsRefreshing { + providers: string[]; +} + export interface ProviderModelsView { provider: string; /** `discovered` / `manual` / `none` */ source: string; + status: ModelStatus; + fetching: boolean; checked_at_ms?: number | null; error?: string | null; models: ModelRow[]; diff --git a/src/upstreams/ModelsPanel.tsx b/src/upstreams/ModelsPanel.tsx new file mode 100644 index 00000000..b3d1e231 --- /dev/null +++ b/src/upstreams/ModelsPanel.tsx @@ -0,0 +1,278 @@ +import { type ReactNode, useEffect, useMemo, useState } from "react"; +import { ChevronRightIcon, CircleAlertIcon, RefreshCwIcon, SearchIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/ui/button"; +import { InputGroup, InputGroupAddon, InputGroupInput } from "@/ui/input-group"; +import { Spinner } from "@/ui/spinner"; +import type { ModelRow, ProviderModelsView, ProviderView } from "@/types"; +import { api } from "./api"; +import { contextWindow, errorText, perMillion } from "./labels"; + +/** 列表长过这个数才给筛选框。十来个一眼就扫完了 */ +const FILTER_FROM = 10; + +/** + * 点开「模型」一格看到的东西:这一家有哪些模型,是怎么知道的,没拿到的话 + * 为什么、该做什么。 + * + * **只读,改动在编辑对话框里做** —— 启用范围、手动清单都要一次保存一个 + * 配置版本,和上游其余设置走同一条路。这里给的是去那儿的入口。 + */ +export function ModelsPanel({ + p, + perToken, + onEdit, +}: { + p: ProviderView; + /** 按量计费:列出单价。别的计费方式不按单价算钱,列了也没意义 */ + perToken: boolean; + /** 打开编辑对话框的「模型」一节 */ + onEdit: () => void; +}) { + const [view, setView] = useState(null); + const [failed, setFailed] = useState(null); + const [refreshing, setRefreshing] = useState(false); + 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); + try { + setView(await api.refreshProviderModels(p.name)); + setFailed(null); + } catch (e) { + setFailed(errorText(e)); + } finally { + setRefreshing(false); + } + } + + const fetching = refreshing || (view?.fetching ?? p.model_fetching); + const models = view?.models ?? []; + const q = query.trim().toLowerCase(); + const match = (m: ModelRow) => q === "" || m.id.toLowerCase().includes(q); + const on = useMemo(() => models.filter((m) => m.enabled), [models]); + const off = useMemo(() => models.filter((m) => !m.enabled), [models]); + const shownOn = on.filter(match); + const shownOff = off.filter(match); + + const status = view?.status ?? p.model_status; + const source = view?.source ?? p.model_source; + const error = view?.error ?? p.model_error; + + return ( +
+
+
+
模型
+
{summary(source, models.length, on.length, view)}
+
+ +
+ + {failed ? ( + + ) : !view ? ( + + ) : source === "none" && (status === "pending" || fetching) ? ( + + ) : ( + <> + {/* 没从上游拿到清单:说为什么,指出该做什么。手动清单顶上时照样说 */} + {status === "failed" && ( + + + + + } + after={source === "manual" ? `暂用手动清单中的 ${models.length} 个模型。` : null} + /> + )} + {status === "no_list" && source === "none" && ( + + 填写手动清单… + + } + /> + )} + + {models.length > 0 && ( + <> + {models.length > FILTER_FROM && ( +
+ + + + + setQuery(e.target.value)} + /> + +
+ )} +
+ {shownOn.map((m) => ( + + ))} + {off.length > 0 && ( + <> + + {(showOff || q !== "") && + shownOff.map((m) => )} + + )} + {q !== "" && shownOn.length + shownOff.length === 0 && ( +

无匹配的模型

+ )} +
+
+ +
+ + )} + + )} +
+ ); +} + +/** 标题下那一行:多少个、从哪儿来、什么时候问的 */ +function summary(source: string, total: number, enabled: number, view: ProviderModelsView | null): string { + if (!view) return ""; + const count = enabled === total ? `${total} 个` : `${total} 个,已启用 ${enabled} 个`; + if (source === "discovered") { + return view.checked_at_ms ? `上游列出 ${count} · ${clock(view.checked_at_ms)} 获取` : `上游列出 ${count}`; + } + if (source === "manual") return `手动清单 ${count}`; + // 没拿到清单:那个时间是问的时间,不是拿到的时间 + return view.checked_at_ms ? `最近一次尝试 ${clock(view.checked_at_ms)}` : "尚未获取"; +} + +function Row({ m, perToken }: { m: ModelRow; perToken: boolean }) { + const price = + perToken && m.price + ? `$${perMillion(m.price.input)} / $${perMillion(m.price.output)}${m.estimated ? "(估)" : ""}` + : null; + return ( +
+ + {m.id} + + {price && ( + + {price} + + )} + + {m.context_window ? contextWindow(m.context_window) : ""} + +
+ ); +} + +function Waiting({ text }: { text: string }) { + return ( +

+ + {text} +

+ ); +} + +function Problem({ + title, + text, + action, + after, + muted = false, +}: { + title?: string; + text: string; + action?: ReactNode; + after?: string | null; + muted?: boolean; +}) { + return ( +
+
+ {!muted && } +
+ {title &&
{title}
} +
{text}
+
+
+ {action &&
{action}
} + {after &&

{after}

} +
+ ); +} + +/** 今天只写时刻,别的日子带上月日 */ +function clock(ms: number): string { + const d = new Date(ms); + const p = (n: number) => String(n).padStart(2, "0"); + const time = `${p(d.getHours())}:${p(d.getMinutes())}`; + return d.toDateString() === new Date().toDateString() + ? time + : `${p(d.getMonth() + 1)}-${p(d.getDate())} ${time}`; +} diff --git a/src/upstreams/ModelsSection.tsx b/src/upstreams/ModelsSection.tsx index 48e24bd0..ae946527 100644 --- a/src/upstreams/ModelsSection.tsx +++ b/src/upstreams/ModelsSection.tsx @@ -14,7 +14,7 @@ import { TableRow, } from "@/ui/table"; import { Textarea } from "@/ui/textarea"; -import type { ResolvedPrice } from "@/types"; +import type { ModelStatus, ProviderModelsView, ResolvedPrice } from "@/types"; import { globMatch } from "./glob"; import { contextWindow, modelSourceLabel } from "./labels"; import { Boxed, FormItem, Note, Segmented } from "./parts"; @@ -28,6 +28,22 @@ export interface ModelCatalog { checkedAtMs?: number | null; /** 没拿到清单的原因 */ error?: string | null; + /** 获取的结果:拿到了、上游不提供、没问到 */ + status?: ModelStatus; + /** core 正在向上游问 */ + fetching?: boolean; +} + +/** core 记下的那一份 */ +export function catalogOf(v: ProviderModelsView): ModelCatalog { + return { + source: v.source, + models: v.models.map((m) => m.id), + checkedAtMs: v.checked_at_ms, + error: v.error, + status: v.status, + fetching: v.fetching, + }; } /** 这个模型在不在启用范围里。和 core 同一套通配规则 */ @@ -66,6 +82,9 @@ export function ModelsSection({ */ const [manualText, setManualText] = useState(() => form.manualModels.join("\n")); const listed = catalog?.source === "discovered"; + // 后台正在问、手里还什么都没有:等它,别先让人去填手动清单 + const waiting = !!catalog?.fetching && catalog.source === "none"; + const busy = refreshing || !!catalog?.fetching; const models = listed ? catalog.models : form.manualModels; const shown = useMemo( () => models.filter((m) => m.toLowerCase().includes(filter.trim().toLowerCase())), @@ -100,7 +119,11 @@ export function ModelsSection({
模型列表 - {catalog && {modelSourceLabel(catalog.source)}} + {catalog && !waiting && ( + + {modelSourceLabel(catalog.source, catalog.status)} + + )} {catalog && (listed || models.length > 0) && ( {models.length} 个 @@ -108,13 +131,13 @@ export function ModelsSection({ )}
-
- {loading ? ( + {loading || waiting ? (

正在获取模型列表 diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 32923934..724b57d2 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -23,7 +23,7 @@ import { BillingSection } from "./BillingSection"; import { ChatgptAccountSection } from "./ChatgptAccountSection"; import { ConnectionSection } from "./ConnectionSection"; import { errorText, protocolLabel, shortUrl } from "./labels"; -import { ModelsSection, inScope, type ModelCatalog } from "./ModelsSection"; +import { ModelsSection, catalogOf, inScope, type ModelCatalog } from "./ModelsSection"; import { StepNav } from "./parts"; import { PriceSheetDialog } from "./PriceSheetDialog"; import { ProxyDialog } from "./ProxyDialog"; @@ -163,23 +163,25 @@ export function UpstreamDialog({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [connectionKey]); - // 编辑:读已保存的模型清单 + // 编辑:读已保存的模型清单。**跟着概览里这一家的获取状态重读** —— 打开对话框 + // 时后台可能正在问,问完了这里要跟着变,不该再让人点一次刷新。 + // 连接信息改过时不读:那时的清单对应表单里的新值,是「检测连接」带进来的 + const modelsTick = editing ? `${editing.model_checked_at_ms ?? ""}|${editing.model_fetching}` : ""; useEffect(() => { - if (!editing) return; + if (!editing || connectionChanged(form, editing)) return; let alive = true; api .providerModels(editing.name) .then((v) => { - if (alive) setCatalog({ source: v.source, models: v.models.map((m) => m.id), checkedAtMs: v.checked_at_ms, error: v.error }); + if (alive) setCatalog(catalogOf(v)); }) .catch((e) => alive && setError(errorText(e))) .finally(() => alive && setCatalogLoading(false)); return () => { alive = false; }; - // 只在打开时读一次;之后的变化由「刷新模型列表」和「检测连接」带进来 // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [modelsTick]); const models = catalog?.source === "discovered" ? catalog.models : form.manualModels; const enabledModels = useMemo(() => models.filter((m) => inScope(form, m)), [models, form]); @@ -220,10 +222,11 @@ export function UpstreamDialog({ setTest(r); setCatalog( r.ok && r.models.kind === "listed" - ? { source: "discovered", models: r.models.models, checkedAtMs: Date.now() } + ? { source: "discovered", status: "listed", models: r.models.models, checkedAtMs: Date.now() } : { // 没拿到清单(连接失败,或上游不提供列表接口):手动清单兜底 source: form.manualModels.length > 0 ? "manual" : "none", + status: r.ok ? "no_list" : "failed", models: [], checkedAtMs: Date.now(), error: r.ok ? describeModelList(r.models) : `连接失败:${r.error ?? "未知错误"}`, @@ -234,6 +237,7 @@ export function UpstreamDialog({ setTest({ ok: false, protocol: null, latency_ms: 0, models: { kind: "empty" }, error }); setCatalog({ source: form.manualModels.length > 0 ? "manual" : "none", + status: "failed", models: [], checkedAtMs: Date.now(), error: `连接失败:${error}`, @@ -251,8 +255,7 @@ export function UpstreamDialog({ } setRefreshing(true); try { - const v = await api.refreshProviderModels(editing.name); - setCatalog({ source: v.source, models: v.models.map((m) => m.id), checkedAtMs: v.checked_at_ms, error: v.error }); + setCatalog(catalogOf(await api.refreshProviderModels(editing.name))); } catch (e) { setError(errorText(e)); } finally { diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index cad473a1..0ea5c68c 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -1,4 +1,5 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; +import { cn } from "@/lib/utils"; import { Badge } from "@/ui/badge"; import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover"; import { Progress } from "@/ui/progress"; @@ -12,17 +13,19 @@ import { TableRow, } from "@/ui/table"; import { resetIn } from "@/format"; -import { usd, type ChatgptUsage, type Overview, type ProviderModelsView, type ProviderView } from "@/types"; -import { api, type UpstreamStats } from "./api"; +import { Spinner } from "@/ui/spinner"; +import { usd, type ChatgptUsage, type Overview, type ProviderView } from "@/types"; +import type { UpstreamStats } from "./api"; import { billingLabel, egressLabel, - modelSourceNote, + modelFace, planLabel, protocolLabel, quotaWindowLabel, shortUrl, } from "./labels"; +import { ModelsPanel } from "./ModelsPanel"; export interface UpstreamActions { edit: (name: string) => void; @@ -30,6 +33,8 @@ export interface UpstreamActions { linkTest: (name: string) => void; speedTest: (name: string) => void; refreshModels: (name: string) => void; + /** 打开编辑对话框的「模型」一节:启用范围、手动清单 */ + editModels: (name: string) => void; /** ChatGPT 账号上游:额度与重置卡 */ account: (name: string) => void; toggle: (p: ProviderView) => void; @@ -103,7 +108,7 @@ export function UpstreamTable({ */} - + actions.editModels(p.name)} /> @@ -164,81 +169,49 @@ function Where({ p, account }: { p: ProviderView; account?: ChatgptUsage }) { /** * 有多少个模型,以及都有哪些。 * - * 数目单独回答不了「我要的那个模型在不在里面」,而一个二十几项的清单 - * 又放不进一格。**点数字就展开**,不用为了看一眼进编辑对话框。 + * **整格是一个按钮,什么状态都能点开** —— 数目单独回答不了「我要的那个 + * 模型在不在里面」,而没拿到清单时,点开要能看到为什么、该做什么。不用 + * 为了看一眼进编辑对话框再点刷新。停用的上游不提供模型,状态一栏已经说了。 */ -function ModelsCell({ p }: { p: ProviderView }) { +function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { const [open, setOpen] = useState(false); - const [list, setList] = useState(null); - const [failed, setFailed] = useState(false); - const none = p.disabled || p.model_source === "none"; - const sub = modelSourceNote(p); - - // 展开才去读:一页上十几家上游,没人看的清单不该占着一次调用 - useEffect(() => { - if (!open || list || failed) return; - let alive = true; - api - .providerModels(p.name) - .then((v) => alive && setList(v)) - .catch(() => alive && setFailed(true)); - return () => { - alive = false; - }; - }, [open, list, failed, p.name]); - - if (none) { - return ( - - {/* 停用时 core 报 0 —— 那不是「没有模型」,状态一栏已经说了停用 */} - —{sub &&

{sub}
} - - ); + if (p.disabled) { + return —; } - - const models = list?.models ?? []; - const shown = models.filter((m) => m.enabled); - const hidden = models.length - shown.length; + const face = modelFace(p); + const busy = p.model_fetching || face.note === "获取中"; return ( - + {/* - 悬停时变成一个块,不画下划线 —— 鼠标正好压在字的下方, - 一条紧贴基线的线它自己就把它挡了 + 悬停时整块变底色,不画下划线 —— 鼠标正好压在字的下方,一条紧贴 + 基线的线它自己就把它挡了 */} - - {p.model_count} - - -
- 模型清单 - {sub && {sub}} -
- {failed ? ( -

暂时读不到模型清单。

- ) : !list ? ( -

正在读取

- ) : ( - <> -
    - {shown.map((m) => ( -
  • - {m.id} -
  • - ))} -
- {/* 范围外的不列,但要说有——否则这份清单看起来就是它全部的模型 */} - {hidden > 0 && ( -

- 另有 {hidden} 个不在启用范围内 -

- )} - {list.error &&

{list.error}

} - + + + {busy && } + {face.count ?? "—"} + + {face.note && ( + + {face.note} + )} + + + { + setOpen(false); + onEdit(); + }} + />
- {sub &&
{sub}
}
); } diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 9e0c1e79..fb5305de 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -138,6 +138,19 @@ export default function UpstreamsPage({ loadStatus(); }, [loadStatus, configVersion]); + /** + * **打开这一页时补问模型清单**:还没有的、没问到的、过期的。 + * + * 不等、不管结果 —— core 立刻回话,答案随 `models_changed` 一家一家地到, + * 概览跟着重读。一分钟内问过的它自己会跳过,来回切页面不会每次都打网络。 + * 以前要「编辑 → 模型 → 刷新」才看得到的东西,现在进页面就有。 + */ + useEffect(() => { + api.refreshStaleModels().catch(() => { + // 问不了(core 正在重启)就等后台那一轮,列表照常可用 + }); + }, []); + const changed = () => { onChanged(); loadStats(); @@ -318,6 +331,8 @@ export default function UpstreamsPage({ linkTest: (name) => setDialog({ kind: "link", provider: name }), speedTest: (name) => setDialog({ kind: "speed", provider: name }), refreshModels: (name) => void refreshModels(name), + editModels: (name) => + 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), diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 21a36c4b..52b239e3 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -21,6 +21,7 @@ import type { PriceSheetSave, PricingRefreshed, PricingStatus, + ModelsRefreshing, ProviderModelsView, ProviderPreview, ProviderQuota, @@ -57,6 +58,8 @@ export const api = { providerModels: (name: string) => invoke("provider_models", { name }), refreshProviderModels: (name: string) => invoke("refresh_provider_models", { name }), + /** 补问缺失、失败、过期的清单。**立刻回**,答案随 `models_changed` 到 */ + refreshStaleModels: () => invoke("refresh_stale_models"), upstreamStats: (sinceMs: number) => invoke("upstream_stats", { sinceMs }), createProxy: (save: ProxySave) => invoke("create_proxy", { save }), diff --git a/src/upstreams/labels.test.ts b/src/upstreams/labels.test.ts new file mode 100644 index 00000000..b1af61da --- /dev/null +++ b/src/upstreams/labels.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderView } from "@/types"; +import { modelFace } from "./labels"; + +function p(patch: Partial): ProviderView { + return { + name: "x", + base_url: "https://x.example", + base_url_masked: false, + auth_header: "x-api-key", + protocol: "anthropic", + protocol_explicit: false, + proxy: "direct", + on_proxy_fail: "fail", + models: [], + models_only: null, + model_source: "discovered", + model_status: "listed", + model_fetching: false, + model_count: 7, + disabled: false, + health: "ok", + billing: null, + billing_effective: "per-token", + trust: "untrusted", + trust_explicit: false, + redact: [], + redact_explicit: false, + references: [], + pricing: null, + ...patch, + } as ProviderView; +} + +describe("modelFace", () => { + it("counts what an upstream serves and says when the range is narrowed", () => { + expect(modelFace(p({}))).toEqual({ count: 7, note: null, warn: false }); + expect(modelFace(p({ models_only: ["claude-*"] })).note).toBe("指定范围"); + }); + + it("tells not-yet-asked, refused and no-list apart instead of calling all of them 未获取", () => { + const none = { model_source: "none", model_count: 0 } as const; + expect(modelFace(p({ ...none, model_status: "pending" }))).toEqual({ count: null, note: "获取中", warn: false }); + expect(modelFace(p({ ...none, model_status: "failed", model_fetching: true })).note).toBe("获取中"); + expect(modelFace(p({ ...none, model_status: "failed" }))).toEqual({ count: null, note: "获取失败", warn: true }); + expect(modelFace(p({ ...none, model_status: "no_list" }))).toEqual({ + count: null, + note: "未提供清单", + warn: false, + }); + }); + + it("keeps showing a manual list that stands in for a failed or missing one", () => { + const face = modelFace(p({ model_source: "manual", model_status: "failed", model_count: 2 })); + expect(face).toEqual({ count: 2, note: "手动清单", warn: false }); + }); +}); diff --git a/src/upstreams/labels.ts b/src/upstreams/labels.ts index 5708e71a..bc4a2753 100644 --- a/src/upstreams/labels.ts +++ b/src/upstreams/labels.ts @@ -4,7 +4,15 @@ * **同一个概念只有一个叫法**,所以集中在这里:列表、对话框、测速结果里 * 说的「按量计费」「默认价目表」「自动识别」必须是同一个词。 */ -import type { L1Result, L1Skip, L1Stage, PriceFields, PriceSourceView, ProviderView } from "@/types"; +import type { + L1Result, + L1Skip, + L1Stage, + ModelStatus, + PriceFields, + PriceSourceView, + ProviderView, +} from "@/types"; export const PROTOCOLS: { id: string; label: string }[] = [ { id: "anthropic", label: "Anthropic Messages" }, @@ -77,23 +85,48 @@ export function authHeaderLabel(header: string): string { return header === "authorization" ? "Authorization: Bearer" : header; } -export function modelSourceLabel(source: string): string { +/** + * 模型清单从哪儿来。**没拿到清单时说为什么**:还在获取、上游不提供、 + * 没问到 —— 三种情况要做的事不一样,不能都叫「未获取」。 + */ +export function modelSourceLabel(source: string, status?: ModelStatus): string { switch (source) { case "discovered": return "自动发现"; case "manual": return "手动清单"; default: - return "未获取"; + return status === "failed" ? "获取失败" : status === "no_list" ? "未提供清单" : "未获取"; } } /** 订阅额度窗口:`5h` / `7d` / `weekly` */ -/** 模型清单是怎么来的。自动获取、范围也没限制时不用说 */ -export function modelSourceNote(p: ProviderView): string | null { - if (p.model_source === "manual") return "手动清单"; - if (p.model_source === "none") return "未获取"; - return p.models_only ? "指定范围" : null; +/** + * 上游表「模型」一格的样子:主数字,和下面那一行小字。 + * + * **每种状态都说得出是什么**:以前「还没问」「密钥被拒」「上游不给清单」 + * 都显示成「未获取」,而用户该做的事完全不同 —— 等一下、改密钥、填手动清单。 + */ +export function modelFace(p: ProviderView): { + count: number | null; + note: string | null; + warn: boolean; +} { + const manual = p.model_source === "manual"; + const known = p.model_source !== "none"; + // 还没问过:打开这一页时已经去问了,马上就有 + if (p.model_status === "pending" && !known) return { count: null, note: "获取中", warn: false }; + if (p.model_fetching && !known) return { count: null, note: "获取中", warn: false }; + if (!known) { + return p.model_status === "no_list" + ? { count: null, note: "未提供清单", warn: false } + : { count: null, note: "获取失败", warn: true }; + } + return { + count: p.model_count, + note: manual ? "手动清单" : p.models_only ? "指定范围" : null, + warn: false, + }; } /** diff --git a/src/upstreams/upstreamForm.test.ts b/src/upstreams/upstreamForm.test.ts index e2c7dbe1..6357a28d 100644 --- a/src/upstreams/upstreamForm.test.ts +++ b/src/upstreams/upstreamForm.test.ts @@ -29,6 +29,8 @@ function view(patch: Partial = {}): ProviderView { models: [], models_only: null, model_source: "discovered", + model_status: "listed", + model_fetching: false, model_count: 3, disabled: false, health: "ok", diff --git a/src/useRequests.ts b/src/useRequests.ts index abea301a..1c5cea82 100644 --- a/src/useRequests.ts +++ b/src/useRequests.ts @@ -121,6 +121,11 @@ export function useRequests() { * 不再每两秒问一次同样的问题。 */ const [health, setHealth] = useState(0); + /** + * 模型清单变了几次:某家开始获取了、获取完了。**同样不属于任何一次请求** —— + * 启动时、每天、改了地址或凭据之后,core 自己在后台问。 + */ + const [models, setModels] = useState(0); /** @@ -208,6 +213,7 @@ export function useRequests() { landed = true; } if (ev.kind === "health_changed") setHealth((n) => n + 1); + if (ev.kind === "models_changed") setModels((n) => n + 1); if (ev.kind === "locally_answered") local += 1; if (ev.kind === "config_rejected") setRejected(ev); if (ev.kind === "scan_alert") setAlerts((prev) => [...ev.alerts, ...prev].slice(0, 50)); @@ -262,6 +268,7 @@ export function useRequests() { seeded, settled, health, + models, locallyAnswered, rejected, configVersion,