Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src-tauri/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,6 +803,28 @@ impl ControlClient {
.await
}

// ───────────────────────────────────────── Z.ai / BigModel 账号

/// 开始一次登录。回来的地址要在浏览器里打开,core 自己去问「授权了没有」
pub async fn start_zai_login(&self, req: &tw_api::ZaiLoginStart) -> Result<tw_api::ZaiLogin> {
self.post_json("/zai/login", req).await
}

pub async fn zai_login_status(&self, id: &str) -> Result<tw_api::ZaiLoginStatus> {
Ok(serde_json::from_slice(
&self.get(&format!("/zai/login/{}", segment(id))).await?,
)?)
}

pub async fn cancel_zai_login(&self, id: &str) -> Result<tw_api::ZaiLoginStatus> {
self.send_json(
hyper::Method::DELETE,
&format!("/zai/login/{}", segment(id)),
&(),
)
.await
}

pub async fn chatgpt_usage(&self, name: &str) -> Result<tw_api::ChatgptUsage> {
Ok(serde_json::from_slice(
&self
Expand Down
5 changes: 5 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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,
Expand Down
124 changes: 124 additions & 0 deletions src-tauri/src/zai.rs
Original file line number Diff line number Diff line change
@@ -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<T> = Result<T, String>;

fn text(e: anyhow::Error) -> String {
format!("{e:#}")
}

/// 正在等的那次登录。**同一时刻只有一次**,core 那边也是
static PENDING: Mutex<Option<Pending>> = 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<String>,
name: Option<String>,
proxy: Option<String>,
) -> Out<Login> {
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<tw_api::ZaiLoginStatus> {
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<tw_api::ZaiLoginStatus> {
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;
}
}
19 changes: 19 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 不往外带 */
Expand Down
2 changes: 2 additions & 0 deletions src/upstreams/ConnectionSection.i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const connectionSectionText = messages(
protocol: "接口协议",
service: "服务类型",
chatgpt: "ChatGPT 账号(登录)",
zai: "Z.ai / BigModel 账号(登录)",
name: "名称",
namePlaceholder: "例如 relay-hk",
baseUrl: "接口地址",
Expand Down Expand Up @@ -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",
Expand Down
10 changes: 9 additions & 1 deletion src/upstreams/ConnectionSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/** 「新建代理…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */
Expand All @@ -33,6 +33,7 @@ export function ConnectionSection({
onTest,
onNewProxy,
onChatgptLogin,
onZaiLogin,
}: {
form: UpstreamForm;
set: (patch: Partial<UpstreamForm>) => void;
Expand All @@ -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;
Expand All @@ -61,6 +64,10 @@ export function ConnectionSection({
onChatgptLogin();
return;
}
if (id === ZAI) {
onZaiLogin();
return;
}
const prev = presetById(form.preset);
const next = presetById(id);
set({
Expand Down Expand Up @@ -93,6 +100,7 @@ export function ConnectionSection({
>
<NativeSelectOption value="custom">{CUSTOM.label}</NativeSelectOption>
<NativeSelectOption value={CHATGPT}>{t.chatgpt}</NativeSelectOption>
<NativeSelectOption value={ZAI}>{t.zai}</NativeSelectOption>
{PRESETS.map((p) => (
<NativeSelectOption key={p.id} value={p.id}>
{p.label}
Expand Down
4 changes: 4 additions & 0 deletions src/upstreams/UpstreamDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export function UpstreamDialog({
onSaved,
onChanged,
onChatgptLogin,
onZaiLogin,
}: {
mode: UpstreamDialogMode;
ov: Overview;
Expand All @@ -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);
Expand Down Expand Up @@ -340,6 +343,7 @@ export function UpstreamDialog({
onTest={runTest}
onNewProxy={() => setNested({ kind: "proxy" })}
onChatgptLogin={onChatgptLogin}
onZaiLogin={onZaiLogin}
/>
)}
{section === "models" && (
Expand Down
6 changes: 6 additions & 0 deletions src/upstreams/UpstreamsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 }
Expand Down Expand Up @@ -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" && (
Expand Down Expand Up @@ -498,6 +501,9 @@ export default function UpstreamsPage({
onSaved={() => changed()}
/>
)}
{dialog?.kind === "zai-login" && (
<ZaiLoginDialog ov={ov} onClose={() => setDialog(null)} onSaved={() => changed()} />
)}
{dialog?.kind === "test" && (
<TestConnectionDialog ov={ov} name={dialog.name} onClose={() => setDialog(null)} />
)}
Expand Down
Loading
Loading