diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7a33d8f5..cf0cffe9 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4982,8 +4982,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.6.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.6.0#03b83a78b708a3a9ca35c5c790c85bb4c586e66d" +version = "0.7.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.7.0#8e8a0a28381e034cc2523db7f1548311d2e4b8ce" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index dd6d3e57..eeec7bee 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.6.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.7.0" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/chatgpt.rs b/src-tauri/src/chatgpt.rs index 6dd897bb..5bbc3d59 100644 --- a/src-tauri/src/chatgpt.rs +++ b/src-tauri/src/chatgpt.rs @@ -1,10 +1,12 @@ //! ChatGPT 账号的命令:登录、用量、额度重置卡。 //! -//! 登录本身在 core:它给出授权地址、在本机等浏览器回调、把凭据写进配置。这一层做 +//! 登录本身在 core:它给出授权地址或者设备码、等授权完成、把凭据写进配置。这一层做 //! core 做不到的两件事 —— **打开浏览器**,以及授权完成后**把应用带回前台**。 //! -//! 授权地址存在这里而不是交给界面:界面拿着它,就等于多了一条「界面传来一个地址、 -//! 应用去打开它」的路径。重新打开授权页只按登录 ID 找。 +//! 授权地址和登录码存在这里而不是交给界面:界面拿着地址,就等于多了一条「界面传来 +//! 一个地址、应用去打开它」的路径;拿着码,就等于多了一个往剪贴板里写任意内容的口子。 +//! 重新打开授权页、复制登录码都只按登录 ID 找。**只有设备码要给界面看**,因为用户 +//! 得把它念出来或者抄到另一台设备上。 use std::sync::Mutex; @@ -21,43 +23,92 @@ fn text(e: anyhow::Error) -> String { /// 授权完成后回到应用的地址。core 只接受应用自己的协议 const RETURN_TO: &str = "thinkwatch://chatgpt/login"; -/// 正在等的那次登录:(登录 ID, 授权地址)。**同一时刻只有一次**,core 那边也是 -static PENDING: Mutex> = Mutex::new(None); +/// 正在等的那次登录。**同一时刻只有一次**,core 那边也是 +static PENDING: Mutex> = Mutex::new(None); +struct Pending { + id: String, + /// 在这台电脑上登录:要打开的授权地址 + url: Option, + /// 在其他设备上登录:要输的那个码 + code: Option, +} + +/// 一次登录里界面该知道的部分。**授权地址不在其中** +#[derive(serde::Serialize)] +pub struct Login { + id: String, + user_code: Option, + verification_url: Option, + expires_in_secs: u64, +} + +/// `mode`:`browser` 在这台电脑上开浏览器,`device` 拿一个码去别处输。 +/// +/// **浏览器那条路在这里就把页面打开**:让用户再点一次「打开授权页」,中间那一步 +/// 没有任何意义。 #[tauri::command] pub async fn start_chatgpt_login( app: tauri::AppHandle, state: tauri::State<'_, AppState>, name: Option, proxy: Option, -) -> Out { + mode: Option, +) -> Out { let login = state .control .start_chatgpt_login(&tw_api::ChatgptLoginStart { name, proxy, return_to: Some(RETURN_TO.to_string()), + mode, }) .await .map_err(text)?; if let Ok(mut g) = PENDING.lock() { - *g = Some((login.id.clone(), login.authorize_url.clone())); + *g = Some(Pending { + id: login.id.clone(), + url: login.authorize_url.clone(), + code: login.user_code.clone(), + }); + } + if let Some(url) = &login.authorize_url { + open_page(&app, url)?; } - open_page(&app, &login.authorize_url)?; - Ok(login) + Ok(Login { + id: login.id, + user_code: login.user_code, + verification_url: login.verification_url, + expires_in_secs: login.expires_in_secs, + }) } /// 浏览器被关掉、或者授权页打不开时再打开一次。**只认还在等的那一次** #[tauri::command] pub async fn reopen_chatgpt_login(app: tauri::AppHandle, id: String) -> Out<()> { - let url = PENDING + let url = pending(&id, |p| p.url.clone())?; + open_page(&app, &url) +} + +/// 把登录码放进剪贴板。 +/// +/// **码由这里给出,不从界面传进来**:那样等于给 webview 开一个往剪贴板里写任意内容 +/// 的口子。在 Rust 这边写也不用看 webview 给不给剪贴板权限 —— 一个「复制」按钮 +/// 唯一不能有的表现就是点了没反应。 +#[tauri::command] +pub fn copy_chatgpt_code(app: tauri::AppHandle, id: String) -> Out<()> { + use tauri_plugin_clipboard_manager::ClipboardExt; + let code = pending(&id, |p| p.code.clone())?; + app.clipboard().write_text(code).map_err(|e| e.to_string()) +} + +/// 还在等的那次登录里的某一项。**只认还在等的那一次** +fn pending(id: &str, get: impl Fn(&Pending) -> Option) -> Out { + PENDING .lock() .ok() - .and_then(|g| g.clone()) - .filter(|(pending, _)| *pending == id) - .map(|(_, url)| url) - .ok_or_else(|| "这次登录已经结束,请重新发起".to_string())?; - open_page(&app, &url) + .and_then(|g| g.as_ref().filter(|p| p.id == id).and_then(&get)) + .ok_or_else(|| "这次登录已经结束,请重新发起".to_string()) } fn open_page(app: &tauri::AppHandle, url: &str) -> Out<()> { @@ -85,7 +136,7 @@ pub async fn cancel_chatgpt_login( pub fn forget(id: &str) { if let Ok(mut g) = PENDING.lock() - && g.as_ref().is_some_and(|(pending, _)| pending == id) + && g.as_ref().is_some_and(|p| p.id == id) { *g = None; } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5e008aa0..31fa88b1 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1261,6 +1261,7 @@ pub fn run() { take_pending_view, chatgpt::start_chatgpt_login, chatgpt::reopen_chatgpt_login, + chatgpt::copy_chatgpt_code, chatgpt::chatgpt_login_status, chatgpt::cancel_chatgpt_login, chatgpt::chatgpt_usage, diff --git a/src/format.test.ts b/src/format.test.ts index 0a78c47d..6cac6c07 100644 --- a/src/format.test.ts +++ b/src/format.test.ts @@ -5,6 +5,7 @@ import { latency, money, repeated, + resetIn, statusTone, tokens, when, @@ -196,3 +197,24 @@ describe("金额", () => { expect(usd(2_500_000)).toBe("$2.50"); }); }); + +describe("额度重置时间", () => { + it("按量级说,不精确到分", () => { + expect(resetIn(90)).toBe("2 分钟后"); + expect(resetIn(3 * 3600)).toBe("3 小时后"); + expect(resetIn(4 * 86400)).toBe("4 天后"); + }); + /** 59 分 30 秒说成「60 分钟后」是错的量级 */ + it("进位之后换下一个量级", () => { + expect(resetIn(3570)).toBe("1 小时后"); + expect(resetIn(86_000)).toBe("1 天后"); + }); + /** 「0 分钟后」读起来像已经重置了,而那时额度还是满的 */ + it("不足一分钟不说成零", () => { + expect(resetIn(20)).toBe("1 分钟内"); + }); + it("上游没给就是不知道,不猜", () => { + expect(resetIn(null)).toBeNull(); + expect(resetIn(undefined)).toBeNull(); + }); +}); diff --git a/src/format.ts b/src/format.ts index fe22474c..8b69bb58 100644 --- a/src/format.ts +++ b/src/format.ts @@ -202,3 +202,21 @@ export function densify( } return out; } + +/** + * 额度还有多久重置。 + * + * **只给一个量级。**这句话贴在进度条旁边,读它是为了知道「今天还够不够用」, + * 不是为了对表 —— 精确到分钟反而要多读一眼。 + * + * 不足一分钟不说「0 分钟后」:那读起来像已经重置了,而那时额度还是满的。 + */ +export function resetIn(secs: number | null | undefined): string | null { + if (secs == null || secs < 0) return null; + if (secs < 60) return "1 分钟内"; + const mins = Math.round(secs / 60); + if (mins < 60) return `${mins} 分钟后`; + const hours = Math.round(secs / 3600); + if (hours < 24) return `${hours} 小时后`; + return `${Math.round(secs / 86400)} 天后`; +} diff --git a/src/types.ts b/src/types.ts index b4dd0ecb..571da743 100644 --- a/src/types.ts +++ b/src/types.ts @@ -876,10 +876,16 @@ export interface OAuthView { // —— ChatGPT 账号 —— -/** 一次登录。地址要在浏览器里打开,core 在本机等回调 */ +/** 在哪台设备上授权:这台机器的浏览器,还是把码输到另一台设备上 */ +export type ChatgptLoginMode = "browser" | "device"; + +/** 一次登录。授权地址留在 Rust 侧,界面拿到的是码和输码的地址 */ export interface ChatgptLogin { id: string; - authorize_url: string; + /** 要用户输进去的登录码。设备码登录才有 */ + user_code?: string | null; + /** 让用户在另一台设备上打开的地址。设备码登录才有 */ + verification_url?: string | null; expires_in_secs: number; } diff --git a/src/upstreams/ChatgptAccountDialog.tsx b/src/upstreams/ChatgptAccountDialog.tsx deleted file mode 100644 index 4d2188cd..00000000 --- a/src/upstreams/ChatgptAccountDialog.tsx +++ /dev/null @@ -1,225 +0,0 @@ -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/ChatgptAccountSection.tsx b/src/upstreams/ChatgptAccountSection.tsx new file mode 100644 index 00000000..35244ad3 --- /dev/null +++ b/src/upstreams/ChatgptAccountSection.tsx @@ -0,0 +1,281 @@ +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 { Input } from "@/ui/input"; +import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Progress } from "@/ui/progress"; +import { Spinner } from "@/ui/spinner"; +import { resetIn } from "@/format"; +import type { ChatgptUsage, Overview, ProviderView, ResetCredits, ResetCreditView } from "@/types"; +import { api } from "./api"; +import { errorText, proxyKindLabel, quotaWindowLabel } from "./labels"; +import { FormItem } from "./parts"; +import type { UpstreamForm } from "./upstreamForm"; + +/** 卡的状态词表由上游给,只有这一个能用 */ +const AVAILABLE = "available"; + +/** 上游的状态词。认不出来的原样显示 —— 编不出来的说法比一个陌生的词更糟 */ +const STATUS: Record = { + available: "可用", + redeemed: "已使用", + expired: "已过期", + revoked: "已作废", +}; + +/** 用一张卡的结果 */ +const CODES: Record = { + reset: "额度已重置", + nothing_to_reset: "额度尚未用完,未使用重置卡", + no_credit: "没有可用的重置卡", + already_redeemed: "这次操作此前已经完成,额度已在那一次重置", +}; + +/** + * ChatGPT 账号上游的「账号」一节:叫什么、从哪出去、登录状态、还剩多少额度。 + * + * 这一家没有可填的连接信息 —— 地址、协议、凭据都由登录决定,**把它们摆成 + * 输入框只会让人以为可以改**。 + * + * **重置卡用掉就回不来**,所以只有用户明确点下去、并在确认之后才会用掉一张; + * 网关自己从不使用。同一次操作重试时带同一个幂等键,上游据此不会重复扣卡。 + */ +export function ChatgptAccountSection({ + form, + set, + editing, + ov, + onRelogin, +}: { + form: UpstreamForm; + set: (patch: Partial) => void; + editing: ProviderView; + ov: Overview; + onRelogin: () => void; +}) { + const name = editing.name; + 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]); + + // 额度只在 core 的内存里:冷启动之后第一次打开就去问一次 + 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 ?? []; + const available = list.filter((c) => c.status === AVAILABLE); + + return ( +
+
+ + set({ name: e.target.value })} + /> + + + set({ proxy: e.target.value })} + > + 直连 + 系统代理 + {(ov.proxies ?? []).map((x) => ( + + {x.name} · {proxyKindLabel(x.kind)} {x.addr} + + ))} + + +
+ + + +
+
+

订阅额度

+ +
+ {loading && !usage ? ( +

正在读取

+ ) : usage && usage.windows.length > 0 ? ( +
+ {usage.windows.map((w) => { + const reset = resetIn(w.reset_in_secs); + return ( +
+
+ {quotaWindowLabel(w.window)}窗口 + + {Math.round(w.used_percent)}%{reset && ` · ${reset}重置`} + +
+ +
+ ); + })} +
+ ) : ( +

上游未报告额度。

+ )} +
+ +
+
+

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

+
+

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

+ {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}> + 使用 + + + + +
+ ); +} + +/** 登录状态:**凭据失效时这里是唯一的出路**,所以它自己就带着重新登录 */ +function LoginBox({ + editing, + plan, + onRelogin, +}: { + editing: ProviderView; + plan: string | null; + onRelogin: () => void; +}) { + const oauth = editing.oauth; + const broken = oauth?.needs_login === true; + const expires = oauth?.expires_at ? Date.parse(oauth.expires_at) : NaN; + const left = Number.isNaN(expires) ? null : resetIn((expires - Date.now()) / 1000); + return ( +
+
+
+

+ {broken ? "登录已失效" : "已登录"} + {plan && !broken && ` · ${plan}`} +

+

+ {broken + ? (oauth?.failure ?? "需要重新登录才能继续使用这个上游。") + : `${left ? `凭据 ${left}过期,到期前自动续期 · ` : ""}请求计入订阅额度,不计算费用`} +

+
+ +
+
+ ); +} diff --git a/src/upstreams/ChatgptLoginDialog.tsx b/src/upstreams/ChatgptLoginDialog.tsx index 9bf07d94..86f3637c 100644 --- a/src/upstreams/ChatgptLoginDialog.tsx +++ b/src/upstreams/ChatgptLoginDialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from "react"; -import { CircleAlertIcon, ExternalLinkIcon } from "lucide-react"; +import { CircleAlertIcon, CopyIcon, ExternalLinkIcon, SmartphoneIcon } from "lucide-react"; import { listen } from "@tauri-apps/api/event"; import { Alert, AlertDescription, AlertTitle } from "@/ui/alert"; import { Button } from "@/ui/button"; @@ -16,9 +16,9 @@ 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 type { ChatgptLoginMode, ChatgptLoginStatus, CoreEvent, Overview } from "@/types"; import { api } from "./api"; -import { errorText, proxyKindLabel } from "./labels"; +import { errorText, proxyKindLabel, shortUrl } from "./labels"; import { FormItem } from "./parts"; import { freeName } from "./upstreamForm"; @@ -27,32 +27,41 @@ const POLL_MS = 2_000; type Phase = | { at: "form" } - | { at: "waiting"; id: string } + /** 授权页已经在这台机器的浏览器里打开 */ + | { at: "browser"; id: string } + /** 码已经拿到,等用户在另一台设备上输 */ + | { at: "device"; id: string; code: string; url: string } | { at: "done"; provider: string; plan: string | null }; /** - * 用 ChatGPT 账号新建上游。 + * 用 ChatGPT 账号新建上游,或给已有的账号换一次凭据。 * - * 授权在浏览器里完成,core 在本机等回调、把凭据写进配置;这个对话框负责登录之前 - * 的说明与选择,以及等待期间的状态。**登录只能有一次在进行**,所以离开时要收尾。 + * **在哪台设备上授权由用户选**:这台机器的浏览器,或者把一个码输到另一台已经登录 + * 的设备上 —— 后者是这台机器上没有浏览器、或者浏览器登不进去时唯一的路。两条路 + * 的凭据都由 core 写进配置。**登录只能有一次在进行**,所以离开时要收尾。 */ export function ChatgptLoginDialog({ ov, + relogin, onClose, onSaved, }: { ov: Overview; + /** 给这个已有的账号换一次凭据:名称固定,出站方式沿用它的 */ + relogin?: { name: string; proxy: string }; 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 [name, setName] = useState(() => relogin?.name ?? freeName("chatgpt", 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); + const [copied, setCopied] = useState(false); // 卸载之后不要再写状态:等待期间用户可能直接关掉对话框。 // **挂载时要置回来** —— 开发模式下 effect 会先跑一遍再清理再跑一遍, // 只在清理里置 false 的话,第二次挂载起就一直是「已卸载」 @@ -64,7 +73,7 @@ export function ChatgptLoginDialog({ }; }, []); - const waiting = phase.at === "waiting" ? phase.id : null; + const waiting = phase.at === "browser" || phase.at === "device" ? phase.id : null; function settle(s: ChatgptLoginStatus) { if (!alive.current || s.status === "pending") return; @@ -109,12 +118,22 @@ export function ChatgptLoginDialog({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [waiting]); - async function start() { + async function start(mode: ChatgptLoginMode) { setBusy(true); setError(null); try { - const login = await api.startChatgptLogin(name.trim(), proxy); - if (alive.current) setPhase({ at: "waiting", id: login.id }); + const login = await api.startChatgptLogin(name.trim(), proxy, mode); + if (!alive.current) return; + setPhase( + login.user_code && login.verification_url + ? { + at: "device", + id: login.id, + code: login.user_code, + url: login.verification_url, + } + : { at: "browser", id: login.id }, + ); } catch (e) { setError(errorText(e)); } finally { @@ -133,21 +152,29 @@ export function ChatgptLoginDialog({ onClose(); } - const nameTaken = taken.includes(name.trim()) && phase.at === "form"; + const nameTaken = !relogin && taken.includes(name.trim()) && phase.at === "form"; const canStart = name.trim().length > 0 && !nameTaken && understood && !busy; return ( !o && void cancel()}> - 使用 ChatGPT 账号 + {relogin ? "重新登录 ChatGPT 账号" : "使用 ChatGPT 账号"} - 登录 OpenAI 账号,把 ChatGPT 订阅额度作为一个上游使用。授权在浏览器中完成。 + {relogin ? ( + <> + 为上游 {relogin.name} 换一次登录凭据。 + 模型范围、计费方式等设置保持不变。 + + ) : ( + "登录 OpenAI 账号,把 ChatGPT 订阅额度作为一个上游使用。" + )} {phase.at === "form" && (
+ {!relogin && ( 登录之前请确认以下几点 @@ -165,6 +192,7 @@ export function ChatgptLoginDialog({ + )}
@@ -173,6 +201,7 @@ export function ChatgptLoginDialog({ className="font-mono" value={name} onChange={(e) => setName(e.target.value)} + disabled={relogin != null} aria-invalid={nameTaken} /> {nameTaken &&

这个名称已被占用

} @@ -196,6 +225,7 @@ export function ChatgptLoginDialog({
{/* 勾选框和文字**分开挂**:套在一个 label 里点一下会切换两次,等于点不动 */} + {!relogin && ( + )}
)} - {phase.at === "waiting" && ( + {phase.at === "browser" && (
@@ -233,6 +264,44 @@ export function ChatgptLoginDialog({
)} + {phase.at === "device" && ( +
+

+ 在另一台已登录 ChatGPT 的设备上打开{" "} + {shortUrl(phase.url)} + ,输入下面的登录码。 +

+
+ {/* 码要能一眼读准也能选中:字距拉开,等宽字体 */} + + {phase.code} + + +
+
+ + 输入完成后此处会自动继续。 +
+ {/* Codex 也有这一句:拿着别人给的码去输,等于把自己的账号授权给对方 */} +

+ 登录码有效期 15 分钟。只输入这里显示的这一个;由他人提供的登录码请勿输入。 +

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

@@ -256,10 +325,21 @@ export function ChatgptLoginDialog({ 取消 {phase.at === "form" && ( - + <> + {/* 次要的那条路先摆:主按钮留在最右边 */} + + + )} )} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 3e1e1b2f..32923934 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -20,6 +20,7 @@ import type { } from "@/types"; import { api } from "./api"; 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"; @@ -38,7 +39,7 @@ import { type UpstreamForm, } from "./upstreamForm"; -export type Section = "connection" | "models" | "billing" | "security"; +export type Section = "connection" | "account" | "models" | "billing" | "security"; const SECTIONS: { id: Section; label: string }[] = [ { id: "connection", label: "连接" }, @@ -47,6 +48,18 @@ const SECTIONS: { id: Section; label: string }[] = [ { id: "security", label: "安全" }, ]; +/** + * ChatGPT 账号上游的分节。 + * + * **没有「连接」也没有「计费」**:地址、协议、凭据由登录决定,计费方式是订阅制 —— + * 把这些摆成可填的表单,等于邀请用户去改一个改了就坏的东西。 + */ +const ACCOUNT_SECTIONS: { id: Section; label: string }[] = [ + { id: "account", label: "账号" }, + { id: "models", label: "模型" }, + { id: "security", label: "安全" }, +]; + export type UpstreamDialogMode = | { kind: "create" } | { kind: "edit"; name: string; section?: Section }; @@ -79,8 +92,8 @@ export function UpstreamDialog({ /** 对话框里新建了代理或价目表:外面要重新读概览 */ onChanged: () => void; onGoToGuard: () => void; - /** 改用 ChatGPT 账号登录:这张表单让位给登录对话框 */ - onChatgptLogin: () => void; + /** 改用 ChatGPT 账号登录:这张表单让位给登录对话框。带上名字就是给它换一次凭据 */ + onChatgptLogin: (relogin?: { name: string; proxy: string }) => void; }) { const editing: ProviderView | null = mode.kind === "edit" ? (ov.providers.find((p) => p.name === mode.name) ?? null) : null; @@ -89,8 +102,13 @@ export function UpstreamDialog({ editing ? formFromView(editing) : blankForm(), ); const set = (patch: Partial) => setForm((f) => ({ ...f, ...patch })); + // ChatGPT 账号是登录来的,编辑它的那一套分节也不一样 + const account = editing?.protocol === "chatgpt"; + const sections = account ? ACCOUNT_SECTIONS : SECTIONS; const [section, setSection] = useState

( - mode.kind === "edit" ? (mode.section ?? "connection") : "connection", + mode.kind === "edit" + ? (mode.section ?? (account ? "account" : "connection")) + : "connection", ); const [visited, setVisited] = useState>(() => new Set(["connection"])); @@ -274,7 +292,7 @@ export function UpstreamDialog({ // 新建时没检测过就到了模型这一步:替用户检测一次,这一步才有内容可选。检测不产生费用 if (to === "models" && !editing && catalog == null && !testing) void runTest(); } - const index = SECTIONS.findIndex((s) => s.id === section); + const index = sections.findIndex((s) => s.id === section); const autoBilling = editing && !editing.billing @@ -297,7 +315,9 @@ export function UpstreamDialog({ {editing ? ( {editing.name} ·{" "} - {protocolLabel(editing.protocol)} · {shortUrl(editing.base_url)} + {protocolLabel(editing.protocol)} + {/* 账号上游的地址是登录给的,改不了,写出来只是噪声 */} + {!account && ` · ${shortUrl(editing.base_url)}`} ) : ( @@ -307,13 +327,22 @@ export function UpstreamDialog({
+ {section === "account" && editing && ( + onChatgptLogin({ name: editing.name, proxy: editing.proxy })} + /> + )} {section === "connection" && ( {missing && {missing}} {index > 0 && ( - )} - {index < SECTIONS.length - 1 ? ( - ) : ( diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index e80f444f..ef215604 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -1,4 +1,5 @@ import { Badge } from "@/ui/badge"; +import { Progress } from "@/ui/progress"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; import { Table, @@ -8,9 +9,10 @@ import { TableHeader, TableRow, } from "@/ui/table"; +import { resetIn } from "@/format"; import { usd, type Overview, type ProviderView } from "@/types"; import type { UpstreamStats } from "./api"; -import { billingSummary, egressLabel, protocolLabel, quotaWindowLabel, shortUrl } from "./labels"; +import { billingLabel, egressLabel, protocolLabel, quotaWindowLabel, shortUrl } from "./labels"; export interface UpstreamActions { edit: (name: string) => void; @@ -43,12 +45,11 @@ export function UpstreamTable({ - 名称 + 上游 模型 - 出站 - 计费 - 24 小时请求 - 24 小时费用 + {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} + 额度 / 计费 + 24 小时 首字节 P50 @@ -79,29 +80,25 @@ export function UpstreamTable({ 熔断中 ) : null} - {/* 地址可能很长(带路径的中转):截断,悬停看全 */} + {/* + 协议、地址、出站方式是同一件事的三个部分:这一家在哪、怎么连。 + 地址可能很长(带路径的中转):截断,悬停看全 + */}
{protocolLabel(p.protocol)} · {shortUrl(p.base_url)} - {p.oauth && " · OAuth"} + {/* 直连是默认,不用说 */} + {p.proxy !== "direct" && ` · 经 ${egressLabel(p.proxy)}`}
- - - {egressLabel(p.proxy)} - - - - + + + @@ -150,51 +147,91 @@ function ModelsCell({ p }: { p: ProviderView }) { ); } -function BillingCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { - const quota = stats?.quotas.find((q) => q.provider === p.name); - // 最紧张的那个窗口 - const tight = quota?.windows.reduce<(typeof quota.windows)[number] | null>( +/** + * 还剩多少可用。 + * + * 订阅制上游的答案是额度条 —— 那是这一家「今天还能不能接着用」的唯一答案, + * 而计费方式(订阅制)在额度条出现的那一刻已经不言自明。**上游没报过额度就 + * 退回说计费方式**:画一根 0% 的空条等于说「一点没用」,而事实是不知道。 + */ +function QuotaCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { + const windows = stats?.quotas.find((q) => q.provider === p.name)?.windows ?? []; + // 最紧张的那个窗口:先到的那条线决定什么时候用完 + const tight = windows.reduce<(typeof windows)[number] | null>( (a, w) => (!a || w.used_percent > a.used_percent ? w : a), null, ); + if (tight && !p.disabled) { + const reset = resetIn(tight.reset_in_secs); + return ( + +
+ {Math.round(tight.used_percent)}% + + {reset ? `${quotaWindowLabel(tight.window)} · ${reset}` : quotaWindowLabel(tight.window)} + +
+ +
+ ); + } + const billing = p.billing ?? p.billing_effective; return ( - {billingSummary(p)} - {tight && ( -
- {quotaWindowLabel(tight.window)}额度已用 {Math.round(tight.used_percent)}% -
+
+ {billingLabel(billing)} +
+ {billing === "per-token" && ( +
价目表 {p.pricing ?? "默认"}
)}
); } -function StatsCells({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { +/** + * 一天用了多少:次数在上,花了多少在下。 + * + * 分成两列时,看一行要左右扫两次才知道「这一家跑了多少、花了多少」—— 而这 + * 两个数只有放在一起才有意义。 + */ +function DayCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { const cost = stats?.costs.find((c) => c.name === p.name); - const lat = stats?.latency.find((l) => l.model === p.name); + if (!cost || cost.requests === 0) { + return —; + } const billing = p.billing ?? p.billing_effective; - const money = (() => { - if (!cost || cost.requests === 0) return —; - if (billing === "subscription") return 订阅; - if (billing === "unknown") return 未知; - return ( - <> - {usd(cost.cost_micros)} - {cost.unpriced_requests > 0 && ( -
{cost.unpriced_requests} 次无法计价
+ return ( + +
{cost.requests.toLocaleString()} 次
+
+ {billing === "subscription" ? ( + "订阅内" + ) : billing === "unknown" ? ( + "费用未知" + ) : ( + <> + {usd(cost.cost_micros)} + {cost.unpriced_requests > 0 && ( + · {cost.unpriced_requests} 次无法计价 + )} + )} - - ); - })(); +
+
+ ); +} + +function LatencyCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { + const lat = stats?.latency.find((l) => l.model === p.name); return ( - <> - - {cost && cost.requests > 0 ? cost.requests.toLocaleString() : "—"} - - {money} - - {lat && lat.samples > 0 ? `${lat.p50.toLocaleString()} ms` : "—"} - - + + {lat && lat.samples > 0 ? `${lat.p50.toLocaleString()} ms` : "—"} + ); } diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 19a1e2cb..466152f8 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -16,7 +16,6 @@ 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"; @@ -35,8 +34,8 @@ export type UpstreamTab = "upstreams" | "proxies" | "pricing"; type DialogState = | null | { kind: "upstream"; mode: UpstreamDialogMode } - | { kind: "chatgpt-login" } - | { kind: "chatgpt-account"; name: string } + /** `relogin`:给已有的 ChatGPT 账号换一次凭据,名称和出站方式沿用它的 */ + | { kind: "chatgpt-login"; relogin?: { name: string; proxy: string } } | { kind: "delete-upstream"; name: string } | { kind: "test"; name: string } | { kind: "link"; provider: string | null } @@ -284,7 +283,8 @@ 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 }), + account: (name) => + setDialog({ kind: "upstream", mode: { kind: "edit", name, section: "account" } }), toggle: (p) => void toggle(p.name), locate: (name) => onOpenConfigFile(name), remove: (name) => setDialog({ kind: "delete-upstream", name }), @@ -390,7 +390,7 @@ export default function UpstreamsPage({ setDialog(null); onNavigate("guard"); }} - onChatgptLogin={() => setDialog({ kind: "chatgpt-login" })} + onChatgptLogin={(relogin) => setDialog({ kind: "chatgpt-login", relogin })} /> )} {dialog?.kind === "delete-upstream" && ( @@ -417,13 +417,11 @@ 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 9696c140..21a36c4b 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -8,6 +8,7 @@ import { invoke } from "@tauri-apps/api/core"; import type { ChatgptLogin, + ChatgptLoginMode, ChatgptLoginStatus, ChatgptUsage, ConfigWritten, @@ -65,10 +66,12 @@ 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 }), + /** 开始登录。浏览器登录会顺手打开授权页 —— 授权地址留在 Rust 侧,界面不经手 */ + startChatgptLogin: (name: string, proxy: string, mode: ChatgptLoginMode) => + invoke("start_chatgpt_login", { name, proxy, mode }), reopenChatgptLogin: (id: string) => invoke("reopen_chatgpt_login", { id }), + /** 把登录码放进剪贴板。码也留在 Rust 侧:界面拿不到一个写剪贴板的口子 */ + copyChatgptCode: (id: string) => invoke("copy_chatgpt_code", { id }), chatgptLoginStatus: (id: string) => invoke("chatgpt_login_status", { id }), cancelChatgptLogin: (id: string) => invoke("cancel_chatgpt_login", { id }), chatgptUsage: (name: string) => invoke("chatgpt_usage", { name }),