Compare commits

..
1 Commits
Author SHA1 Message Date
KimiSwitch Dev 6b761251bc feat(usage): v0.7.6 — OpenCode Go 套餐用量查询(5h/7天/30天三窗口)+ 插件市场入口暂时隐藏(功能保留)
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-18 19:09:54 +08:00
24 changed files with 3353 additions and 77 deletions

No files matched your search

+1 -1
View File
@@ -111,7 +111,7 @@ Rust:
## 三、悬而未决(用户已知情,待决定)
1. **OpenCode Go 账单查询**:已实测全部端点 404(`/zen/go/v1/usages`、`/api/usage`、`/api/billing` 等 12+ 路径),cc-switch 源码也不支持 → **结论:无公开 API,不可查**。文档已记录。
1. **OpenCode Go 账单查询**:~~已实测全部端点 404(`/zen/go/v1/usages`、`/api/usage`、`/api/billing` 等 12+ 路径),cc-switch 源码也不支持 → 结论:无公开 API,不可查~~。**2026-08 推翻**:`GET https://opencode.ai/zen/go/v1/usage`(Bearer + 显式浏览器 UA,否则 Cloudflare 1010 拦截 403)实测 200,已实现为 `plan:opencode_go`(滚动 5h / 周 / 月三窗口)。
2. **Kimi login 配 API key**:可以,代码已支持(api_key 优先于 OAuth)。但 managed 供应商编辑页隐藏 key 输入框(`ProviderEdit.tsx:301` `{!provider.managed && ...}`)。选项:① 用户新建 kimi-coding 预设供应商填 key;② 改 UI 让 managed 显示可选 key 输入。
3. **OAuth refresh**:**已实现**(批次 4)。过期自动用 refresh_token 换新并写回凭据文件;单 flight 锁 + 写回前重读防 CLI 竞态。已知边界:若 access token 未过期但被服务端吊销(罕见),401 不会触发重读重试——暂不处理。
4. **NewAPI 面板自动探测**:打开配置面板时探测 `{base}/api/status` 含 `quota_per_unit` → 自动预选 NewAPI 模板。已提议,未确认。
+25 -13
View File
@@ -8,11 +8,11 @@
## 1. 结论速览
- **KimiSwitch 的账单查询不是空白**:已移植 cc-switch 的「余额查询(Balance)+ 套餐查询(Coding Plan)」两大块,共 **8 种 `usageKinds`**,Rust 侧闭环 + `UsageFooter` 展示,错误通道、keep-last-good、缓存、`detect_provider` 自动识别等核心设计均与 cc-switch 对齐。
- **KimiSwitch 的账单查询不是空白**:已移植 cc-switch 的「余额查询(Balance)+ 套餐查询(Coding Plan)」两大块,共 **11 种 `usageKinds`**,Rust 侧闭环 + `UsageFooter` 展示,错误通道、keep-last-good、缓存、`detect_provider` 自动识别等核心设计均与 cc-switch 对齐。
- **OpenCode 本身不提供账单/额度查询**。它只负责"定义"供应商与订阅套餐的接入方式(provider id、base URL、认证、模型清单,数据源为 models.dev),"套餐还剩下多少"需要查各家官方 API——这正是 cc-switch(及 KimiSwitch 已移植部分)做的事。
- **本次调研发现 2 个值得补的能力缺口**:
- **本次调研发现的能力缺口**:
1. **Kimi 开放平台余额查询**(`GET https://api.moonshot.cn/v1/users/me/balance`,Kimi 官方 2026-07 新增公开 API,cc-switch 尚未实现)→ **KimiSwitch 也缺**。
2. **OpenCode Go 订阅套餐额度**(5h / 周 / 月 三窗口)→ 无公开查询 API,只有控制台,暂不可程序化。
2. **OpenCode Go 订阅套餐额度**(5h / 周 / 月 三窗口)→ 调研时结论为"无公开 API";2026-08 已实测 `GET https://opencode.ai/zen/go/v1/usage`(Bearer)可用并已实现(见 §4.4)。
- 其余缺口(ZenMux / 火山方舟 / 智谱团队版 / JS 脚本引擎 / 官方 OAuth 订阅)为 cc-switch 独有能力,与"做好现有账单查询"的目标匹配度分层,见 §6 路线。
---
@@ -26,7 +26,7 @@ ProviderList (前端)
└─ UsageFooter ── invoke("query_provider_usage", { agent, providerName, forceRefresh })
└─ Rust commands.rs:590 ── services::query_kind(kind, base_url, api_key)
├─ balance.rs (余额,5 家)
└─ coding_plan.rs (套餐,3 家)
└─ coding_plan.rs (套餐,4 家)
```
- 前端**永不持有 API key、不直连 HTTP**;所有请求在 Rust 侧用 reqwest 完成(无浏览器 CORS 问题)。
@@ -45,6 +45,7 @@ ProviderList (前端)
| `plan:kimi_coding` | **Kimi For Coding** | `GET https://api.kimi.com/coding/v1/usages` | Bearer | ✅ |
| `plan:zhipu` | **GLM Coding Plan**(bigmodel.cn / z.ai) | `GET {open.bigmodel.cn\|api.z.ai}/api/monitor/usage/quota/limit` | **Raw key(无 Bearer)** | ✅ |
| `plan:minimax` | MiniMax Token Plan (.com/.io) | `GET https://api.minimaxi.com\|.io/v1/api/openplatform/coding_plan/remains` | Bearer | ✅ |
| `plan:opencode_go` | **OpenCode Go** | `GET https://opencode.ai/zen/go/v1/usage` | Bearer(须带浏览器 UA) | ✅ |
已有预设(`providerPresets.ts`):`kimi-coding`(`plan:kimi_coding`)、`zhipu-coding` / `zai-coding`(`plan:zhipu`)、`minimax` / `minimax-token-plan`(`plan:minimax`)、`deepseek` / `stepfun` / `siliconflow` / `novita` / `openrouter`(余额)。
@@ -54,7 +55,7 @@ ProviderList (前端)
```ts
interface UsageData {
planName?: string | null; // 套餐名:five_hour / weekly_limit
planName?: string | null; // 套餐名:five_hour / weekly_limit / monthly_limit
remaining?: number | null; // 余额:金额(balance)或剩余百分比(plan)
total?: number | null; // 总量(plan 恒为 100)
used?: number | null; // 已用百分比 0-100(plan)
@@ -101,7 +102,7 @@ OpenCode(sst/opencode)通过 `~/.config/opencode/opencode.json` 的 `provide
额度按美元计费价值计算(不同模型折算请求数不同)。超出限额后可选"Use balance"回退到 Zen 余额。
**查询方式:仅控制台(console),无公开 REST API**。OpenCode 项目本身不做用量查询(无 usage/billing 命令),社区工具(如 cc-switch 的 `usage_script`)也无法覆盖 Go 套餐——这是目前的技术边界,适配时只能提示用户"网页控制台查看"或把 Go 归入"不可查询"类。
**查询方式(✅ 已实现)**:`GET https://opencode.ai/zen/go/v1/usage`,`Authorization: Bearer <api_key>`,无 query 参数。响应含 `usage.rolling / usage.weekly / usage.monthly` 三窗口,每窗口 `status / percent / resetsAt`(`percent` = 已用百分比)。2026-08 实测可用;注意该站有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的裸请求会被 403,请求必须显式携带浏览器 UA(见 §4.4)。
### 3.3 OpenCode 定义 → KimiSwitch 预设的对应关系
@@ -112,8 +113,8 @@ KimiSwitch 的 `providerPresets.ts` 已镜像这套体系(`baseUrl` 与 OpenCo
| `kimi-coding` | `https://api.kimi.com/coding/v1` | subscription | `plan:kimi_coding` | ✅ 可查套餐 |
| `zhipu-coding` | `https://open.bigmodel.cn/api/coding/paas/v4` | subscription | `plan:zhipu` | ✅ 可查套餐 |
| `zai-coding` | `https://api.z.ai/api/coding/paas/v4` | subscription | `plan:zhipu` | ✅ 可查套餐 |
| `opencode-go` | `https://opencode.ai/zen/go/v1` | subscription | **(空)** | ❌ 不可查,见 §4.4 |
| `opencode-zen` | `https://opencode.ai/zen/v1` | pay_as_you_go | **(空)** | ❌ 不可查 |
| `opencode-go` | `https://opencode.ai/zen/go/v1` | subscription | `plan:opencode_go` | ✅ 可查套餐,见 §4.4 |
| `opencode-zen` | `https://opencode.ai/zen/v1` | pay_as_you_go | **(空)** | ❌ 不可查(按量,无公开余额 API) |
| `moonshot` | `https://api.moonshot.ai/v1` | pay_as_you_go | **(空)** | ❌ 未挂余额查询,见 §4.3 |
---
@@ -185,12 +186,23 @@ KimiSwitch 的 `providerPresets.ts` 已镜像这套体系(`baseUrl` 与 OpenCo
- **适配点**:`moonshot` 预设 baseUrl 为 `https://api.moonshot.ai/v1`(国际站),而该端点固定 `api.moonshot.cn`(国内站)。需按 base_url 消歧:host 含 `moonshot.cn` → 查 CN 端点;`moonshot.ai` → 查 `https://api.moonshot.ai/v1/users/me/balance`(国际站对应端点,待实测确认;官方文档仅给出 CN 示例)。
- 新增 `balance:kimi` kind 即可复用现有 balance 路径,前端 `UsageFooter` 自动生效(余额形态显示 `💰 余额 ¥49.59`)。
### 4.4 OpenCode Go / Zen(❌ 未实现 —— 无公开 API,建议标注"不可查")
### 4.4 OpenCode Go / Zen(✅ Go 已实现 —— `plan:opencode_go`)
- **Go 套餐**:额度窗口见 §3.2,仅控制台可看;`opencode.ai/zen/go/v1` 只有推理端点(`/chat/completions`、`/responses`、`/models`),**无 usage/balance 端点**。
- **Zen 余额**:充值制,同样仅控制台。
- **可选替代(不推荐投入)**:通过调用推理端点时服务端返回的 402/429/额度错误头做被动感知,无法拿到数值,价值低。
- **适配结论**:`opencode-go` / `opencode-zen` 预设维持 `usageKinds` 为空;可在预设 `note`/UI 上提示"额度请在 opencode.ai 控制台查看"。
- **Go 套餐(✅ 已实现)**:端点 `GET https://opencode.ai/zen/go/v1/usage`,`Authorization: Bearer <api_key>`,无 query 参数。响应:
```json
{
"usage": {
"rolling": { "status": "ok", "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "status": "ok", "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "status": "ok", "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
}
```
三窗口各解析为一条 `percent_tier`(`percent` = 已用百分比,映射 five_hour / weekly_limit / monthly_limit,前端 `planLabel` 已本地化);`status` 为展示字段,缺失容忍;单窗口缺失只出其余窗口。
- **坑位(实测)**:opencode.ai 有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的裸请求会被 403(`error code: 1010`),请求必须显式设置浏览器 UA(`coding_plan.rs::BROWSER_USER_AGENT`,经 `get_json_with_ua` 注入)。
- **Zen 余额**:充值制,仍仅控制台,未实现;`opencode-zen` 预设维持 `usageKinds` 为空。
### 4.5 其他 cc-switch 独有、KimiSwitch 未移植的能力(按目标匹配度排序)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kimiswitch",
"version": "0.7.5",
"version": "0.7.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kimiswitch",
"version": "0.7.5",
"version": "0.7.6",
"dependencies": {
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-opener": "^2.5.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "kimiswitch",
"private": true,
"version": "0.7.5",
"version": "0.7.6",
"type": "module",
"scripts": {
"dev": "vite",
+30
View File
@@ -0,0 +1,30 @@
## v0.7.6
### OpenCode Go 套餐用量查询
- 新增 **OpenCode Go 套餐额度查询**:供应商卡片用量页脚显示 **5 小时滚动 / 7 天 / 30 天** 三个窗口的已用百分比与重置时间(数据源为 opencode.ai 官方 usage API)
- 数据源:`GET https://opencode.ai/zen/go/v1/usage`(Bearer 认证),直接解析官方 `rolling / weekly / monthly` 三窗口的 `percent` 与 `resetsAt`
- **老配置自动适配**:已配置 OpenCode Go API Key 的现有用户无需任何手动设置,程序按 `base_url` 自动识别并启用用量查询
- 兼容处理:已适配 opencode.ai 的 Cloudflare 拦截(请求携带浏览器 User-Agent),并对外部接口失败给出可读的错误提示
### 插件目录占用错误提示优化
- 插件目录被运行中进程占用时的错误提示给出明确指引(底层改进)
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` + `.app`(未签名,仅 Apple Silicon / M 系列芯片)
- **Linux**: `.deb` / `.AppImage` / `.rpm`
### macOS 安装说明(无开发者账号签名,需一次手动绕过)
1. 下载 `Kimi.Switch_*.dmg`,双击挂载后把 `Kimi Switch.app` 拖入「应用程序」文件夹
2. 下载本 Release 附带的 `install-macos.sh`,在终端运行:
```bash
bash install-macos.sh
```
脚本会自动清除下载隔离属性并启动应用,只需执行一次,之后正常使用。
3. 手动替代方案:右键 `Kimi Switch.app` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+52 -1
View File
@@ -59,6 +59,15 @@ version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -710,6 +719,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -1958,7 +1978,7 @@ dependencies = [
[[package]]
name = "kimiswitch"
version = "0.7.5"
version = "0.7.6"
dependencies = [
"anyhow",
"chrono",
@@ -1975,9 +1995,11 @@ dependencies = [
"tauri-build",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tempfile",
"tokio",
"toml 0.8.23",
"walkdir",
"zip",
]
[[package]]
@@ -5484,12 +5506,41 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "zip"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
dependencies = [
"arbitrary",
"crc32fast",
"crossbeam-utils",
"displaydoc",
"flate2",
"indexmap 2.14.0",
"memchr",
"thiserror 2.0.18",
"zopfli",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zvariant"
version = "5.12.0"
+8 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "kimiswitch"
version = "0.7.5"
version = "0.7.6"
description = "Kimi Switch - model config manager"
authors = ["codingplan.site"]
edition = "2021"
@@ -25,7 +25,13 @@ futures-util = "0.3"
dirs = "5.0"
toml = "0.8"
rusqlite = { version = "0.32", features = ["bundled", "chrono"] }
tokio = { version = "1", features = ["sync"] }
tokio = { version = "1", features = ["sync", "fs", "io-util"] }
# Plugin marketplace: zip extraction (deflate-only; no extra compression
# backends needed for plugin archives).
zip = { version = "2", default-features = false, features = ["deflate"] }
[dev-dependencies]
tempfile = "3"
[lib]
name = "kimiswitch_lib"
+4 -1
View File
@@ -345,7 +345,10 @@ pub struct UsageRecord {
// Helpers
// ---------------------------------------------------------------------------
fn resolve_kimi_home(override_path: Option<String>) -> PathBuf {
/// Resolve the Kimi Code home directory: explicit override, then
/// `KIMI_CODE_HOME`, then the default `~/.kimi-code`. Shared with the plugin
/// marketplace module (`crate::plugins`).
pub(crate) fn resolve_kimi_home(override_path: Option<String>) -> PathBuf {
if let Some(p) = override_path {
if !p.trim().is_empty() {
return PathBuf::from(p);
+6
View File
@@ -6,6 +6,7 @@ pub mod kimi_code_io;
pub mod models;
pub mod oauth;
pub mod pi_io;
pub mod plugins;
pub mod services;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
@@ -124,6 +125,11 @@ pub fn run() {
dashboard::delete_session,
dashboard::delete_workspace,
dashboard::get_session_preview,
plugins::get_plugin_marketplace,
plugins::list_installed_plugins,
plugins::install_plugin,
plugins::set_plugin_enabled,
plugins::remove_plugin,
])
.manage(commands::KimiWebState::default())
.build(tauri::generate_context!())
File diff suppressed because it is too large. Load diff
+23 -4
View File
@@ -37,16 +37,35 @@ pub(crate) enum Fetched {
///
/// 先 `bytes()` 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
/// 后解析失败才是确定性。reqwest 的 `.json()` 把读体错误也包成 decode,无法区分。
///
/// 默认不带 User-Agent;需要自定义 UA 的供应商(如 opencode.ai 有 Cloudflare
/// 1010 拦截,必须带浏览器 UA)走 [`get_json_with_ua`]。
pub(crate) async fn get_json(
url: &str,
api_key: &str,
auth: AuthStyle,
timeout: Duration,
) -> Result<Fetched, String> {
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| format!("Failed to build HTTP client: {e}"))?;
get_json_with_ua(url, api_key, auth, timeout, None).await
}
/// [`get_json`] 的 UA 变体:`user_agent` 为 `Some` 时设到 client 上。
/// 仅新增链路需要,现有调用方不受影响。
pub(crate) async fn get_json_with_ua(
url: &str,
api_key: &str,
auth: AuthStyle,
timeout: Duration,
user_agent: Option<&str>,
) -> Result<Fetched, String> {
let mut builder = reqwest::Client::builder().timeout(timeout);
if let Some(ua) = user_agent {
builder = builder.user_agent(ua);
}
let client = match builder.build() {
Ok(c) => c,
Err(e) => return Err(format!("Failed to build HTTP client: {e}")),
};
// 注意:api_key 只允许进请求头,严禁拼进 URL / 日志 / 错误信息。
let req = client.get(url).header("Accept", "application/json");
+155 -6
View File
@@ -3,23 +3,24 @@
//! Token Plan 套餐额度查询服务
//!
//! 支持 Kimi For Coding、智谱 GLM、MiniMax 的套餐额度查询。
//! 支持 Kimi For Coding、智谱 GLM、MiniMax、OpenCode Go 的套餐额度查询。
//! cc-switch 的 SubscriptionQuota/tiers 结构在此展平为 `Vec<UsageData>`:
//! 每个窗口(tier)一条 UsageData,`plan_name` = tier 名("five_hour" /
//! "weekly_limit"),`used` = 已用百分比(0-100),`total` = 100,
//! "weekly_limit" / "monthly_limit"),`used` = 已用百分比(0-100),`total` = 100,
//! `remaining` = 剩余百分比,`resets_at` 为 ISO 8601 字符串。
//!
//! 错误通道语义与 balance.rs 一致(Err = 瞬时,Ok(success:false) = 确定性)。
use super::balance::{get_json, AuthStyle, Fetched};
use super::balance::{get_json, get_json_with_ua, AuthStyle, Fetched};
use super::usage_types::{UsageData, UsageResult};
use std::time::Duration;
// 套餐类 tier id 的唯一来源:所有套餐供应商(Kimi/智谱/MiniMax 及未来新增)
// 都只用这两个 id。前端 src/lib/usage-display.ts 的 planLabel() 依赖此约定
// 做本地化映射——新增 tier id 时必须同步加映射。
// 套餐类 tier id 的唯一来源:所有套餐供应商(Kimi/智谱/MiniMax/OpenCode Go 及
// 未来新增)都只用这三个 id。前端 src/lib/usage-display.ts 的 planLabel() 依赖
// 此约定做本地化映射——新增 tier id 时必须同步加映射。
const TIER_FIVE_HOUR: &str = "five_hour";
const TIER_WEEKLY_LIMIT: &str = "weekly_limit";
const TIER_MONTHLY_LIMIT: &str = "monthly_limit";
/// 套餐条目的统一构造:按百分比表示用量。
fn percent_tier(name: &str, used_percent: f64, resets_at: Option<String>) -> UsageData {
@@ -315,6 +316,81 @@ fn parse_minimax(body: &serde_json::Value) -> Result<Vec<UsageData>, UsageResult
Ok(tiers)
}
// ── OpenCode Go ─────────────────────────────────────────────
// GET https://opencode.ai/zen/go/v1/usage
// Response: { usage: { rolling: { status, percent, resetsAt },
// weekly: { status, percent, resetsAt },
// monthly: { status, percent, resetsAt } } }
// percent = 已用百分比(与 percent_tier 语义一致);status 仅作展示参考,缺失容忍;
// resetsAt 为 ISO 8601 字符串。
//
// 坑位:opencode.ai 有 Cloudflare 1010 拦截——reqwest 默认不带 User-Agent 的
// 裸请求会被 403(error code: 1010)。必须显式设置浏览器 UA。
const BROWSER_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
pub async fn query_opencode_go(
api_key: &str,
timeout: Duration,
) -> Result<UsageResult, String> {
match get_json_with_ua(
"https://opencode.ai/zen/go/v1/usage",
api_key,
AuthStyle::Bearer,
timeout,
Some(BROWSER_USER_AGENT),
)
.await?
{
Fetched::Body(body) => {
let tiers = parse_opencode_go(&body);
if tiers.is_empty() {
// 响应里没有可解析的用量窗口(usage 缺失或字段变了)。
// 把原始响应(仅用量数字,无密钥)透出,方便对照接口结构修复。
return Ok(opencode_go_empty_failure(&body));
}
Ok(UsageResult::ok(tiers))
}
Fetched::Failed(err) => Ok(err),
}
}
/// usage 全缺时的确定性失败,附 400 字原始响应预览。抽成纯函数便于离线单测。
fn opencode_go_empty_failure(body: &serde_json::Value) -> UsageResult {
let preview = serde_json::to_string(body)
.unwrap_or_else(|_| "<unserializable body>".into());
let trimmed: String = preview.chars().take(400).collect();
UsageResult::failure(format!(
"opencode go usage 响应无套餐数据,原始返回: {trimmed}"
))
}
/// 三个窗口(5 小时滚动 / 周 / 月)各解析为一条 `percent_tier`;
/// 缺失或 percent 不可解析的窗口跳过(status 字段可缺)。
fn parse_opencode_go(body: &serde_json::Value) -> Vec<UsageData> {
let mut tiers = Vec::new();
let Some(usage) = body.get("usage") else {
return tiers;
};
let windows = [
(TIER_FIVE_HOUR, "rolling"),
(TIER_WEEKLY_LIMIT, "weekly"),
(TIER_MONTHLY_LIMIT, "monthly"),
];
for (name, key) in windows {
let Some(window) = usage.get(key) else {
continue;
};
let Some(percent) = window.get("percent").and_then(parse_f64) else {
continue;
};
let resets_at = window.get("resetsAt").and_then(extract_reset_time);
tiers.push(percent_tier(name, percent, resets_at));
}
tiers
}
#[cfg(test)]
mod tests {
use super::*;
@@ -429,4 +505,77 @@ mod tests {
assert!(!err.success);
assert!(err.error.unwrap().contains("invalid key"));
}
#[test]
fn opencode_go_parses_three_windows() {
// 真实 key 实测样例(2026-08):percent 为已用百分比,直接透传
let body = json!({
"usage": {
"rolling": { "status": "ok", "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "status": "ok", "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "status": "ok", "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 3);
assert_eq!(tiers[0].plan_name.as_deref(), Some("five_hour"));
assert_eq!(tiers[0].used, Some(9.0));
assert_eq!(tiers[0].total, Some(100.0));
assert_eq!(tiers[0].remaining, Some(91.0));
assert_eq!(
tiers[0].resets_at.as_deref(),
Some("2026-08-18T06:09:19.735Z")
);
assert_eq!(tiers[1].plan_name.as_deref(), Some("weekly_limit"));
assert_eq!(tiers[1].used, Some(5.0));
assert_eq!(tiers[1].remaining, Some(95.0));
assert_eq!(tiers[2].plan_name.as_deref(), Some("monthly_limit"));
assert_eq!(tiers[2].used, Some(59.0));
assert_eq!(tiers[2].remaining, Some(41.0));
}
#[test]
fn opencode_go_tolerates_missing_status_field() {
// status 属展示字段,缺失照常解析(percent/resetsAt 都只要求本身存在)
let body = json!({
"usage": {
"rolling": { "percent": 9, "resetsAt": "2026-08-18T06:09:19.735Z" },
"weekly": { "percent": 5, "resetsAt": "2026-08-24T00:00:00.735Z" },
"monthly": { "percent": 59, "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 3);
assert_eq!(tiers[1].plan_name.as_deref(), Some("weekly_limit"));
assert_eq!(tiers[2].used, Some(59.0));
}
#[test]
fn opencode_go_partial_windows_only_emit_present_ones() {
// 单窗口缺失只出两条;percent 缺失 / 非数字的窗口整窗跳过
let body = json!({
"usage": {
"rolling": { "status": "ok", "percent": "9", "resetsAt": "2026-08-18T06:09:19.735Z" },
"monthly": { "status": "ok", "resetsAt": "2026-08-27T03:33:50.735Z" }
}
});
let tiers = parse_opencode_go(&body);
assert_eq!(tiers.len(), 1);
// percent 以字符串给出也兼容(parse_f64)
assert_eq!(tiers[0].plan_name.as_deref(), Some("five_hour"));
assert_eq!(tiers[0].used, Some(9.0));
}
#[test]
fn opencode_go_missing_usage_is_deterministic_failure_with_preview() {
// usage 全缺:确定性失败,附原始响应预览(400 字内,无密钥)
let body = json!({ "error": { "message": "boom" } });
assert!(parse_opencode_go(&body).is_empty());
let err = opencode_go_empty_failure(&body);
assert!(!err.success);
assert!(err.data.is_none());
let msg = err.error.unwrap();
assert!(msg.contains("原始返回"), "msg: {msg}");
assert!(msg.contains(r#""message":"boom""#), "msg: {msg}");
}
}
+29 -3
View File
@@ -3,7 +3,7 @@
//! 供应商账单/用量查询统一入口。
//!
//! - [`UsageKind`]:8 种查询类型,字符串形式与前端 / SQLite settings 约定一致
//! - [`UsageKind`]:11 种查询类型,字符串形式与前端 / SQLite settings 约定一致
//! (如 `"balance:deepseek"`、`"plan:kimi_coding"`)。
//! - [`detect_provider`]:按 base_url host 子串匹配,旧用户无显式配置时自动识别。
//! - [`query_kind`]:按 kind 路由到 balance / coding_plan 的具体实现。
@@ -26,6 +26,7 @@ pub enum UsageKind {
PlanKimiCoding,
PlanZhipu,
PlanMinimax,
PlanOpencodeGo,
}
impl UsageKind {
@@ -42,10 +43,11 @@ impl UsageKind {
UsageKind::PlanKimiCoding => "plan:kimi_coding",
UsageKind::PlanZhipu => "plan:zhipu",
UsageKind::PlanMinimax => "plan:minimax",
UsageKind::PlanOpencodeGo => "plan:opencode_go",
}
}
pub const ALL: [UsageKind; 10] = [
pub const ALL: [UsageKind; 11] = [
UsageKind::BalanceDeepseek,
UsageKind::BalanceSiliconflow,
UsageKind::BalanceOpenrouter,
@@ -56,6 +58,7 @@ impl UsageKind {
UsageKind::PlanKimiCoding,
UsageKind::PlanZhipu,
UsageKind::PlanMinimax,
UsageKind::PlanOpencodeGo,
];
}
@@ -74,6 +77,7 @@ impl std::str::FromStr for UsageKind {
"plan:kimi_coding" => UsageKind::PlanKimiCoding,
"plan:zhipu" => UsageKind::PlanZhipu,
"plan:minimax" => UsageKind::PlanMinimax,
"plan:opencode_go" => UsageKind::PlanOpencodeGo,
_ => return Err(()),
})
}
@@ -113,6 +117,10 @@ pub fn detect_provider(base_url: &str) -> Vec<UsageKind> {
if url.contains("api.minimaxi.com") {
kinds.push(UsageKind::PlanMinimax);
}
// OpenCode Go 套餐:只认 /zen/go 路径;/zen/v1(OpenCode Zen 按量付费)不得命中。
if url.contains("/zen/go") {
kinds.push(UsageKind::PlanOpencodeGo);
}
kinds
}
@@ -166,6 +174,7 @@ pub async fn query_kind(
UsageKind::PlanMinimax => {
coding_plan::query_minimax(api_key, !lower.contains("minimax.io"), timeout).await
}
UsageKind::PlanOpencodeGo => coding_plan::query_opencode_go(api_key, timeout).await,
}
}
@@ -175,7 +184,7 @@ mod tests {
#[test]
fn detect_provider_maps_known_hosts() {
let cases: [(&str, UsageKind); 9] = [
let cases: [(&str, UsageKind); 10] = [
("https://api.deepseek.com/v1", UsageKind::BalanceDeepseek),
("https://api.siliconflow.cn/v1", UsageKind::BalanceSiliconflow),
("https://openrouter.ai/api/v1", UsageKind::BalanceOpenrouter),
@@ -188,6 +197,7 @@ mod tests {
UsageKind::PlanZhipu,
),
("https://api.minimaxi.com/v1", UsageKind::PlanMinimax),
("https://opencode.ai/zen/go/v1", UsageKind::PlanOpencodeGo),
];
for (url, expected) in cases {
assert_eq!(
@@ -212,6 +222,22 @@ mod tests {
assert!(detect_provider("https://api.kimi.com/v1").is_empty());
}
#[test]
fn detect_provider_opencode_go_excludes_payg_zen() {
// /zen/go 命中套餐查询
assert_eq!(
detect_provider("https://opencode.ai/zen/go/v1"),
vec![UsageKind::PlanOpencodeGo]
);
// /zen/v1(OpenCode Zen 按量付费)不得命中
assert!(detect_provider("https://opencode.ai/zen/v1").is_empty());
// 裸域名也命中(go 套餐 base 无 v1 后缀时)
assert_eq!(
detect_provider("https://opencode.ai/zen/go"),
vec![UsageKind::PlanOpencodeGo]
);
}
#[test]
fn usage_kind_string_roundtrip() {
use std::str::FromStr;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"productName": "Kimi Switch",
"version": "0.7.5",
"version": "0.7.6",
"identifier": "com.kimiswitch.app",
"build": {
"beforeDevCommand": "npm run dev",
+15 -2
View File
@@ -8,6 +8,7 @@ import { ProviderEdit } from "./components/ProviderEdit";
import { SubagentSettingsPage } from "./components/SubagentSettingsPage";
import { DashboardPage } from "./components/dashboard/DashboardPage";
import { SessionsPage } from "./components/sessions/SessionsPage";
import { PluginMarketplacePage } from "./components/plugins/PluginMarketplacePage";
import { SettingsModal } from "./components/SettingsModal";
import { UsageConfigModal } from "./components/UsageConfigModal";
import { PresetPickerModal } from "./components/PresetPickerModal";
@@ -71,7 +72,9 @@ export default function App() {
updateConfig,
} = useConfig(agent);
const [view, setView] = useState<"list" | "edit" | "subagent" | "dashboard" | "sessions">("list");
const [view, setView] = useState<
"list" | "edit" | "subagent" | "dashboard" | "sessions" | "plugins"
>("list");
const [editingProvider, setEditingProvider] = useState<string>("");
const [loadTimeout, setLoadTimeout] = useState(false);
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
@@ -603,6 +606,14 @@ export default function App() {
>
{t("sessions")}
</button>
{/* 插件市场功能尚未成熟,导航入口暂时隐藏;页面代码保留,
恢复时把下面的按钮加回即可(view/渲染分支均未移除)。
<button
type="button"
onClick={() => setView("plugins")}
...
</button>
*/}
</div>
<div className="flex items-center gap-2">
{/* Language */}
@@ -650,6 +661,8 @@ export default function App() {
<DashboardPage />
) : view === "sessions" ? (
<SessionsPage />
) : view === "plugins" ? (
<PluginMarketplacePage />
) : view === "subagent" ? (
<SubagentSettingsPage
rawOther={config.raw_other}
@@ -777,7 +790,7 @@ export default function App() {
)}
</main>
{view !== "dashboard" && view !== "sessions" && (
{view !== "dashboard" && view !== "sessions" && view !== "plugins" && (
<footer className="flex items-center justify-between px-4 py-2 border-t border-border bg-panel text-sm">
<div className="flex items-center gap-2 min-w-0">
{dirty && (
@@ -0,0 +1,578 @@
import { useMemo, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { useTranslation } from "../../i18n";
import type { TranslationKey } from "../../i18n/zh";
import { fmtTime } from "../../lib/dashboard-format";
import type { InstalledPluginInfo } from "../../types";
import { usePlugins } from "./usePlugins";
/**
* Plugin marketplace page. Sections:
* 已安装 (installed, incl. non-marketplace "自定义安装" entries),
* 官方 (tier === "official"), 社区 (any other tier).
* Catalog failures fall back to the local installed list; cached catalog
* responses surface a yellow banner (fromCache + fetchedAt).
*/
export function PluginMarketplacePage() {
const { t, lang } = useTranslation();
const locale = lang === "zh" ? "zh" : "en";
const {
catalog,
installed,
catalogLoading,
installedLoading,
catalogError,
installedError,
loadCatalog,
loadInstalled,
installPlugin,
setPluginEnabled,
removePlugin,
} = usePlugins();
const [query, setQuery] = useState("");
const [busy, setBusy] = useState<{ id: string; action: PluginAction } | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [notice, setNotice] = useState<{ kind: PluginNoticeKind; name: string } | null>(null);
const [copiedReload, setCopiedReload] = useState(false);
const [trustEntry, setTrustEntry] = useState<PluginCard | null>(null);
const [removeEntry, setRemoveEntry] = useState<PluginCard | null>(null);
const [confirmBusy, setConfirmBusy] = useState(false);
// Fresh installed state wins over the (possibly stale) catalog snapshot.
const installedById = useMemo(
() => new Map(installed.map((i) => [i.id, i])),
[installed]
);
const catalogCards = useMemo<PluginCard[]>(() => {
return (catalog?.entries ?? []).map((e) => {
const fresh = installedById.get(e.id) ?? null;
return {
id: e.id,
displayName: e.displayName,
version: (fresh ?? e.installed)?.version ?? e.version,
description: e.description,
keywords: e.keywords,
homepage: e.homepage,
tier: e.tier,
source: e.source,
capabilityId: e.capabilityId,
updateAvailable: e.updateAvailable,
installed: fresh ?? e.installed,
customInstall: false,
};
});
}, [catalog, installedById]);
// Installed plugins with no catalog entry (catalog failed, or a manual
// install) are shown in the installed section from the local list.
const fallbackCards = useMemo<PluginCard[]>(
() =>
installed
.filter((i) => !catalogCards.some((c) => c.id === i.id))
.map((i) => ({
id: i.id,
displayName: i.id,
version: i.version,
description: null,
keywords: [],
homepage: null,
tier: i.isMarketplace ? "unknown" : "custom",
source: i.source,
capabilityId: null,
updateAvailable: false,
installed: i,
customInstall: !i.isMarketplace,
})),
[installed, catalogCards]
);
const q = query.trim().toLowerCase();
const matchesQuery = (c: PluginCard) =>
q === "" ||
c.displayName.toLowerCase().includes(q) ||
c.id.toLowerCase().includes(q) ||
(c.description ?? "").toLowerCase().includes(q) ||
c.keywords.some((k) => k.toLowerCase().includes(q));
const installedCards = useMemo(
() => [...catalogCards.filter((c) => c.installed), ...fallbackCards].filter(matchesQuery),
[catalogCards, fallbackCards, q]
);
const officialCards = useMemo(
() => catalogCards.filter((c) => !c.installed && c.tier === "official" && matchesQuery(c)),
[catalogCards, q]
);
const communityCards = useMemo(
() => catalogCards.filter((c) => !c.installed && c.tier !== "official" && matchesQuery(c)),
[catalogCards, q]
);
const initialLoading =
(catalogLoading || installedLoading) && !catalog && installed.length === 0;
const copyReload = async () => {
try {
await navigator.clipboard.writeText("/reload");
setCopiedReload(true);
setTimeout(() => setCopiedReload(false), 2000);
} catch {
// Clipboard may be unavailable; ignore silently.
}
};
/** Shared post-mutation refresh: local list is cheap, catalog force-fetch
* brings fresh updateAvailable / installed flags. */
const afterMutation = async () => {
await loadInstalled();
await loadCatalog(true);
};
const doInstall = async (card: PluginCard) => {
const isUpdate = card.updateAvailable;
setBusy({ id: card.id, action: isUpdate ? "update" : "install" });
setActionError(null);
try {
await installPlugin(card.source, card.id);
setNotice({ kind: isUpdate ? "updated" : "installed", name: card.displayName });
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(null);
}
};
const handleInstall = (card: PluginCard) => {
if (card.capabilityId) return;
if (card.tier !== "official") {
// Third-party plugin: require explicit trust confirmation first.
setTrustEntry(card);
return;
}
void doInstall(card);
};
const confirmTrust = async () => {
if (!trustEntry) return;
setConfirmBusy(true);
try {
await doInstall(trustEntry);
setTrustEntry(null);
} finally {
setConfirmBusy(false);
}
};
const handleToggle = async (card: PluginCard) => {
if (!card.installed) return;
const enabled = !card.installed.enabled;
setBusy({ id: card.id, action: enabled ? "enable" : "disable" });
setActionError(null);
try {
await setPluginEnabled(card.id, enabled);
setNotice({ kind: enabled ? "enabled" : "disabled", name: card.displayName });
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(null);
}
};
const confirmRemove = async () => {
if (!removeEntry) return;
setConfirmBusy(true);
try {
await removePlugin(removeEntry.id);
setNotice({ kind: "removed", name: removeEntry.displayName });
setRemoveEntry(null);
await afterMutation();
} catch (err) {
setActionError(err instanceof Error ? err.message : String(err));
setRemoveEntry(null);
} finally {
setConfirmBusy(false);
}
};
const sectionData = [
{ key: "installed", title: t("pluginSectionInstalled"), cards: installedCards },
{ key: "official", title: t("pluginSectionOfficial"), cards: officialCards },
{ key: "community", title: t("pluginSectionCommunity"), cards: communityCards },
].filter((s) => s.cards.length > 0);
const showEmpty =
!initialLoading && !catalogError && !installedError && sectionData.length === 0;
return (
<div className="flex h-full flex-col overflow-hidden p-4 space-y-3">
<div className="flex shrink-0 flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 className="text-lg font-semibold text-content-primary">{t("pluginMarketplace")}</h2>
<p className="mt-1 max-w-[60ch] text-sm text-content-muted">{t("pluginMarketplaceSubtitle")}</p>
</div>
<div className="flex items-center gap-2">
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t("pluginSearchPlaceholder")}
aria-label={t("pluginSearchPlaceholder")}
className="w-56 bg-input border border-border rounded px-2.5 py-1.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none sm:w-64"
/>
<button
type="button"
onClick={() => void loadCatalog(true)}
disabled={catalogLoading}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{catalogLoading ? t("refreshing") : t("refresh")}
</button>
</div>
</div>
{catalogError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="font-semibold">{t("pluginCatalogFailed")}</div>
<div className="mt-0.5 break-all opacity-90">{catalogError}</div>
</div>
)}
{installedError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="font-semibold">{t("pluginInstalledListFailed")}</div>
<div className="mt-0.5 break-all opacity-90">{installedError}</div>
</div>
)}
{actionError && (
<div className="shrink-0 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-300">
<div className="break-all">{actionError}</div>
</div>
)}
{catalog?.fromCache && (
<div className="shrink-0 rounded-lg border border-amber-500/40 bg-amber-900/20 px-4 py-2.5 text-sm text-amber-300">
{t("pluginCacheNotice", { time: fmtTime(parseTime(catalog.fetchedAt), locale) })}
</div>
)}
{notice && (
<div className="flex shrink-0 items-center justify-between gap-3 rounded-lg border border-green-300 dark:border-green-500/20 bg-green-100 dark:bg-green-900/20 px-4 py-2.5 text-sm text-green-600 dark:text-green-400">
<span>{t(NOTICE_KEYS[notice.kind], { name: notice.name })}</span>
<button
type="button"
onClick={copyReload}
className="shrink-0 px-2.5 py-1 text-xs rounded border border-green-400/50 hover:bg-green-900/20"
>
{copiedReload ? t("pluginReloadCopied") : t("pluginCopyReload")}
</button>
</div>
)}
{initialLoading ? (
<div className="flex min-h-0 flex-1 items-center justify-center">
<div className="animate-spin h-8 w-8 border-2 border-blue-500 border-t-transparent rounded-full" />
</div>
) : (
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto">
{sectionData.map((section) => (
<section key={section.key}>
<h3 className="mb-2 flex items-center gap-2 text-sm font-medium text-content-primary">
{section.title}
<span className="rounded border border-border bg-input px-1.5 py-0 text-[10px] text-content-muted tabular-nums">
{section.cards.length}
</span>
</h3>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
{section.cards.map((card) => (
<PluginCardView
key={`${section.key}:${card.id}`}
card={card}
busy={busy?.id === card.id ? busy.action : null}
onInstall={handleInstall}
onUpdate={doInstall}
onToggle={(c) => void handleToggle(c)}
onRemove={setRemoveEntry}
/>
))}
</div>
</section>
))}
{showEmpty && (
<div className="py-16 text-center text-sm text-content-muted">
{q ? t("pluginEmptyResults") : t("pluginNoPlugins")}
</div>
)}
</div>
)}
{/* Third-party trust confirm */}
{trustEntry && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="w-full max-w-md rounded-xl border border-border bg-panel shadow-xl">
<div className="space-y-3 p-5">
<h3 className="text-base font-semibold text-content-primary">{t("pluginTrustTitle")}</h3>
<p className="text-sm text-content-muted">
{t("pluginTrustDesc", { source: trustEntry.source })}
</p>
<div className="rounded-md border border-border bg-input px-3 py-2.5">
<div className="truncate text-sm font-medium">{trustEntry.displayName}</div>
<div className="mt-1 break-all font-mono text-[11px] text-content-muted">
{trustEntry.source}
</div>
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border bg-footer px-5 py-3">
<button
type="button"
disabled={confirmBusy}
onClick={() => setTrustEntry(null)}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{t("cancel")}
</button>
<button
type="button"
disabled={confirmBusy}
onClick={() => void confirmTrust()}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
{confirmBusy ? t("pluginInstalling") : t("pluginTrustInstall")}
</button>
</div>
</div>
</div>
)}
{/* Remove confirm */}
{removeEntry && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="w-full max-w-md rounded-xl border border-border bg-panel shadow-xl">
<div className="space-y-3 p-5">
<h3 className="text-base font-semibold text-content-primary">{t("pluginRemoveTitle")}</h3>
<p className="text-sm text-content-muted">
{t("pluginRemoveConfirm", { name: removeEntry.displayName })}
</p>
<div className="rounded-md border border-border bg-input px-3 py-2.5">
<div className="truncate text-sm font-medium">{removeEntry.displayName}</div>
<div className="mt-1 break-all font-mono text-[11px] text-content-muted">
{removeEntry.id}
</div>
</div>
</div>
<div className="flex justify-end gap-2 border-t border-border bg-footer px-5 py-3">
<button
type="button"
disabled={confirmBusy}
onClick={() => setRemoveEntry(null)}
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{t("cancel")}
</button>
<button
type="button"
disabled={confirmBusy}
onClick={() => void confirmRemove()}
className="px-3 py-1.5 text-sm rounded bg-red-600 text-white hover:bg-red-500 disabled:opacity-50"
>
{confirmBusy ? t("pluginRemoving") : t("pluginRemove")}
</button>
</div>
</div>
</div>
)}
</div>
);
}
type PluginAction = "install" | "update" | "enable" | "disable" | "remove";
type PluginNoticeKind = "installed" | "updated" | "enabled" | "disabled" | "removed";
const NOTICE_KEYS: Record<PluginNoticeKind, TranslationKey> = {
installed: "pluginInstalledMsg",
updated: "pluginUpdatedMsg",
enabled: "pluginEnabledMsg",
disabled: "pluginDisabledMsg",
removed: "pluginRemovedMsg",
};
/** Normalized card data: catalog metadata merged with fresh installed state. */
interface PluginCard {
id: string;
displayName: string;
version: string | null;
description: string | null;
keywords: string[];
homepage: string | null;
tier: string;
source: string;
capabilityId: string | null;
updateAvailable: boolean;
installed: InstalledPluginInfo | null;
/** Card synthesized from the local installed list (not in the catalog). */
customInstall: boolean;
}
function parseTime(value: string | null | undefined): number {
if (value == null || value === "") return 0;
const ms = Date.parse(value);
return Number.isFinite(ms) ? ms : 0;
}
function PluginCardView({
card,
busy,
onInstall,
onUpdate,
onToggle,
onRemove,
}: {
card: PluginCard;
busy: PluginAction | null;
onInstall: (card: PluginCard) => void;
onUpdate: (card: PluginCard) => void;
onToggle: (card: PluginCard) => void;
onRemove: (card: PluginCard) => void;
}) {
const { t } = useTranslation();
const { installed } = card;
const busyLabel =
busy === "install"
? t("pluginInstalling")
: busy === "update"
? t("pluginUpdating")
: busy === "enable" || busy === "disable"
? t("pluginToggling")
: busy === "remove"
? t("pluginRemoving")
: null;
return (
<div className="flex flex-col gap-2.5 rounded-xl border border-border bg-panel p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-1.5">
<h4 className="truncate text-sm font-semibold text-content-primary" title={card.displayName}>
{card.displayName}
</h4>
{card.updateAvailable && (
<span className="rounded-md bg-amber-100 dark:bg-amber-900/30 px-2 py-0.5 text-[10px] text-amber-700 dark:text-amber-300">
{t("pluginUpdateAvailable")}
</span>
)}
{card.customInstall && (
<span className="rounded-md bg-blue-100 dark:bg-blue-900/30 px-2 py-0.5 text-[10px] text-blue-700 dark:text-blue-300">
{t("pluginCustomInstall")}
</span>
)}
</div>
<div className="mt-0.5 flex items-center gap-2 text-[11px] text-content-muted">
<span className="truncate font-mono">{card.id}</span>
{card.version && <span className="shrink-0">v{card.version}</span>}
</div>
</div>
{installed && (
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-xs ${
installed.enabled
? "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300"
: "bg-zinc-200 dark:bg-zinc-700/40 text-zinc-600 dark:text-zinc-300"
}`}
>
{installed.enabled ? t("activated") : t("disabled")}
</span>
)}
</div>
{card.description && (
<p className="line-clamp-2 text-sm leading-relaxed text-content-muted">{card.description}</p>
)}
{card.keywords.length > 0 && (
<div className="flex flex-wrap gap-1">
{card.keywords.slice(0, 6).map((k) => (
<span
key={k}
className="rounded border border-border bg-input px-1.5 py-0.5 text-[10px] text-content-muted"
>
{k}
</span>
))}
</div>
)}
<div className="mt-auto flex items-center justify-between gap-2 border-t border-border/50 pt-2.5">
<div className="flex min-w-0 items-center gap-2">
{card.homepage && (
<button
type="button"
onClick={() => openUrl(card.homepage!)}
title={card.homepage}
className="shrink-0 text-xs text-blue-600 hover:underline dark:text-blue-400"
>
{t("pluginHomepage")}
</button>
)}
{card.source && !card.customInstall && (
<span className="truncate font-mono text-[10px] text-content-muted" title={card.source}>
{card.source}
</span>
)}
</div>
<div className="flex shrink-0 items-center gap-1.5">
{installed ? (
<>
{card.updateAvailable && (
<button
type="button"
disabled={busy != null || !!card.capabilityId}
onClick={() => onUpdate(card)}
title={card.capabilityId ? t("pluginCapabilityRequired") : undefined}
className="px-2.5 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
>
{busy === "update" ? busyLabel : t("pluginUpdate")}
</button>
)}
<button
type="button"
disabled={busy != null}
onClick={() => onToggle(card)}
className="px-2.5 py-1 text-xs rounded border border-border hover:bg-hover-2 disabled:opacity-50"
>
{busy === "enable" || busy === "disable"
? busyLabel
: installed.enabled
? t("pluginDisable")
: t("pluginEnable")}
</button>
<button
type="button"
disabled={busy != null}
onClick={() => onRemove(card)}
className="px-2.5 py-1 text-xs rounded border border-red-500/30 text-red-300 hover:bg-red-900/20 disabled:opacity-50"
>
{busy === "remove" ? busyLabel : t("pluginRemove")}
</button>
</>
) : (
<span title={card.capabilityId ? t("pluginCapabilityRequired") : undefined}>
<button
type="button"
disabled={busy != null || !!card.capabilityId}
onClick={() => onInstall(card)}
className="px-2.5 py-1 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
>
{busy === "install" ? busyLabel : t("pluginInstall")}
</button>
</span>
)}
</div>
</div>
</div>
);
}
function openUrl(url: string) {
invoke("open_external_url", { url }).catch(() => {
const w = window.open(url, "_blank");
if (!w) console.error(`failed to open ${url}`);
});
}
+106
View File
@@ -0,0 +1,106 @@
import { useCallback, useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import type {
InstalledPluginInfo,
PluginMarketplaceResult,
} from "../../types";
/**
* Plugin marketplace data + mutations. All backend IPC for the plugin
* marketplace is concentrated here so the page stays thin and the switch
* to a live backend is a drop-in change.
*
* IPC contract (Rust, camelCase args):
* get_plugin_marketplace(homeOverride?, refresh?) → PluginMarketplaceResult
* list_installed_plugins(homeOverride?) → InstalledPluginInfo[]
* install_plugin(homeOverride?, source, expectedId?) → InstalledPluginInfo
* set_plugin_enabled(homeOverride?, id, enabled) → void
* remove_plugin(homeOverride?, id) → void
* Like the existing pages, homeOverride is never passed (Rust side defaults).
*/
export function usePlugins() {
const [catalog, setCatalog] = useState<PluginMarketplaceResult | null>(null);
const [installed, setInstalled] = useState<InstalledPluginInfo[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [installedLoading, setInstalledLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [installedError, setInstalledError] = useState<string | null>(null);
const loadCatalog = useCallback(async (refresh = false) => {
setCatalogLoading(true);
setCatalogError(null);
try {
const result = await invoke<PluginMarketplaceResult>(
"get_plugin_marketplace",
{ refresh }
);
setCatalog(result);
return result;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setCatalogError(msg);
return null;
} finally {
setCatalogLoading(false);
}
}, []);
const loadInstalled = useCallback(async () => {
setInstalledLoading(true);
setInstalledError(null);
try {
const result = await invoke<InstalledPluginInfo[]>(
"list_installed_plugins",
{}
);
setInstalled(result);
return result;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
setInstalledError(msg);
return null;
} finally {
setInstalledLoading(false);
}
}, []);
useEffect(() => {
void loadCatalog(false);
void loadInstalled();
}, [loadCatalog, loadInstalled]);
const installPlugin = useCallback(
async (source: string, expectedId?: string) => {
return invoke<InstalledPluginInfo>("install_plugin", {
source,
expectedId,
});
},
[]
);
const setPluginEnabled = useCallback(
async (id: string, enabled: boolean) => {
await invoke("set_plugin_enabled", { id, enabled });
},
[]
);
const removePlugin = useCallback(async (id: string) => {
await invoke("remove_plugin", { id });
}, []);
return {
catalog,
installed,
catalogLoading,
installedLoading,
catalogError,
installedError,
loadCatalog,
loadInstalled,
installPlugin,
setPluginEnabled,
removePlugin,
};
}
+5 -1
View File
@@ -16,7 +16,8 @@ export type UsageKind =
| "balance:kimi"
| "plan:kimi_coding"
| "plan:zhipu"
| "plan:minimax";
| "plan:minimax"
| "plan:opencode_go";
/** Billing model for a preset. Drives the tab filter in PresetPickerModal. */
export type BillingMode = "subscription" | "pay_as_you_go";
@@ -32,6 +33,7 @@ export const SUPPORTED_USAGE_KINDS: ReadonlySet<string> = new Set<UsageKind>([
"plan:kimi_coding",
"plan:zhipu",
"plan:minimax",
"plan:opencode_go",
]);
export type PresetCategory =
@@ -469,6 +471,8 @@ export const providerPresets: ProviderPreset[] = [
{ model: "deepseek-v4-flash", displayName: "DeepSeek V4 Flash" },
],
billingMode: "subscription",
// Go 套餐额度查询:GET https://opencode.ai/zen/go/v1/usage(Bearer)。
usageKinds: ["plan:opencode_go"],
},
{
id: "opencode-zen",
+48
View File
@@ -422,6 +422,7 @@ export const enTranslations: Record<TranslationKey, string> = {
usageUnsupportedProvider: "This provider is not supported by auto query",
usageTier5h: "5-hour",
usageTierWeekly: "Weekly",
usageTierMonthly: "Monthly",
usageErrNoKey: "No API key configured",
usageErrDisabled: "Usage query is disabled in the config panel",
usageErrLoginExpired: "Kimi Code login expired and auto-refresh failed; run `kimi login` again",
@@ -514,4 +515,51 @@ export const enTranslations: Record<TranslationKey, string> = {
"Open the new Web UI in an independent in-app window, or in your system browser (built into kimi-code 0.33+). Requires the kimi CLI on PATH.",
openWebUIEmbedded: "Open in App",
openWebUIBrowser: "Open in Browser",
// Plugin marketplace
pluginMarketplace: "Plugin Marketplace",
pluginMarketplaceSubtitle:
"Browse and install Kimi Code plugins — official and community, with install, update, and enable/disable management.",
pluginSearchPlaceholder: "Search by name, description, keyword, or ID…",
pluginSectionInstalled: "Installed",
pluginSectionOfficial: "Official",
pluginSectionCommunity: "Community",
pluginCustomInstall: "Custom",
pluginUpdateAvailable: "Update available",
pluginCapabilityRequired: "Install inside kimi-code (/plugins)",
pluginInstall: "Install",
pluginUpdate: "Update",
pluginEnable: "Enable",
pluginDisable: "Disable",
pluginRemove: "Remove",
pluginInstalling: "Installing…",
pluginUpdating: "Updating…",
pluginToggling: "Switching…",
pluginRemoving: "Removing…",
pluginTrustTitle: "Install third-party plugin?",
pluginTrustDesc:
"This plugin comes from {source}. Plugins can contribute MCP tools, hooks, and commands, and may access your sessions and files. Only install from sources you trust.",
pluginTrustInstall: "Trust & install",
pluginRemoveTitle: "Remove plugin?",
pluginRemoveConfirm:
"Remove \"{name}\"? Run /reload in kimi-code or start a new session afterwards to apply.",
pluginInstalledMsg:
"\"{name}\" installed. Run /reload in kimi-code or start a new session to apply.",
pluginUpdatedMsg:
"\"{name}\" updated. Run /reload in kimi-code or start a new session to apply.",
pluginEnabledMsg:
"\"{name}\" enabled. Run /reload in kimi-code or start a new session to apply.",
pluginDisabledMsg:
"\"{name}\" disabled. Run /reload in kimi-code or start a new session to apply.",
pluginRemovedMsg:
"\"{name}\" removed. Run /reload in kimi-code or start a new session to apply.",
pluginCopyReload: "Copy /reload",
pluginReloadCopied: "Copied",
pluginCacheNotice: "Showing cached data (fetched {time})",
pluginCatalogFailed:
"Failed to load the plugin catalog; showing locally installed plugins",
pluginInstalledListFailed: "Failed to load the installed plugin list",
pluginEmptyResults: "No matching plugins",
pluginNoPlugins: "No plugins available",
pluginHomepage: "Homepage",
};
+41
View File
@@ -417,6 +417,7 @@ export const zhTranslations = {
usageUnsupportedProvider: "此供应商暂不支持自动查询",
usageTier5h: "5小时",
usageTierWeekly: "7天",
usageTierMonthly: "30天",
usageErrNoKey: "未配置 API Key",
usageErrDisabled: "用量查询已在配置面板中停用",
usageErrLoginExpired: "Kimi Code 登录已过期且自动续期失败,请重新运行 `kimi login`",
@@ -506,6 +507,46 @@ export const zhTranslations = {
"以独立窗口在应用内打开新版 Web 界面,也可以选择在系统浏览器打开(kimi-code 0.33+ 内置 code-app;需要 kimi 命令在 PATH 中)。",
openWebUIEmbedded: "在应用内打开",
openWebUIBrowser: "在浏览器打开",
// Plugin marketplace
pluginMarketplace: "插件市场",
pluginMarketplaceSubtitle:
"浏览并安装 Kimi Code 插件:官方、社区插件均可安装,支持更新与启用/禁用管理。",
pluginSearchPlaceholder: "搜索插件名称、描述、关键词或 ID…",
pluginSectionInstalled: "已安装",
pluginSectionOfficial: "官方",
pluginSectionCommunity: "社区",
pluginCustomInstall: "自定义安装",
pluginUpdateAvailable: "有更新",
pluginCapabilityRequired: "需在 kimi-code 内安装(/plugins)",
pluginInstall: "安装",
pluginUpdate: "更新",
pluginEnable: "启用",
pluginDisable: "禁用",
pluginRemove: "移除",
pluginInstalling: "安装中…",
pluginUpdating: "更新中…",
pluginToggling: "切换中…",
pluginRemoving: "移除中…",
pluginTrustTitle: "安装第三方插件?",
pluginTrustDesc:
"该插件来自 {source}。插件可贡献 MCP 工具、hooks 与命令,并可能访问你的会话和文件。请仅安装你信任的来源。",
pluginTrustInstall: "信任并安装",
pluginRemoveTitle: "移除插件?",
pluginRemoveConfirm: "确定移除「{name}」?移除后请在 kimi-code 中 /reload 或开新会话生效。",
pluginInstalledMsg: "「{name}」已安装。请在 kimi-code 中 /reload 或开新会话生效。",
pluginUpdatedMsg: "「{name}」已更新。请在 kimi-code 中 /reload 或开新会话生效。",
pluginEnabledMsg: "「{name}」已启用。请在 kimi-code 中 /reload 或开新会话生效。",
pluginDisabledMsg: "「{name}」已禁用。请在 kimi-code 中 /reload 或开新会话生效。",
pluginRemovedMsg: "「{name}」已移除。请在 kimi-code 中 /reload 或开新会话生效。",
pluginCopyReload: "复制 /reload",
pluginReloadCopied: "已复制",
pluginCacheNotice: "显示缓存数据(获取于 {time})",
pluginCatalogFailed: "插件目录加载失败,已改用本地已安装列表",
pluginInstalledListFailed: "已安装插件列表加载失败",
pluginEmptyResults: "没有匹配的插件",
pluginNoPlugins: "暂无插件",
pluginHomepage: "主页",
} as const;
export type TranslationKey = keyof typeof zhTranslations;
+46 -18
View File
@@ -13005,6 +13005,21 @@
"input_limit": 16384,
"output_limit": 8192
},
{
"id": "zai-org/glm-5.3:thinking",
"name": "GLM 5.3 Preview Thinking",
"cost": {
"input": 1.4,
"output": 4.4,
"cache_read": 0.26
},
"context": 1048576,
"input_limit": 1048576,
"output_limit": 131072,
"reasoning": true,
"tool_call": true,
"structured_output": true
},
{
"id": "zai-org/glm-5-original:thinking",
"name": "GLM 5 Original Thinking",
@@ -13206,6 +13221,21 @@
"tool_call": true,
"structured_output": true
},
{
"id": "zai-org/glm-5.3",
"name": "GLM 5.3 Preview",
"cost": {
"input": 1.4,
"output": 4.4,
"cache_read": 0.26
},
"context": 1048576,
"input_limit": 1048576,
"output_limit": 131072,
"reasoning": true,
"tool_call": true,
"structured_output": true
},
{
"id": "zai-org/glm-4.7-flash-original:thinking",
"name": "GLM 4.7 Flash Original Thinking",
@@ -24348,9 +24378,8 @@
"id": "qwen/qwen-plus-2025-07-28:thinking",
"name": "Qwen Plus 0728 (thinking)",
"cost": {
"input": 0.4,
"output": 1.2,
"cache_write": 0.5
"input": 0.26,
"output": 0.78
},
"context": 1000000,
"output_limit": 32768,
@@ -56152,10 +56181,10 @@
"id": "gemini-3.1-flash-lite@eu",
"name": "Gemini 3.1 Flash Lite (EU)",
"cost": {
"input": 0.25,
"output": 1.5,
"cache_read": 0.025,
"cache_write": 0.08333
"input": 0.275,
"output": 1.65,
"cache_read": 0.0275,
"cache_write": 0.091663
},
"context": 1048576,
"output_limit": 65535,
@@ -56357,10 +56386,10 @@
"id": "gemini-3.5-flash@eu",
"name": "Gemini 3.5 Flash (EU)",
"cost": {
"input": 1.5,
"output": 9,
"cache_read": 0.15,
"cache_write": 1.583
"input": 1.65,
"output": 9.9,
"cache_read": 0.165,
"cache_write": 1.7413
},
"context": 1048576,
"output_limit": 65535,
@@ -56409,7 +56438,7 @@
"input": 5.5,
"output": 27.5,
"cache_read": 0.55,
"cache_write": 6.88
"cache_write": 6.875
},
"context": 1000000,
"output_limit": 128000,
@@ -56590,9 +56619,9 @@
"id": "gemini-3.7-flash@eu",
"name": "Gemini 3.7 Flash (EU)",
"cost": {
"input": 0.75,
"output": 3.75,
"cache_read": 0.075
"input": 0.825,
"output": 4.125,
"cache_read": 0.0825
},
"context": 1048576,
"output_limit": 65535,
@@ -81769,9 +81798,8 @@
"id": "qwen/qwen-plus-2025-07-28:thinking",
"name": "Qwen: Qwen Plus 0728 (thinking)",
"cost": {
"input": 0.4,
"output": 1.2,
"cache_write": 0.5
"input": 0.26,
"output": 0.78
},
"context": 1000000,
"output_limit": 32768,
+40 -18
View File
@@ -10428,6 +10428,18 @@
"cache_read": 0.2465
}
},
"nano-gpt/zai-org/glm-5.3:thinking": {
"name": "GLM 5.3 Preview Thinking",
"context": 1048576,
"reasoning": true,
"tool_call": true,
"structured_output": true,
"cost": {
"input": 1.4,
"output": 4.4,
"cache_read": 0.26
}
},
"nano-gpt/zai-org/glm-5-original:thinking": {
"name": "GLM 5 Original Thinking",
"context": 200000,
@@ -10587,6 +10599,18 @@
"cache_read": 0.078
}
},
"nano-gpt/zai-org/glm-5.3": {
"name": "GLM 5.3 Preview",
"context": 1048576,
"reasoning": true,
"tool_call": true,
"structured_output": true,
"cost": {
"input": 1.4,
"output": 4.4,
"cache_read": 0.26
}
},
"nano-gpt/zai-org/glm-4.7-flash-original:thinking": {
"name": "GLM 4.7 Flash Original Thinking",
"context": 200000,
@@ -19817,9 +19841,8 @@
"tool_call": true,
"structured_output": true,
"cost": {
"input": 0.4,
"output": 1.2,
"cache_write": 0.5
"input": 0.26,
"output": 0.78
}
},
"openrouter/qwen/qwen3-235b-a22b-thinking-2507": {
@@ -46199,10 +46222,10 @@
"image": true,
"video": true,
"cost": {
"input": 0.25,
"output": 1.5,
"cache_read": 0.025,
"cache_write": 0.08333
"input": 0.275,
"output": 1.65,
"cache_read": 0.0275,
"cache_write": 0.091663
}
},
"requesty/gpt-5@eu": {
@@ -46375,10 +46398,10 @@
"image": true,
"video": true,
"cost": {
"input": 1.5,
"output": 9,
"cache_read": 0.15,
"cache_write": 1.583
"input": 1.65,
"output": 9.9,
"cache_read": 0.165,
"cache_write": 1.7413
}
},
"requesty/claude-sonnet-5@eu": {
@@ -46420,7 +46443,7 @@
"input": 5.5,
"output": 27.5,
"cache_read": 0.55,
"cache_write": 6.88
"cache_write": 6.875
}
},
"requesty/claude-opus-4-7@eu": {
@@ -46578,9 +46601,9 @@
"image": true,
"video": true,
"cost": {
"input": 0.75,
"output": 3.75,
"cache_read": 0.075
"input": 0.825,
"output": 4.125,
"cache_read": 0.0825
}
},
"requesty/gpt-5.4@eu": {
@@ -67604,9 +67627,8 @@
"tool_call": true,
"structured_output": true,
"cost": {
"input": 0.4,
"output": 1.2,
"cache_write": 0.5
"input": 0.26,
"output": 0.78
}
},
"kilo/qwen/qwen3-235b-a22b-thinking-2507": {
+5 -3
View File
@@ -11,9 +11,9 @@ type TranslateFn = (
*
* Coverage note: ALL plan-type (套餐) queries flow through
* src-tauri/src/services/coding_plan.rs::percent_tier, whose names come only
* from TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT — so this mapping covers every
* current and future plan provider automatically. If a new tier id is ever
* added there, add a case here too.
* from TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT / TIER_MONTHLY_LIMIT — so this
* mapping covers every current and future plan provider automatically. If a
* new tier id is ever added there, add a case here too.
*/
export function planLabel(name: string, t: TranslateFn): string {
switch (name) {
@@ -21,6 +21,8 @@ export function planLabel(name: string, t: TranslateFn): string {
return t("usageTier5h");
case "weekly_limit":
return t("usageTierWeekly");
case "monthly_limit":
return t("usageTierMonthly");
default:
return name;
}
+41
View File
@@ -163,3 +163,44 @@ export interface SecondaryModelConfig {
/** Values of experimental env vars that are currently set (non-empty). */
export type ExperimentalEnvStatus = Record<string, string>;
/**
* A plugin installed under the kimi-code plugin directory
* (mirrors the Rust `InstalledPluginInfo`, camelCase via serde).
*/
export interface InstalledPluginInfo {
id: string;
root: string;
source: string;
enabled: boolean;
version: string | null;
installedAt: string | null;
updatedAt: string | null;
/** Whether the plugin came from the marketplace catalog (vs. manual install). */
isMarketplace: boolean;
}
/** One entry of the plugin marketplace catalog (mirrors Rust `MarketplaceEntry`). */
export interface MarketplaceEntry {
id: string;
displayName: string;
version: string | null;
description: string | null;
keywords: string[];
homepage: string | null;
/** "official" | "curated" | anything else → community. */
tier: string;
/** Install source (URL / path) passed to `install_plugin`. */
source: string;
/** Non-null → must be installed inside kimi-code via /plugins, not here. */
capabilityId: string | null;
installed: InstalledPluginInfo | null;
updateAvailable: boolean;
}
/** Result of `get_plugin_marketplace` (mirrors Rust `PluginMarketplaceResult`). */
export interface PluginMarketplaceResult {
fetchedAt: string;
fromCache: boolean;
entries: MarketplaceEntry[];
}