diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 734919e7..594541a4 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -546,6 +546,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + [[package]] name = "cookie" version = "0.18.2" @@ -908,6 +928,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "dlv-list" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" +dependencies = [ + "const-random", +] + [[package]] name = "dom_query" version = "0.27.0" @@ -1609,6 +1638,12 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.15.5" @@ -1754,7 +1789,7 @@ dependencies = [ "tokio", "tower-service", "tracing", - "windows-registry", + "windows-registry 0.6.1", ] [[package]] @@ -2722,6 +2757,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-multimap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79" +dependencies = [ + "dlv-list", + "hashbrown 0.14.5", +] + [[package]] name = "ordered-stream" version = "0.2.0" @@ -3282,6 +3327,16 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rust-ini" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" +dependencies = [ + "cfg-if", + "ordered-multimap", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -4206,6 +4261,27 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "tauri-plugin-deep-link" +version = "2.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d489b8ecceae1cd09f6e1f7606f2095ac721cc8d54cf2f0e6bb377cc52cff6" +dependencies = [ + "dunce", + "plist", + "rust-ini", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.20", + "tracing", + "url", + "windows-registry 0.5.3", + "windows-result 0.3.4", +] + [[package]] name = "tauri-plugin-notification" version = "2.4.0" @@ -4225,6 +4301,28 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-opener" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d60366174b745b4ef5824b8bbc1c457fd08f0ce101ff643c0a49181a9f4e91" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.20", + "url", + "windows", + "zbus", +] + [[package]] name = "tauri-plugin-shell" version = "2.3.6" @@ -4430,7 +4528,9 @@ dependencies = [ "tauri-build", "tauri-plugin-autostart", "tauri-plugin-clipboard-manager", + "tauri-plugin-deep-link", "tauri-plugin-notification", + "tauri-plugin-opener", "tauri-plugin-shell", "tauri-plugin-updater", "thiserror 2.0.20", @@ -4533,6 +4633,15 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -4866,8 +4975,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.4.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.4.0#c76dc8626e07fea52fc45a96eb96d948b29a5daa" +version = "0.5.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.5.0#d5caa054c16064d8cefc9ab003e830b69709fbb5" dependencies = [ "serde", "serde_json", @@ -5461,6 +5570,17 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-registry" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +dependencies = [ + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + [[package]] name = "windows-registry" version = "0.6.1" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 61085749..1c0319d7 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -21,13 +21,17 @@ tauri-build = { version = "2", features = [] } tauri = { version = "2", features = ["macos-private-api", "tray-icon"] } tauri-plugin-autostart = "2" tauri-plugin-shell = "2" +# 在默认浏览器里打开授权页 +tauri-plugin-opener = "2" +# 浏览器里授权完成之后,那一页把应用带回前台(`thinkwatch://`) +tauri-plugin-deep-link = "2" # 控制面契约来自 core。UI 和 CLI 依赖同一份类型,不会各写一遍。 # **钉在 tag 上,不是分支。**跟着 `main` 走意味着同一份源码今天和明天 # 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制 # 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从 # 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。 -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.4.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.5.0" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/chatgpt.rs b/src-tauri/src/chatgpt.rs new file mode 100644 index 00000000..6dd897bb --- /dev/null +++ b/src-tauri/src/chatgpt.rs @@ -0,0 +1,138 @@ +//! ChatGPT 账号的命令:登录、用量、额度重置卡。 +//! +//! 登录本身在 core:它给出授权地址、在本机等浏览器回调、把凭据写进配置。这一层做 +//! 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 只接受应用自己的协议 +const RETURN_TO: &str = "thinkwatch://chatgpt/login"; + +/// 正在等的那次登录:(登录 ID, 授权地址)。**同一时刻只有一次**,core 那边也是 +static PENDING: Mutex> = Mutex::new(None); + +#[tauri::command] +pub async fn start_chatgpt_login( + app: tauri::AppHandle, + state: tauri::State<'_, AppState>, + name: Option, + proxy: Option, +) -> Out { + let login = state + .control + .start_chatgpt_login(&tw_api::ChatgptLoginStart { + name, + proxy, + return_to: Some(RETURN_TO.to_string()), + }) + .await + .map_err(text)?; + if let Ok(mut g) = PENDING.lock() { + *g = Some((login.id.clone(), login.authorize_url.clone())); + } + open_page(&app, &login.authorize_url)?; + Ok(login) +} + +/// 浏览器被关掉、或者授权页打不开时再打开一次。**只认还在等的那一次** +#[tauri::command] +pub async fn reopen_chatgpt_login(app: tauri::AppHandle, id: String) -> Out<()> { + let url = PENDING + .lock() + .ok() + .and_then(|g| g.clone()) + .filter(|(pending, _)| *pending == id) + .map(|(_, url)| url) + .ok_or_else(|| "这次登录已经结束,请重新发起".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| format!("无法打开浏览器:{e}")) +} + +#[tauri::command] +pub async fn chatgpt_login_status( + state: tauri::State<'_, AppState>, + id: String, +) -> Out { + state.control.chatgpt_login_status(&id).await.map_err(text) +} + +#[tauri::command] +pub async fn cancel_chatgpt_login( + state: tauri::State<'_, AppState>, + id: String, +) -> Out { + forget(&id); + state.control.cancel_chatgpt_login(&id).await.map_err(text) +} + +pub fn forget(id: &str) { + if let Ok(mut g) = PENDING.lock() + && g.as_ref().is_some_and(|(pending, _)| pending == id) + { + *g = None; + } +} + +#[tauri::command] +pub async fn chatgpt_usage( + state: tauri::State<'_, AppState>, + name: String, +) -> Out { + state.control.chatgpt_usage(&name).await.map_err(text) +} + +#[tauri::command] +pub async fn chatgpt_resets( + state: tauri::State<'_, AppState>, + name: String, +) -> Out { + state.control.chatgpt_resets(&name).await.map_err(text) +} + +/// 用掉一张额度重置卡。**界面上必须先让用户确认**:卡用掉就回不来 +#[tauri::command] +pub async fn use_chatgpt_reset( + state: tauri::State<'_, AppState>, + name: String, + credit_id: Option, + idempotency_key: String, +) -> Out { + state + .control + .use_chatgpt_reset( + &name, + &tw_api::ResetCreditUse { + idempotency_key, + credit_id, + }, + ) + .await + .map_err(text) +} + +/// 浏览器里点了「返回 ThinkWatch」。**窗口可能已经被销毁**(菜单栏模式下关窗即销毁), +/// 所以这里要能把它重新建起来,而不只是 `show()` +pub fn handle_return(app: &tauri::AppHandle, urls: &[String]) { + if !urls.iter().any(|u| u.starts_with("thinkwatch://")) { + return; + } + let _ = crate::show_main_window(app); +} diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 24091158..21d95da4 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -568,6 +568,57 @@ impl ControlClient { .await } + // ───────────────────────────────────────── ChatGPT 账号 + + /// 开始一次登录。回来的地址要在浏览器里打开,core 在本机等回调 + pub async fn start_chatgpt_login( + &self, + req: &tw_api::ChatgptLoginStart, + ) -> Result { + self.post_json("/chatgpt/login", req).await + } + + pub async fn chatgpt_login_status(&self, id: &str) -> Result { + Ok(serde_json::from_slice( + &self.get(&format!("/chatgpt/login/{}", segment(id))).await?, + )?) + } + + pub async fn cancel_chatgpt_login(&self, id: &str) -> Result { + self.send_json( + hyper::Method::DELETE, + &format!("/chatgpt/login/{}", segment(id)), + &(), + ) + .await + } + + pub async fn chatgpt_usage(&self, name: &str) -> Result { + Ok(serde_json::from_slice( + &self + .get(&format!("/providers/{}/chatgpt/usage", segment(name))) + .await?, + )?) + } + + pub async fn chatgpt_resets(&self, name: &str) -> Result { + Ok(serde_json::from_slice( + &self + .get(&format!("/providers/{}/chatgpt/resets", segment(name))) + .await?, + )?) + } + + /// 用掉一张额度重置卡。**只在用户明确点下去时调**:卡用掉就回不来 + pub async fn use_chatgpt_reset( + &self, + name: &str, + req: &tw_api::ResetCreditUse, + ) -> Result { + self.post_json(&format!("/providers/{}/chatgpt/resets", segment(name)), req) + .await + } + // ───────────────────────────────────────── 代理 pub async fn create_proxy(&self, req: &tw_api::ProxySave) -> Result { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 94d9091a..8219f430 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -12,6 +12,7 @@ use tauri::tray::TrayIconBuilder; use tauri::{Emitter, Manager, WebviewUrl, WebviewWindowBuilder}; pub mod autostart; +pub mod chatgpt; pub mod control; pub mod memcheck; pub mod menubar; @@ -1211,6 +1212,8 @@ pub fn run() { .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_clipboard_manager::init()) .plugin(tauri_plugin_shell::init()) + .plugin(tauri_plugin_opener::init()) + .plugin(tauri_plugin_deep_link::init()) .plugin(tauri_plugin_autostart::init( // LaunchAgent 模式:往 ~/Library/LaunchAgents 写一个 plist。 // 不是 SMAppService、也不是登录项 API —— 插件在 macOS 上就是 @@ -1250,6 +1253,13 @@ pub fn run() { upstreams::update_proxy, upstreams::delete_proxy, upstreams::test_proxy, + chatgpt::start_chatgpt_login, + chatgpt::reopen_chatgpt_login, + chatgpt::chatgpt_login_status, + chatgpt::cancel_chatgpt_login, + chatgpt::chatgpt_usage, + chatgpt::chatgpt_resets, + chatgpt::use_chatgpt_reset, upstreams::pricing_status, upstreams::refresh_pricing, upstreams::set_price_auto_update, @@ -1387,6 +1397,17 @@ pub fn run() { memcheck::run(handle.clone()); } + // 浏览器里授权完成之后点「返回 ThinkWatch」:把应用带回前台。 + // **窗口这时可能根本不存在**(菜单栏模式下关窗即销毁) + { + use tauri_plugin_deep_link::DeepLinkExt; + let h = handle.clone(); + handle.deep_link().on_open_url(move |event| { + let urls: Vec = event.urls().iter().map(|u| u.to_string()).collect(); + chatgpt::handle_return(&h, &urls); + }); + } + // 事件桥:控制面的 SSE → Tauri 事件 → 前端。 let h = handle.clone(); let sock = default_socket(); @@ -1684,7 +1705,7 @@ fn check_autostart_path(app: &tauri::AppHandle) { /// /// **「根本不创建」不是「创建后隐藏」**:后者省不了内存也省不了 /// 启动时间,而且窗口会有一帧闪烁 —— 开机的时候屏幕上什么都不该出现。 -fn show_main_window(app: &tauri::AppHandle) -> tauri::Result<()> { +pub(crate) fn show_main_window(app: &tauri::AppHandle) -> tauri::Result<()> { if let Some(w) = app.get_webview_window("main") { w.show()?; w.set_focus()?; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 61046d49..722d3b29 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -42,6 +42,13 @@ "https://github.com/ThinkWatchProject/ThinkWatch-Lite/releases/latest/download/latest.json" ], "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEIzNjAzNzAzNDU2MzFGRUYKUldUdkgyTkZBemRnczM3QnpqYnpGTGo5SHZNZCtEbmhTVThnOXlTZHpFTy85WENTMWZmWldpaG4K" + }, + "deep-link": { + "desktop": { + "schemes": [ + "thinkwatch" + ] + } } } } diff --git a/src/types.ts b/src/types.ts index 0272bbcd..b4dd0ecb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -163,8 +163,26 @@ export type CoreEvent = /** 真的切断了流吗。**高危 + 不受信任 + 拦截态**三者同时成立才会 */ blocked: boolean; at_ms: number; + } + /** + * 浏览器里的登录有结果了。 + * + * **界面等的就是这一条**:收到它就能说明结果,不用一直问 core。 + */ + | { + kind: "login_finished"; + id: number; + /** 发起登录时拿到的 ID */ + login: string; + status: LoginStatus; + provider?: string; + error?: string; + at_ms: number; }; +/** `done` 之外都不会留下上游 */ +export type LoginStatus = "pending" | "done" | "failed" | "expired" | "cancelled"; + /** * 上游报回来的 token 用量。 * @@ -848,6 +866,70 @@ export interface HeaderView { export interface OAuthView { endpoint: string; client_id?: string | null; + /** access token 什么时候过期,RFC 3339。不知道时没有 */ + expires_at?: string | null; + /** 最近一次换 token 失败的原因。恢复之后没有 */ + failure?: string | null; + /** 凭据已失效,只有重新登录能恢复 */ + needs_login?: boolean; +} + +// —— ChatGPT 账号 —— + +/** 一次登录。地址要在浏览器里打开,core 在本机等回调 */ +export interface ChatgptLogin { + id: string; + authorize_url: string; + expires_in_secs: number; +} + +export interface ChatgptLoginStatus { + id: string; + status: LoginStatus; + /** 登录成功后写进配置的上游名 */ + provider?: string | null; + /** `plus` / `pro` / `team` … */ + plan?: string | null; + error?: string | null; +} + +/** 账号的订阅额度 */ +export interface ChatgptUsage { + plan?: string | null; + windows: QuotaWindow[]; + /** 可用的额度重置卡张数。账号没有这一项时没有 */ + reset_credits?: number | null; +} + +/** 一张额度重置卡 */ +export interface ResetCreditView { + id: string; + /** 重置哪种额度,上游的原词 */ + reset_type: string; + /** 上游的原词。`available` 之外的不能用 */ + status: string; + granted_at: string; + expires_at?: string | null; + title?: string | null; + description?: string | null; +} + +export interface ResetCredits { + available_count: number; + credits: ResetCreditView[]; +} + +/** + * 用掉一张卡的结果。 + * + * - `reset`:额度已重置 + * - `nothing_to_reset`:额度没用完,不需要重置,没有扣卡 + * - `no_credit`:没有可用的卡 + * - `already_redeemed`:这个幂等键已经用过,额度在那一次已经重置 + */ +export interface ResetCreditUsed { + code: string; + windows_reset: number; } /** 配置里引用了某个上游的一处 */ diff --git a/src/upstreams/ChatgptAccountDialog.tsx b/src/upstreams/ChatgptAccountDialog.tsx new file mode 100644 index 00000000..4d2188cd --- /dev/null +++ b/src/upstreams/ChatgptAccountDialog.tsx @@ -0,0 +1,225 @@ +import { useCallback, useEffect, useState } from "react"; +import { CircleAlertIcon, RefreshCwIcon } from "lucide-react"; +import { Alert, AlertDescription, AlertTitle } from "@/ui/alert"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/ui/alert-dialog"; +import { Button } from "@/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { Progress } from "@/ui/progress"; +import { Spinner } from "@/ui/spinner"; +import { when } from "@/format"; +import type { ChatgptUsage, ResetCredits, ResetCreditView } from "@/types"; +import { api } from "./api"; +import { errorText, quotaWindowLabel } from "./labels"; + +/** 卡的状态词表由上游给,只有这一个能用 */ +const AVAILABLE = "available"; + +/** 上游的状态词。认不出来的原样显示 —— 编不出来的说法比一个陌生的词更糟 */ +const STATUS: Record = { + available: "可用", + redeemed: "已使用", + expired: "已过期", + revoked: "已作废", +}; + +/** 用一张卡的结果 */ +const CODES: Record = { + reset: "额度已重置", + nothing_to_reset: "额度尚未用完,未使用重置卡", + no_credit: "没有可用的重置卡", + already_redeemed: "这次操作此前已经完成,额度已在那一次重置", +}; + +/** + * ChatGPT 账号的额度与额度重置卡。 + * + * **重置卡用掉就回不来**,所以只有用户明确点下去、并在确认之后才会用掉一张; + * 网关自己从不使用。同一次操作重试时带同一个幂等键,上游据此不会重复扣卡。 + */ +export function ChatgptAccountDialog({ name, onClose }: { name: string; onClose: () => void }) { + const [usage, setUsage] = useState(null); + const [credits, setCredits] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [confirming, setConfirming] = useState(null); + const [using, setUsing] = useState(false); + const [outcome, setOutcome] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const [u, c] = await Promise.all([api.chatgptUsage(name), api.chatgptResets(name)]); + setUsage(u); + setCredits(c); + } catch (e) { + setError(errorText(e)); + } finally { + setLoading(false); + } + }, [name]); + + useEffect(() => { + void load(); + }, [load]); + + async function use(credit: ResetCreditView) { + setUsing(true); + setError(null); + try { + // 幂等键按这一次操作生成:重试时不会再扣一张 + const key = `${name}:${credit.id}:${Date.now()}`; + const r = await api.useChatgptReset(name, credit.id, key); + setOutcome(CODES[r.code] ?? r.code); + await load(); + } catch (e) { + setError(errorText(e)); + } finally { + setUsing(false); + setConfirming(null); + } + } + + const list = credits?.credits ?? []; + + return ( + <> + !o && onClose()}> + + + 额度与重置卡 + + 上游 {name} + {usage?.plan && ` · 订阅类型 ${usage.plan}`} + + + + {loading && !usage ? ( +
+ + 正在读取 +
+ ) : ( +
+
+

订阅额度

+ {usage && usage.windows.length > 0 ? ( + usage.windows.map((w) => ( +
+
+ {quotaWindowLabel(w.window)} + {Math.round(w.used_percent)}% +
+ + {w.reset_in_secs != null && ( +

+ {when(Date.now() + w.reset_in_secs * 1000)} 重置 +

+ )} +
+ )) + ) : ( +

上游未报告额度。

+ )} +
+ +
+

+ 额度重置卡{credits && ` · 可用 ${credits.available_count} 张`} +

+

+ 一张重置卡把已用完的额度窗口重置一次。使用之后无法撤回,网关不会自动使用。 +

+ {list.length === 0 ? ( +

账号上没有重置卡。

+ ) : ( +
    + {list.map((c) => ( +
  • +
    +

    {c.title ?? "额度重置卡"}

    +

    + {STATUS[c.status] ?? c.status} + {/* 到期日只对还能用的卡有意义 */} + {c.status === AVAILABLE && + c.expires_at && + ` · ${c.expires_at.slice(0, 10)} 到期`} +

    +
    + +
  • + ))} +
+ )} +
+ + {outcome &&

{outcome}

} + {error &&

{error}

} +
+ )} + + + + + +
+
+ + !o && setConfirming(null)}> + + + 使用一张额度重置卡 + + 这张卡将被立即使用,用于重置已经用完的额度窗口。使用之后无法撤回。 + + + + + 额度尚未用完时不会消耗 + + 上游在没有需要重置的窗口时直接返回,不扣除这张卡。 + + + + 取消 + confirming && void use(confirming)} + disabled={using} + > + 使用 + + + + + + ); +} diff --git a/src/upstreams/ChatgptLoginDialog.tsx b/src/upstreams/ChatgptLoginDialog.tsx new file mode 100644 index 00000000..9bf07d94 --- /dev/null +++ b/src/upstreams/ChatgptLoginDialog.tsx @@ -0,0 +1,270 @@ +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 { Spinner } from "@/ui/spinner"; +import type { ChatgptLoginStatus, CoreEvent, Overview } from "@/types"; +import { api } from "./api"; +import { errorText, proxyKindLabel } from "./labels"; +import { FormItem } from "./parts"; +import { freeName } from "./upstreamForm"; + +/** 登录还没结果时,多久问一次 core。事件是主路,这是它的兜底 */ +const POLL_MS = 2_000; + +type Phase = + | { at: "form" } + | { at: "waiting"; id: string } + | { at: "done"; provider: string; plan: string | null }; + +/** + * 用 ChatGPT 账号新建上游。 + * + * 授权在浏览器里完成,core 在本机等回调、把凭据写进配置;这个对话框负责登录之前 + * 的说明与选择,以及等待期间的状态。**登录只能有一次在进行**,所以离开时要收尾。 + */ +export function ChatgptLoginDialog({ + ov, + onClose, + onSaved, +}: { + ov: Overview; + onClose: () => void; + onSaved: (name: string) => void; +}) { + const proxies = ov.proxies ?? []; + const taken = ov.providers.map((p) => p.name); + const [name, setName] = useState(() => freeName("chatgpt", taken)); + const [proxy, setProxy] = useState("direct"); + const [understood, setUnderstood] = useState(false); + const [phase, setPhase] = useState({ at: "form" }); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + // 卸载之后不要再写状态:等待期间用户可能直接关掉对话框。 + // **挂载时要置回来** —— 开发模式下 effect 会先跑一遍再清理再跑一遍, + // 只在清理里置 false 的话,第二次挂载起就一直是「已卸载」 + const alive = useRef(true); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + + const waiting = phase.at === "waiting" ? phase.id : null; + + function settle(s: ChatgptLoginStatus) { + if (!alive.current || s.status === "pending") return; + if (s.status === "done" && s.provider) { + setPhase({ at: "done", provider: s.provider, plan: s.plan ?? null }); + onSaved(s.provider); + return; + } + setPhase({ at: "form" }); + setError( + s.error ?? + (s.status === "expired" ? "授权未在有效期内完成" : "登录已取消"), + ); + } + + // 结果由 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 t = setInterval(() => { + api + .chatgptLoginStatus(waiting) + .then(settle) + .catch(() => { + // 控制面一时不通:下一轮再问 + }); + }, POLL_MS); + return () => { + void un.then((f) => f()); + clearInterval(t); + }; + // settle 每次渲染都是新的,但订阅只该跟着这次登录重建 + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [waiting]); + + async function start() { + setBusy(true); + setError(null); + try { + const login = await api.startChatgptLogin(name.trim(), proxy); + if (alive.current) setPhase({ at: "waiting", id: login.id }); + } catch (e) { + setError(errorText(e)); + } finally { + setBusy(false); + } + } + + async function cancel() { + if (waiting) { + try { + await api.cancelChatgptLogin(waiting); + } catch { + // 取消失败也要关掉:它最多在 15 分钟后自己过期 + } + } + onClose(); + } + + const nameTaken = taken.includes(name.trim()) && phase.at === "form"; + const canStart = name.trim().length > 0 && !nameTaken && understood && !busy; + + return ( + !o && void cancel()}> + + + 使用 ChatGPT 账号 + + 登录 OpenAI 账号,把 ChatGPT 订阅额度作为一个上游使用。授权在浏览器中完成。 + + + + {phase.at === "form" && ( +
+ + + 登录之前请确认以下几点 + +
    +
  • + ChatGPT 订阅的用途是在 OpenAI 的官方客户端中对话。把订阅额度用于其他客户端不受 + OpenAI 支持,账号可能因此受限。 +
  • +
  • + 请求会如实说明来自 ThinkWatch,不伪装成其他客户端。 +
  • +
  • 登录得到的凭据保存在本机的配置文件中,与其他上游一同管理。
  • +
  • 删除该上游时,登录凭据会一并吊销。
  • +
+
+
+ +
+ + setName(e.target.value)} + aria-invalid={nameTaken} + /> + {nameTaken &&

这个名称已被占用

} +
+ + setProxy(e.target.value)} + > + 直连 + 系统代理 + {proxies.map((x) => ( + + {x.name} · {proxyKindLabel(x.kind)} {x.addr} + + ))} + + +
+ + {/* 勾选框和文字**分开挂**:套在一个 label 里点一下会切换两次,等于点不动 */} + + setUnderstood(v === true)} + /> + + 已阅读上述说明,继续登录 + + +
+ )} + + {phase.at === "waiting" && ( +
+
+ + 授权页已在浏览器中打开,完成授权后此处会自动继续。 +
+

+ 授权有效期 15 分钟。浏览器未打开时可再打开一次。 +

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

+ 已登录,上游 {phase.provider} 已写入配置。 + {phase.plan && ` 订阅类型 ${phase.plan}。`} +

+

+ 模型范围、计费方式等可在该上游的编辑对话框中调整。 +

+
+ )} + + {error &&

{error}

} + + + {phase.at === "done" ? ( + + ) : ( + <> + + {phase.at === "form" && ( + + )} + + )} + +
+
+ ); +} diff --git a/src/upstreams/ConnectionSection.tsx b/src/upstreams/ConnectionSection.tsx index a576312d..ec29a24d 100644 --- a/src/upstreams/ConnectionSection.tsx +++ b/src/upstreams/ConnectionSection.tsx @@ -7,7 +7,7 @@ import type { Overview, ProviderPreview, ProviderTestResult, ProviderView } from import { HeaderEditor } from "./HeaderEditor"; import { AUTH_MODES, PROTOCOLS, authHeaderLabel, protocolLabel, proxyKindLabel } from "./labels"; import { FormItem, Note, Segmented } from "./parts"; -import { PRESETS, nameFromUrl, presetById } from "./presets"; +import { CHATGPT, PRESETS, nameFromUrl, presetById } from "./presets"; import { describeModelList, freeName, type UpstreamForm } from "./upstreamForm"; /** 「新建代理…」在下拉里的占位值。名称首尾不能有空白,不会和真实名称重复 */ @@ -23,6 +23,7 @@ export function ConnectionSection({ test, onTest, onNewProxy, + onChatgptLogin, }: { form: UpstreamForm; set: (patch: Partial) => void; @@ -34,6 +35,8 @@ export function ConnectionSection({ test: ProviderTestResult | null; onTest: () => void; onNewProxy: () => void; + /** 服务类型选了 ChatGPT 账号:那一条走登录,不走这张表单 */ + onChatgptLogin: () => void; }) { const proxies = ov.proxies ?? []; const taken = ov.providers.map((p) => p.name); @@ -44,6 +47,10 @@ export function ConnectionSection({ : "自动识别(未识别,按原格式转发)"; function pickPreset(id: string) { + if (id === CHATGPT) { + onChatgptLogin(); + return; + } const prev = presetById(form.preset); const next = presetById(id); set({ @@ -75,6 +82,7 @@ export function ConnectionSection({ onChange={(e) => pickPreset(e.target.value)} > 自定义 + ChatGPT 账号(登录) {PRESETS.map((p) => ( {p.label} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 1c4ec04a..3e1e1b2f 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -67,6 +67,7 @@ export function UpstreamDialog({ onSaved, onChanged, onGoToGuard, + onChatgptLogin, }: { mode: UpstreamDialogMode; ov: Overview; @@ -78,6 +79,8 @@ export function UpstreamDialog({ /** 对话框里新建了代理或价目表:外面要重新读概览 */ onChanged: () => void; onGoToGuard: () => void; + /** 改用 ChatGPT 账号登录:这张表单让位给登录对话框 */ + onChatgptLogin: () => void; }) { const editing: ProviderView | null = mode.kind === "edit" ? (ov.providers.find((p) => p.name === mode.name) ?? null) : null; @@ -322,6 +325,7 @@ export function UpstreamDialog({ test={test} onTest={runTest} onNewProxy={() => setNested({ kind: "proxy" })} + onChatgptLogin={onChatgptLogin} /> )} {section === "models" && ( diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 129dbc75..e80f444f 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -18,6 +18,8 @@ export interface UpstreamActions { linkTest: (name: string) => void; speedTest: (name: string) => void; refreshModels: (name: string) => void; + /** ChatGPT 账号上游:额度与重置卡 */ + account: (name: string) => void; toggle: (p: ProviderView) => void; locate: (name: string) => void; remove: (name: string) => void; @@ -119,6 +121,9 @@ function menu(p: ProviderView, a: UpstreamActions): MenuItems { { kind: "item", label: "链路测速", onSelect: () => a.linkTest(p.name) }, { kind: "item", label: "推理测速…", onSelect: () => a.speedTest(p.name) }, { kind: "item", label: "刷新模型列表", onSelect: () => a.refreshModels(p.name) }, + ...(p.protocol === "chatgpt" + ? ([{ kind: "item", label: "额度与重置卡…", onSelect: () => a.account(p.name) }] as MenuItems) + : []), { kind: "sep" }, { kind: "item", label: p.disabled ? "启用" : "停用", onSelect: () => a.toggle(p) }, { kind: "item", label: "在配置文件中定位", onSelect: () => a.locate(p.name) }, diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index d781e4cb..19a1e2cb 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -16,6 +16,8 @@ import { Switch } from "@/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import type { Overview, PricingStatus } from "@/types"; import { api, type UpstreamStats } from "./api"; +import { ChatgptAccountDialog } from "./ChatgptAccountDialog"; +import { ChatgptLoginDialog } from "./ChatgptLoginDialog"; import { DeleteDialog, type Referrer } from "./DeleteDialog"; import { when } from "@/format"; import { errorText } from "./labels"; @@ -33,6 +35,8 @@ export type UpstreamTab = "upstreams" | "proxies" | "pricing"; type DialogState = | null | { kind: "upstream"; mode: UpstreamDialogMode } + | { kind: "chatgpt-login" } + | { kind: "chatgpt-account"; name: string } | { kind: "delete-upstream"; name: string } | { kind: "test"; name: string } | { kind: "link"; provider: string | null } @@ -280,6 +284,7 @@ export default function UpstreamsPage({ linkTest: (name) => setDialog({ kind: "link", provider: name }), speedTest: (name) => setDialog({ kind: "speed", provider: name }), refreshModels: (name) => void refreshModels(name), + account: (name) => setDialog({ kind: "chatgpt-account", name }), toggle: (p) => void toggle(p.name), locate: (name) => onOpenConfigFile(name), remove: (name) => setDialog({ kind: "delete-upstream", name }), @@ -385,6 +390,7 @@ export default function UpstreamsPage({ setDialog(null); onNavigate("guard"); }} + onChatgptLogin={() => setDialog({ kind: "chatgpt-login" })} /> )} {dialog?.kind === "delete-upstream" && ( @@ -408,6 +414,16 @@ export default function UpstreamsPage({ }} /> )} + {dialog?.kind === "chatgpt-login" && ( + setDialog(null)} + onSaved={() => changed()} + /> + )} + {dialog?.kind === "chatgpt-account" && ( + setDialog(null)} /> + )} {dialog?.kind === "test" && ( setDialog(null)} /> )} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 55de8ffe..9696c140 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -7,6 +7,9 @@ */ import { invoke } from "@tauri-apps/api/core"; import type { + ChatgptLogin, + ChatgptLoginStatus, + ChatgptUsage, ConfigWritten, CostGroup, L1Result, @@ -25,6 +28,8 @@ import type { ProviderTestResult, ProxySave, ProxyTest, + ResetCredits, + ResetCreditUsed, SpeedQuote, SpeedResult, } from "@/types"; @@ -60,6 +65,18 @@ export const api = { invoke("delete_proxy", { name, baseVersion }), testProxy: (test: ProxyTest) => invoke("test_proxy", { test }), + /** 开始登录并打开授权页。授权地址留在 Rust 侧,界面不经手 */ + startChatgptLogin: (name: string, proxy: string) => + invoke("start_chatgpt_login", { name, proxy }), + reopenChatgptLogin: (id: string) => invoke("reopen_chatgpt_login", { id }), + chatgptLoginStatus: (id: string) => invoke("chatgpt_login_status", { id }), + cancelChatgptLogin: (id: string) => invoke("cancel_chatgpt_login", { id }), + chatgptUsage: (name: string) => invoke("chatgpt_usage", { name }), + chatgptResets: (name: string) => invoke("chatgpt_resets", { name }), + /** 用掉一张卡。**用掉就回不来**,调用前必须让用户确认 */ + useChatgptReset: (name: string, creditId: string | null, idempotencyKey: string) => + invoke("use_chatgpt_reset", { name, creditId, idempotencyKey }), + pricingStatus: () => invoke("pricing_status"), refreshPricing: () => invoke("refresh_pricing"), setPriceAutoUpdate: (on: boolean, baseVersion: Base) => diff --git a/src/upstreams/labels.ts b/src/upstreams/labels.ts index ccf1ee2e..a65eb39c 100644 --- a/src/upstreams/labels.ts +++ b/src/upstreams/labels.ts @@ -13,8 +13,12 @@ export const PROTOCOLS: { id: string; label: string }[] = [ { id: "gemini", label: "Google Gemini" }, ]; +/** 登录得来的上游,协议不在上面那张表里:它不能在新建表单里选 */ +export const CHATGPT_PROTOCOL = { id: "chatgpt", label: "ChatGPT 账号" }; + /** 地址认不出协议、配置里也没写时,请求按客户端发来的格式原样转发 */ export function protocolLabel(id: string | null | undefined): string { + if (id === CHATGPT_PROTOCOL.id) return CHATGPT_PROTOCOL.label; return PROTOCOLS.find((p) => p.id === id)?.label ?? "协议未识别"; } diff --git a/src/upstreams/presets.ts b/src/upstreams/presets.ts index ed76a0b4..b5fc798c 100644 --- a/src/upstreams/presets.ts +++ b/src/upstreams/presets.ts @@ -23,6 +23,12 @@ export const CUSTOM: Preset = { protocol: "", }; +/** + * 「ChatGPT 账号」在服务类型里的取值。**它不是一份预设**:选中它之后走的是登录, + * 地址、协议和凭据都由 core 在登录成功时写入 + */ +export const CHATGPT = "chatgpt-login"; + export const PRESETS: Preset[] = [ { id: "anthropic",