diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index b6ed731c..2d79399a 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -803,6 +803,28 @@ impl ControlClient { .await } + // ───────────────────────────────────────── Z.ai / BigModel 账号 + + /// 开始一次登录。回来的地址要在浏览器里打开,core 自己去问「授权了没有」 + pub async fn start_zai_login(&self, req: &tw_api::ZaiLoginStart) -> Result { + self.post_json("/zai/login", req).await + } + + pub async fn zai_login_status(&self, id: &str) -> Result { + Ok(serde_json::from_slice( + &self.get(&format!("/zai/login/{}", segment(id))).await?, + )?) + } + + pub async fn cancel_zai_login(&self, id: &str) -> Result { + self.send_json( + hyper::Method::DELETE, + &format!("/zai/login/{}", segment(id)), + &(), + ) + .await + } + pub async fn chatgpt_usage(&self, name: &str) -> Result { Ok(serde_json::from_slice( &self diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index debd8973..ffe037df 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -32,6 +32,7 @@ pub mod theme; mod token; pub mod update; pub mod upstreams; +pub mod zai; use control::ControlClient; use supervisor::{CoreState, Supervisor}; @@ -1608,6 +1609,10 @@ pub fn run() { chatgpt::chatgpt_usage, chatgpt::chatgpt_resets, chatgpt::use_chatgpt_reset, + zai::start_zai_login, + zai::reopen_zai_login, + zai::zai_login_status, + zai::cancel_zai_login, upstreams::pricing_status, upstreams::refresh_pricing, upstreams::set_price_auto_update, diff --git a/src-tauri/src/zai.rs b/src-tauri/src/zai.rs new file mode 100644 index 00000000..1e5a0c43 --- /dev/null +++ b/src-tauri/src/zai.rs @@ -0,0 +1,124 @@ +//! Z.ai / BigModel 账号的命令:登录。 +//! +//! 登录本身在 core:它给出授权地址、自己去问「授权了没有」、把换来的密钥写进配置。 +//! 这一层做 core 做不到的那一件事 —— **打开浏览器**。 +//! +//! **没有「返回 ThinkWatch」那一步。**授权回的是对方自己的服务端,浏览器最后停在 +//! 他们的页面上,那一页不是我们的,我们既关不掉它、也没法在上面放一个跳回来的链接 +//! (见 ChatGPT 那条路的 `handle_return`:那是因为回调页是 core 自己发的)。所以登录 +//! 成没成只有界面在轮询里知道。 +//! +//! 授权地址存在这里而不是交给界面:界面拿着地址,就等于多了一条「界面传来一个地址、 +//! 应用去打开它」的路径。重新打开授权页只按登录 ID 找。 + +use std::sync::Mutex; + +use tauri_plugin_opener::OpenerExt; + +use crate::AppState; + +type Out = Result; + +fn text(e: anyhow::Error) -> String { + format!("{e:#}") +} + +/// 正在等的那次登录。**同一时刻只有一次**,core 那边也是 +static PENDING: Mutex> = Mutex::new(None); + +struct Pending { + id: String, + /// 要打开的授权地址 + url: String, +} + +/// 一次登录里界面该知道的部分。**授权地址不在其中** +#[derive(serde::Serialize)] +pub struct Login { + id: String, + expires_in_secs: u64, +} + +/// `family`:`zai`(api.z.ai)或 `bigmodel`(open.bigmodel.cn)。 +/// +/// **这里就把授权页打开**:让用户再点一次「打开授权页」,中间那一步没有任何意义。 +#[tauri::command] +pub async fn start_zai_login( + app: tauri::AppHandle, + state: tauri::State<'_, AppState>, + family: Option, + name: Option, + proxy: Option, +) -> Out { + let login = state + .control + .start_zai_login(&tw_api::ZaiLoginStart { + family, + name, + proxy, + }) + .await + .map_err(text)?; + if let Ok(mut g) = PENDING.lock() { + *g = Some(Pending { + id: login.id.clone(), + url: login.authorize_url.clone(), + }); + } + open_page(&app, &login.authorize_url)?; + Ok(Login { + id: login.id, + expires_in_secs: login.expires_in_secs, + }) +} + +/// 浏览器被关掉、或者授权页打不开时再打开一次。**只认还在等的那一次** +#[tauri::command] +pub async fn reopen_zai_login(app: tauri::AppHandle, id: String) -> Out<()> { + let url = PENDING + .lock() + .ok() + .and_then(|g| g.as_ref().filter(|p| p.id == id).map(|p| p.url.clone())) + .ok_or_else(|| { + tr!( + "这次登录已经结束,请重新发起", + "This sign-in has ended; start a new one" + ) + .to_string() + })?; + open_page(&app, &url) +} + +fn open_page(app: &tauri::AppHandle, url: &str) -> Out<()> { + app.opener().open_url(url, None::<&str>).map_err(|e| { + tr!( + format!("无法打开浏览器:{e}"), + format!("The browser could not be opened: {e}") + ) + }) +} + +#[tauri::command] +pub async fn zai_login_status( + state: tauri::State<'_, AppState>, + id: String, +) -> Out { + state.control.zai_login_status(&id).await.map_err(text) +} + +#[tauri::command] +pub async fn cancel_zai_login( + state: tauri::State<'_, AppState>, + id: String, +) -> Out { + forget(&id); + state.control.cancel_zai_login(&id).await.map_err(text) +} + +pub fn forget(id: &str) { + if let Ok(mut g) = PENDING.lock() + && g.as_ref().is_some_and(|p| p.id == id) + { + *g = None; + } +} diff --git a/src/types.ts b/src/types.ts index eceaaedd..85753d70 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1176,6 +1176,25 @@ export interface ChatgptLoginStatus { error?: string | null; } +/** 登哪一家的账号 */ +export type ZaiFamily = "zai" | "bigmodel"; + +/** 一次 Z.ai 登录。授权地址留在 Rust 侧,界面只拿到 ID */ +export interface ZaiLogin { + id: string; + expires_in_secs: number; +} + +export interface ZaiLoginStatus { + id: string; + status: LoginStatus; + /** 登录成功后写进配置的上游名 */ + provider?: string | null; + /** 登的是哪个账号,邮箱或者昵称。对方没给就没有 */ + account?: string | null; + error?: string | null; +} + /** 账号的订阅额度 */ export interface ChatgptUsage { /** 登的是哪个账号。core 只给邮箱,用户 ID 和账户 ID 不往外带 */ diff --git a/src/upstreams/ConnectionSection.i18n.ts b/src/upstreams/ConnectionSection.i18n.ts index 9a8f23a5..62aba456 100644 --- a/src/upstreams/ConnectionSection.i18n.ts +++ b/src/upstreams/ConnectionSection.i18n.ts @@ -12,6 +12,7 @@ export const connectionSectionText = messages( protocol: "接口协议", service: "服务类型", chatgpt: "ChatGPT 账号(登录)", + zai: "Z.ai / BigModel 账号(登录)", name: "名称", namePlaceholder: "例如 relay-hk", baseUrl: "接口地址", @@ -56,6 +57,7 @@ export const connectionSectionText = messages( 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", diff --git a/src/upstreams/ConnectionSection.tsx b/src/upstreams/ConnectionSection.tsx index 31d2f3e9..8816a17f 100644 --- a/src/upstreams/ConnectionSection.tsx +++ b/src/upstreams/ConnectionSection.tsx @@ -16,7 +16,7 @@ import { proxyKindLabel, } from "./labels"; import { FormItem, Note, Segmented } from "./parts"; -import { CHATGPT, CUSTOM, PRESETS, nameFromUrl, presetById } from "./presets"; +import { CHATGPT, CUSTOM, PRESETS, ZAI, nameFromUrl, presetById } from "./presets"; import { describeModelList, freeName, type UpstreamForm } from "./upstreamForm"; /** 「新建代理…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */ @@ -33,6 +33,7 @@ export function ConnectionSection({ onTest, onNewProxy, onChatgptLogin, + onZaiLogin, }: { form: UpstreamForm; set: (patch: Partial) => void; @@ -46,6 +47,8 @@ export function ConnectionSection({ onNewProxy: () => void; /** 服务类型选了 ChatGPT 账号:那一条走登录,不走这张表单 */ onChatgptLogin: () => void; + /** 服务类型选了 Z.ai / BigModel 账号:同样走登录 */ + onZaiLogin: () => void; }) { const t = useText(connectionSectionText); const proxies = ov.proxies; @@ -61,6 +64,10 @@ export function ConnectionSection({ onChatgptLogin(); return; } + if (id === ZAI) { + onZaiLogin(); + return; + } const prev = presetById(form.preset); const next = presetById(id); set({ @@ -93,6 +100,7 @@ export function ConnectionSection({ > {CUSTOM.label} {t.chatgpt} + {t.zai} {PRESETS.map((p) => ( {p.label} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 2ebb87cb..499f7368 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -73,6 +73,7 @@ export function UpstreamDialog({ onSaved, onChanged, onChatgptLogin, + onZaiLogin, }: { mode: UpstreamDialogMode; ov: Overview; @@ -83,6 +84,8 @@ export function UpstreamDialog({ onChanged: () => void; /** 改用 ChatGPT 账号登录:这张表单让位给登录对话框。带上名字就是给它换一次凭据 */ onChatgptLogin: (relogin?: { name: string; proxy: string }) => void; + /** 改用 Z.ai / BigModel 账号登录:同样让位给登录对话框 */ + onZaiLogin: () => void; }) { const t = useText(upstreamDialogText); const c = useText(commonText); @@ -340,6 +343,7 @@ export function UpstreamDialog({ onTest={runTest} onNewProxy={() => setNested({ kind: "proxy" })} onChatgptLogin={onChatgptLogin} + onZaiLogin={onZaiLogin} /> )} {section === "models" && ( diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index fb00581f..2eb282b5 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -20,6 +20,7 @@ import type { ChatgptUsage, CoreEvent, Overview, PricingStatus } from "@/types"; import { useCoreEvent } from "@/useCoreEvent"; import { api, type UpstreamStats } from "./api"; import { ChatgptLoginDialog } from "./ChatgptLoginDialog"; +import { ZaiLoginDialog } from "./ZaiLoginDialog"; import { DeleteDialog, type Referrer } from "./DeleteDialog"; import { when } from "@/format"; import { errorText } from "./labels"; @@ -41,6 +42,7 @@ type DialogState = | { kind: "upstream"; mode: UpstreamDialogMode } /** `relogin`:给已有的 ChatGPT 账号换一次凭据,名称和出站方式沿用它的 */ | { kind: "chatgpt-login"; relogin?: { name: string; proxy: string } } + | { kind: "zai-login" } | { kind: "delete-upstream"; name: string } | { kind: "test"; name: string } | { kind: "link"; provider: string | null } @@ -467,6 +469,7 @@ export default function UpstreamsPage({ }} onChanged={changed} onChatgptLogin={(relogin) => setDialog({ kind: "chatgpt-login", relogin })} + onZaiLogin={() => setDialog({ kind: "zai-login" })} /> )} {dialog?.kind === "delete-upstream" && ( @@ -498,6 +501,9 @@ export default function UpstreamsPage({ onSaved={() => changed()} /> )} + {dialog?.kind === "zai-login" && ( + setDialog(null)} onSaved={() => changed()} /> + )} {dialog?.kind === "test" && ( setDialog(null)} /> )} diff --git a/src/upstreams/ZaiLoginDialog.i18n.tsx b/src/upstreams/ZaiLoginDialog.i18n.tsx new file mode 100644 index 00000000..ed69137b --- /dev/null +++ b/src/upstreams/ZaiLoginDialog.i18n.tsx @@ -0,0 +1,89 @@ +import type { ReactNode } from "react"; +import { messages } from "@/i18n"; + +export const zaiLoginText = messages( + { + expired: "授权未在有效期内完成", + cancelled: "登录已取消", + title: "使用 Z.ai 或 BigModel 账号", + desc: "登录账号,把它的编程套餐额度作为一个上游使用。", + reloginTitle: "重新登录账号", + reloginDesc: (name: ReactNode) => ( + <> + 为上游 {name} 换一把密钥。模型范围、计费方式等设置保持不变。 + + ), + service: "账号归属", + serviceDesc: (url: ReactNode) => ( + <>两者是同一服务的两个站点,账号不通用;请求发往 {url} + ), + noticeTitle: "登录之前请确认以下几点", + noticeTheirPage: + "授权页由对方提供,页面上显示的是他们自己的客户端名称 —— 该服务不开放第三方注册授权应用。", + noticeKey: + "登录会在账号中创建一把名为 thinkwatch 的 API 密钥(已存在则直接使用),额度按该密钥计入套餐。", + noticeHonest: "请求会如实说明来自 ThinkWatch,不伪装成其他客户端。", + noticeStorage: "得到的密钥保存在本机的配置文件中,与其他上游一同管理。", + name: "名称", + nameDesc: "配置中这个上游的名称", + nameTaken: "这个名称已被占用", + nameReplaces: "将替换该上游的密钥", + proxy: "出站代理", + proxyDesc: "登录与后续请求都经此发出", + direct: "直连", + systemProxy: "系统代理", + understood: "已阅读上述说明,继续登录", + waiting: "授权页已在浏览器中打开,完成授权后此处会自动继续。", + hint: "浏览器未打开时可再打开一次。授权完成后浏览器会停在对方的页面上,可直接关闭。", + reopen: "重新打开授权页", + done: (provider: ReactNode) => <>已登录,上游 {provider} 已写入配置。, + account: (who: string) => `账号 ${who}。`, + doneHint: "模型范围、计费方式等可在该上游的编辑对话框中调整。", + finish: "完成", + signIn: "登录", + }, + { + expired: "Authorization was not completed within the time limit", + cancelled: "Sign-in was canceled", + title: "Use a Z.ai or BigModel account", + desc: "Signs in to an account and uses its coding plan quota as an upstream.", + reloginTitle: "Sign in to the account again", + reloginDesc: (name: ReactNode) => ( + <> + Replaces the key of the upstream {name}. Model scope, billing and other settings stay + unchanged. + + ), + service: "Account service", + serviceDesc: (url: ReactNode) => ( + <>Two sites of the same service; an account works on one of them only. Requests go to {url} + ), + noticeTitle: "Confirm the following before signing in", + noticeTheirPage: + "The authorization page is theirs, and it names their own client, because the service does not let third parties register an authorization app.", + noticeKey: + "Signing in creates an API key named thinkwatch on the account, or uses the existing one. Quota is counted against that key.", + noticeHonest: + "Requests truthfully identify themselves as coming from ThinkWatch and do not impersonate other clients.", + noticeStorage: + "The key obtained by signing in is stored in the config file on this computer and managed together with the other upstreams.", + name: "Name", + nameDesc: "This upstream's name in the config", + nameTaken: "This name is already in use", + nameReplaces: "The key of that upstream will be replaced", + proxy: "Outbound proxy", + proxyDesc: "Used for sign-in and all later requests", + direct: "Direct", + systemProxy: "System proxy", + understood: "Acknowledge the notes above and continue signing in", + waiting: + "The authorization page is open in the browser. Sign-in continues here automatically once authorization is complete.", + hint: "If the browser did not open, the page can be opened again. After authorization the browser stays on their page and can simply be closed.", + reopen: "Reopen authorization page", + done: (provider: ReactNode) => <>Signed in. The upstream {provider} has been saved to the config., + account: (who: string) => `Account: ${who}.`, + doneHint: "Model scope, billing and other settings can be changed in the upstream's edit dialog.", + finish: "Done", + signIn: "Sign in", + }, +); diff --git a/src/upstreams/ZaiLoginDialog.tsx b/src/upstreams/ZaiLoginDialog.tsx new file mode 100644 index 00000000..52f81413 --- /dev/null +++ b/src/upstreams/ZaiLoginDialog.tsx @@ -0,0 +1,303 @@ +import { useEffect, useRef, useState } from "react"; +import { CircleAlertIcon, ExternalLinkIcon } from "lucide-react"; +import { listen } from "@tauri-apps/api/event"; +import { Alert, AlertDescription, AlertTitle } from "@/ui/alert"; +import { Button } from "@/ui/button"; +import { Checkbox } from "@/ui/checkbox"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +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 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 { errorText, proxyKindLabel, shortUrl } from "./labels"; +import { FormItem } from "./parts"; +import { ZAI_ENDPOINTS } from "./presets"; +import { freeName } from "./upstreamForm"; + +/** 登录还没结果时,多久问一次 core。事件是主路,这是它的兜底 */ +const POLL_MS = 2_000; + +type Phase = + | { at: "form" } + /** 授权页已经在这台机器的浏览器里打开 */ + | { at: "waiting"; id: string } + | { at: "done"; provider: string; account: string | null }; + +/** + * 用 Z.ai 或 BigModel 账号新建上游,或给已有的换一把密钥。 + * + * **只有一条路:这台机器上的浏览器。**授权回的是对方自己的服务端,所以既没有 + * 「在另一台设备上输码」那条路(那要对方支持),也没有「返回 ThinkWatch」那一步 —— + * 登录成没成由 core 轮询出来,再通过事件告诉这里。 + */ +export function ZaiLoginDialog({ + ov, + relogin, + onClose, + onSaved, +}: { + ov: Overview; + /** 给这个已有的上游换一把密钥:名称固定,账号归属和出站方式沿用它的 */ + relogin?: { name: string; proxy: string; family: ZaiFamily }; + onClose: () => void; + onSaved: (name: string) => void; +}) { + const t = useText(zaiLoginText); + const common = useText(commonText); + const proxies = ov.proxies; + const taken = ov.providers.map((p) => p.name); + const [family, setFamily] = useState(relogin?.family ?? "zai"); + const [name, setName] = useState(() => relogin?.name ?? freeName("zai", taken)); + const [proxy, setProxy] = useState(relogin?.proxy ?? "direct"); + // 重新登录的人此前已经看过并同意了这些,不再拦一次 + const [understood, setUnderstood] = useState(relogin != null); + const [phase, setPhase] = useState({ at: "form" }); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + // 卸载之后不要再写状态:等待期间用户可能直接关掉对话框。 + // **挂载时要置回来** —— 开发模式下 effect 会先跑一遍再清理再跑一遍 + const alive = useRef(true); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + + const waiting = phase.at === "waiting" ? phase.id : null; + + function settle(s: ZaiLoginStatus) { + if (!alive.current || s.status === "pending") return; + if (s.status === "done" && s.provider) { + setPhase({ at: "done", provider: s.provider, account: s.account ?? null }); + onSaved(s.provider); + return; + } + setPhase({ at: "form" }); + const text = textOf(zaiLoginText); + setError(s.error ?? (s.status === "expired" ? text.expired : text.cancelled)); + } + + // 结果由 core 发事件,不必一直问;问一遍是为了事件漏掉时也能收尾 + useEffect(() => { + if (!waiting) return; + const un = listen("core-event", (e) => { + const ev = e.payload; + if (ev.kind !== "login_finished" || ev.login !== waiting) return; + settle({ + id: ev.login, + status: ev.status, + provider: ev.provider ?? null, + error: ev.error ?? null, + }); + }); + const timer = setInterval(() => { + api + .zaiLoginStatus(waiting) + .then(settle) + .catch(() => { + // 控制面一时不通:下一轮再问 + }); + }, POLL_MS); + return () => { + void un.then((f) => f()); + clearInterval(timer); + }; + // settle 每次渲染都是新的,但订阅只该跟着这次登录重建 + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [waiting]); + + async function start() { + setBusy(true); + setError(null); + try { + const login = await api.startZaiLogin(family, name.trim(), proxy); + if (!alive.current) return; + setPhase({ at: "waiting", id: login.id }); + } catch (e) { + setError(errorText(e)); + } finally { + setBusy(false); + } + } + + async function cancel() { + if (waiting) { + try { + await api.cancelZaiLogin(waiting); + } catch { + // 取消失败也要关掉:它最多在 15 分钟后自己过期 + } + } + onClose(); + } + + // 同名的上游已经是这一家的话,登录换的是它的密钥 —— 那不是冲突,要说清是替换 + const existing = ov.providers.find((p) => p.name === name.trim()); + const replaces = + existing != null && existing.base_url === ZAI_ENDPOINTS[family] && !relogin; + const nameTaken = !relogin && !replaces && existing != null && phase.at === "form"; + const canStart = name.trim().length > 0 && !nameTaken && understood && !busy; + + return ( + !o && void cancel()}> + + + {relogin ? t.reloginTitle : t.title} + + {relogin ? t.reloginDesc({relogin.name}) : t.desc} + + + + {phase.at === "form" && ( +
+ {!relogin && ( + + + {t.noticeTitle} + +
    +
  • {t.noticeTheirPage}
  • +
  • {t.noticeKey}
  • +
  • {t.noticeHonest}
  • +
  • {t.noticeStorage}
  • +
+
+
+ )} + + {shortUrl(ZAI_ENDPOINTS[family])}, + )} + > +
+ +
+
+ +
+ + setName(e.target.value)} + disabled={relogin != null} + aria-invalid={nameTaken} + /> + {nameTaken &&

{t.nameTaken}

} + {replaces &&

{t.nameReplaces}

} +
+ + setProxy(e.target.value)} + > + {t.direct} + {t.systemProxy} + {proxies.map((x) => ( + + {x.name} · {proxyKindLabel(x.kind)} {x.addr} + + ))} + + +
+ + {/* 勾选框和文字**分开挂**:套在一个 label 里点一下会切换两次,等于点不动 */} + {!relogin && ( + + setUnderstood(v === true)} + /> + + {t.understood} + + + )} +
+ )} + + {phase.at === "waiting" && ( +
+
+ + {t.waiting} +
+

{t.hint}

+
+ +
+
+ )} + + {phase.at === "done" && ( +
+

+ {t.done({phase.provider})} + {phase.account && ` ${t.account(phase.account)}`} +

+

{t.doneHint}

+
+ )} + + {error &&

{error}

} + + + {phase.at === "done" ? ( + + ) : ( + <> + + {phase.at === "form" && ( + + )} + + )} + +
+
+ ); +} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 5ed1ca9b..fdbacc0d 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -34,6 +34,9 @@ import type { ResetCreditUsed, SpeedQuote, SpeedResult, + ZaiFamily, + ZaiLogin, + ZaiLoginStatus, } from "@/types"; export interface UpstreamStats { @@ -76,6 +79,13 @@ export const api = { copyChatgptCode: (id: string) => invoke("copy_chatgpt_code", { id }), chatgptLoginStatus: (id: string) => invoke("chatgpt_login_status", { id }), cancelChatgptLogin: (id: string) => invoke("cancel_chatgpt_login", { id }), + /** 开始一次 Z.ai / BigModel 登录。顺手打开授权页 —— 地址留在 Rust 侧 */ + startZaiLogin: (family: ZaiFamily, name: string, proxy: string) => + invoke("start_zai_login", { family, name, proxy }), + reopenZaiLogin: (id: string) => invoke("reopen_zai_login", { id }), + zaiLoginStatus: (id: string) => invoke("zai_login_status", { id }), + cancelZaiLogin: (id: string) => invoke("cancel_zai_login", { id }), + chatgptUsage: (name: string) => invoke("chatgpt_usage", { name }), chatgptResets: (name: string) => invoke("chatgpt_resets", { name }), /** 用掉一张卡。**用掉就回不来**,调用前必须让用户确认 */ diff --git a/src/upstreams/presets.ts b/src/upstreams/presets.ts index d54bebfc..bc4fc3c5 100644 --- a/src/upstreams/presets.ts +++ b/src/upstreams/presets.ts @@ -1,4 +1,5 @@ import { textOf } from "@/i18n"; +import type { ZaiFamily } from "@/types"; import { presetsText } from "./presets.i18n"; /** @@ -35,6 +36,24 @@ export const CUSTOM: Preset = { */ export const CHATGPT = "chatgpt-login"; +/** + * 「Z.ai 账号」在服务类型里的取值。**它不是一份预设**:选中它之后走的是登录, + * 密钥由 core 在登录成功时写入 + */ +export const ZAI = "zai-login"; + +/** + * 两家账号登录后会用的接口地址。 + * + * **地址由 core 决定**,这里的两份只用来在登录对话框里显示「请求会发往哪里」, + * 以及认出「这个名字上已有的上游正是这一家」——换句话说,它错了也只是显示错, + * 登录本身不受影响。 + */ +export const ZAI_ENDPOINTS: Record = { + zai: "https://api.z.ai/api/anthropic", + bigmodel: "https://open.bigmodel.cn/api/anthropic", +}; + export const PRESETS: Preset[] = [ { id: "anthropic",