Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b80d66239 | ||
|
|
0f421b4e44 | ||
|
|
00cf194b5c | ||
|
|
b9002281a3 | ||
|
|
0ea9e5b3de | ||
|
|
36e64a1f72 | ||
|
|
9ce1ed65b0 | ||
|
|
33a27ba31b | ||
|
|
7bc2dee8b2 | ||
|
|
5864d661c1 | ||
|
|
34a9c4c2d9 | ||
|
|
4f0b0cae12 | ||
|
|
35fd2e7b0e | ||
|
|
86112ee90b | ||
|
|
e349fa5971 | ||
|
|
1de8b9ee4c | ||
|
|
36fc9c50a8 | ||
|
|
1a11cfbaaf | ||
|
|
81699e757d | ||
|
|
4de13ad353 |
No files matched your search
@@ -69,6 +69,45 @@ jobs:
|
||||
libgtk-3-dev \
|
||||
libayatana-appindicator3-dev
|
||||
|
||||
- name: Compose release body
|
||||
id: notes
|
||||
shell: bash
|
||||
run: |
|
||||
FILE="release-notes-${{ github.ref_name }}.md"
|
||||
{
|
||||
echo 'body<<RELEASE_BODY_EOF'
|
||||
if [ -f "$FILE" ]; then
|
||||
cat "$FILE"
|
||||
else
|
||||
echo "## ${{ github.ref_name }}"
|
||||
echo
|
||||
echo "见提交记录(未找到 $FILE)。"
|
||||
fi
|
||||
echo
|
||||
cat <<'TAIL_EOF'
|
||||
### 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` → 打开 → 弹窗中点「打开」(或 系统设置 → 隐私与安全性 → 仍要打开)
|
||||
|
||||
Full changelog: see commit history.
|
||||
TAIL_EOF
|
||||
echo 'RELEASE_BODY_EOF'
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and upload release
|
||||
uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
@@ -76,36 +115,7 @@ jobs:
|
||||
with:
|
||||
tagName: ${{ github.ref_name }}
|
||||
releaseName: ${{ github.ref_name }}
|
||||
releaseBody: |
|
||||
## ${{ github.ref_name }}
|
||||
|
||||
### 本次更新
|
||||
|
||||
- **模型数据同步(models.dev 2026-08-27)**:7343 个模型 / 203 个供应商
|
||||
- **新增 GLM-5.3 / GLM-5.3-Flash 全线接入**:智谱官方、OpenRouter、Cloudflare、DeepInfra、HuggingFace、火山引擎等约 20 条渠道;GLM-5.3-Flash 定价 $0.075 / $0.25(输入/输出,每百万 token)
|
||||
- 新增 coding plan 渠道:`zhipuai-coding-plan/glm-5.3`、`glm-5.3-highspeed`、`glm-5.3-flash`
|
||||
- 新增 Qwen3.8 系列、火山引擎豆包 Seed 2.x 全系、DeepSeek-V4 GA 版、MiniMax-M2.7/M3 等共 74 个模型条目
|
||||
- 价格更新 58 处、能力信息修正 56 处(详见 release-notes-v0.7.9.md)
|
||||
|
||||
### 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` → 打开 → 弹窗中点「打开」(或 系统设置 → 隐私与安全性 → 仍要打开)
|
||||
|
||||
Full changelog: see commit history.
|
||||
releaseBody: ${{ steps.notes.outputs.body }}
|
||||
prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
|
||||
overwrite: true
|
||||
args: ${{ matrix.args }}
|
||||
|
||||
@@ -253,6 +253,17 @@ KimiSwitch 现有 `usageKinds` 枚举是**每家中转站一个 Rust 函数**的
|
||||
|
||||
## 5. 新增能力实现清单(改动点)
|
||||
|
||||
> 实施状态更新(2026-09-13):**Sub2API 兼容已实现(`balance:sub2api`)**。
|
||||
> 实测澄清:`codingplan.site`(主域)**不是** NewAPI 而是 Wei-Shaw/sub2api 面板
|
||||
> (NewAPI 端点 `/api/status`、`/api/user/self` 全 404;`/api/v1/settings/public`
|
||||
> 返回 `data.affiliate_enabled` 指纹命中;`/v1/usage`、`/v1/sub2api/billing` 为
|
||||
> API-key 网关端点)。`ai.codingplan.site` 才是 NewAPI 实例。detect_provider
|
||||
> 已按此拆分家族规则。Sub2API 查询复用推理 sk- key(`GET {base}/v1/usage`,
|
||||
> Bearer),解析三种 mode:quota_limited(quota + 5h/1d/7d rate_limits)、
|
||||
> unrestricted 订阅组(daily/weekly/monthly usage/limit USD)、钱包余额。
|
||||
> UsageConfigModal 模板加 "sub2api"(无需凭据,可选 Base URL 覆盖)。
|
||||
> 验证:cargo test 124 通过(含 6 个 sub2api 解析用例)、tsc 零错误。
|
||||
|
||||
> 实施状态(2026-07-31):**P0 已实现,未验证、未提交**。
|
||||
> 展示方案已确认为 **A(供应商卡片底部 UsageFooter,零前端改动)**。
|
||||
> 改动文件:`src-tauri/src/services/balance.rs`(query_kimi/parse_kimi + 单测)、`src-tauri/src/services/mod.rs`(枚举/路由/detect + 单测)、`src/config/providerPresets.ts`(UsageKind/SUPPORTED_USAGE_KINDS + moonshot 预设挂 `balance:kimi`)。
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "kimiswitch",
|
||||
"private": true,
|
||||
"version": "0.7.12",
|
||||
"version": "0.7.19",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
+81355
-77455
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
# KimiSwitch v0.7.13
|
||||
|
||||
## 适配 kimi-code 0.41.0
|
||||
|
||||
- **实验 flag 清单回至 9 个**:上游 0.41.0 移除了 `file_history` 实验 flag(轮级文件历史转为恒开),KimiSwitch 镜像全链路同步删除;用户配置中残留的该键会被上游静默忽略,无副作用
|
||||
- **危险命令守卫文案更新**:Auto(永不询问)模式自 0.41.0 起不再拦截危险命令与无法静态分析的命令,仅 Manual/YOLO 模式强制询问——设置页描述文案(中英)同步修正
|
||||
|
||||
## 账单查询改进
|
||||
|
||||
- **CodingPlan.site 自动识别**:`codingplan.site` 系供应商自动识别为 NewAPI 余额查询,无需手动选模板
|
||||
- **修复凭据缺失误报「网络异常」**:NewAPI 模板未配置 Access Token/User ID 时,现在显示明确的本地化配置提示,而非误导性的网络错误
|
||||
- **金额显示统一**:配置弹窗与卡片底部走同一格式化(两位小数);NewAPI 站点未配置货币符号时的 `¤` 占位符不再显示
|
||||
|
||||
## 其它
|
||||
|
||||
- models-dev 快照随 0.7.12 线更新;新增 usage 错误本地化单元测试
|
||||
@@ -0,0 +1,10 @@
|
||||
# KimiSwitch v0.7.14
|
||||
|
||||
## 修复
|
||||
|
||||
- **关闭「启用用量查询」后不再残留查询行为**:此前关闭开关后前端仍会发起查询,卡片上持续显示「查询失败 · 用量查询已关闭」的红色错误行。现在关闭后立即停止查询、隐藏整行用量信息(卡片头部与底部两种展示均生效),重新开启后自动恢复
|
||||
- 在途的查询结果在开关切换瞬间作废,且不再写入共享缓存,避免过期的失败状态在 5 分钟内复活
|
||||
|
||||
## 数据
|
||||
|
||||
- models-dev 快照同步(上游格式与价格更新)
|
||||
@@ -0,0 +1,16 @@
|
||||
# KimiSwitch v0.7.15
|
||||
|
||||
## 新功能
|
||||
|
||||
- **用量统计新增「昨天」选项卡**:时间范围现为 今天 / 昨天 / 7 天 / 30 天 / 全部,「昨天」按本地时区严格统计昨日 0 点至今日 0 点(不渗入今天),顶部概览卡同步扩展为 5 张
|
||||
- **新增「模型用量统计」趋势选项卡**:在「供应商模型用量趋势」之后,不按天、跨供应商按模型名汇总(同一模型经不同供应商合并为一行),横向条形图按 Token 降序,悬停显示请求数 / Token / 缓存命中 / 费用;子代理模型仍单独成行
|
||||
|
||||
## 修复
|
||||
|
||||
- **opencode Go 套餐子代理请求 400**:Go 网关(opencode.ai/zen/go)近期强制要求 `x-opencode-session` 请求头用于路由与提示词缓存,缺失即 400 拒绝。现在导出配置时,凡指向 Go 端点的供应商会自动补写 `custom_headers.x-opencode-session`(已有用户自定义值保留不覆盖);按量计费的 `zen/v1` 端点不受影响
|
||||
- 定价测试基准条目更新:models.dev 上游下架 `moonshotai/kimi-k2.5` 官方条目,测试基准切换到 `moonshotai/kimi-k3`
|
||||
|
||||
## 数据
|
||||
|
||||
- models-dev 快照同步至 2026-09-09(7583 模型 / 213 供应商),并补齐 `public/` 前端静态目录(原停留在 08-27)
|
||||
- 注意:k2.5 官方定价条目下架后,`kimi/k2.5` 费用估算暂解析到 302ai 转售价格(0.66 / 3.3),略高于原官方价
|
||||
@@ -0,0 +1,7 @@
|
||||
# KimiSwitch v0.7.16
|
||||
|
||||
## 适配
|
||||
|
||||
- **适配 kimi-code 0.42.0 实验 flag 镜像(9→6)**:移除已转正/删除的 4 个开关(子代理次主力模型——模型池恒开、MiniDB 读模型——改由 `[database]` 配置节、远程控制、搜索 Worker),新增 `notify_user`(实验性 Updates 面板,默认关闭);环境变量探测清单同步;老配置残留旧键上游静默忽略,无需迁移
|
||||
- 用量统计「模型用量统计」图表固定最大高度 360px 并支持滚动,与右侧模型用量表一致
|
||||
- models-dev 快照同步至 2026-09-10(7615 模型 / 213 供应商),`public/` 前端静态目录同步
|
||||
@@ -0,0 +1,16 @@
|
||||
# KimiSwitch v0.7.17
|
||||
|
||||
## 新增
|
||||
|
||||
- **账单查询适配 Sub2API 中转站(`balance:sub2api`)**:支持 Wei-Shaw/sub2api 面板的余额/额度查询(`GET {base}/v1/usage`),自动复用推理 `sk-` API Key,**无需**网页后台 Access Token;解析三种模式——单 Key 总额度(quota)、5 小时/每日/7 天速率窗口(含重置倒计时)、订阅组日/周/月额度与钱包余额(USD)
|
||||
- 用量配置面板新增「Sub2API 中转站」模板,可选覆盖查询地址(Base URL)
|
||||
- `detect_provider` 家族规则拆分:`codingplan.site` 主域识别为 Sub2API,`ai.codingplan.site` 识别为 NewAPI(修正此前主域被误判为 NewAPI 导致查询 404 的问题)
|
||||
- **模型映射「获取模型列表」新增批量选择**:发现列表标题右侧新增「全选 / 取消全选 / 反选」三个按钮,配合已有的已添加标记与「添加选中的」,批量接入中转站模型列表更省事
|
||||
|
||||
## 修复
|
||||
|
||||
- 修复 `codingplan.site`(Sub2API 面板)走 NewAPI 模板查询必然失败的问题——NewAPI 模板(Access Token + User ID)仍适用于 NewAPI / OneAPI 站点,两者互不影响
|
||||
|
||||
## 备注
|
||||
|
||||
- Sub2API 查询的金额单位由上游硬编码为 USD;速率窗口标签沿用现有本地化(5 小时 / 每日 / 7 天)
|
||||
@@ -0,0 +1,14 @@
|
||||
# KimiSwitch v0.7.18
|
||||
|
||||
## 新增
|
||||
|
||||
- **会话管理「一键归档」**:支持按 1 个月前 / 半个月前 / 1 星期前 / 指定日期,一键归档所有最后活跃时间早于所选时间点的会话(一次批量操作,替代逐个选择);结果反馈已归档 / 跳过数量
|
||||
- **归档用量快照落库**:归档瞬间把每个会话的 token 用量与费用按「天 × 模型」粒度快照进 SQLite(`archived_sessions` 表)。之后删除已归档会话(释放磁盘)不再损失历史统计——仪表盘的趋势图、热力图、模型统计、区间合计均会自动合并快照数据,且与现存文件实时统计严格去重(只合并文件已删除的归档会话,绝不双计)
|
||||
|
||||
## 修复
|
||||
|
||||
- models-dev 快照同步至 2026-09-14(7784 模型 / 213 供应商),`public/` 前端静态目录同步;pricing 测试价格断言跟随 DeepSeek 官方调价(deepseek-v4-flash input 0.14→0.15 / output 0.28→0.60)
|
||||
|
||||
## 备注
|
||||
|
||||
- 归档仍是元数据语义(文件原地保留),删除文件才会触发快照合并;用量配置、账单查询等其余功能不受影响
|
||||
@@ -0,0 +1,10 @@
|
||||
# KimiSwitch v0.7.19
|
||||
|
||||
## 适配
|
||||
|
||||
- **适配 kimi-code 0.43.0 实验 flag 镜像(7→5)**:移除已转正的 `auto_session_title` 开关(上游 #3749,AI 会话标题不再需要 flag,首轮对话后自动生成、可在重命名处重新生成)。设置页「实验性 flag」、环境变量探测(`get_experimental_env_status`)、中英文案与测试断言同步清理;上游 0.43.0 注册表现剩 5 个 flag: `wait_for` / `tool-select` / `notify_user` / `tower` / `subagent_fork`
|
||||
- **兼容性核查结论(无需改动)**:0.43.0 的 wire 持久化重建(#3737)不影响用量统计——`usage.record` / `token_counting.measured` / `context.apply_compaction` / `turn.prompt` 记录全部保留(`turn.prompt` 仅新增可选 `turnId` 字段);新增配置项 `loop_control.compaction_max_attempts`(#3750)经现有合并式写入验证保存不丢失;MCP `deferred` 字段(#3667)不涉及本应用管理的配置节
|
||||
|
||||
## 备注
|
||||
|
||||
- 若此前在 `[experimental]` 中显式开启过 `auto_session_title`,残留键会被上游静默忽略,无需手动清理
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env bash
|
||||
# Publish a release (notes + assets) to the domestic Gitea mirror
|
||||
# (git.codingplan.site/admin/KimiCodeSwitch).
|
||||
#
|
||||
# Usage: publish-gitea.sh <tag> <asset> [asset...]
|
||||
# tag : e.g. v0.7.15; notes read from release-notes-<tag>.md
|
||||
# assets : files to attach (MSI, install-macos.sh, ...)
|
||||
#
|
||||
# Auth: reuses the stored git credential for git.codingplan.site
|
||||
# (`git credential fill`); the secret never appears in argv or output.
|
||||
set -euo pipefail
|
||||
|
||||
GITEA="https://git.codingplan.site/api/v1"
|
||||
REPO="admin/KimiCodeSwitch"
|
||||
TAG="${1:?usage: publish-gitea.sh <tag> <asset> [asset...]}"
|
||||
shift
|
||||
|
||||
NOTES_FILE="release-notes-${TAG}.md"
|
||||
json_escape() {
|
||||
python - "$1" <<'PYEOF'
|
||||
import json, sys
|
||||
print(json.dumps(open(sys.argv[1], encoding="utf-8").read()))
|
||||
PYEOF
|
||||
}
|
||||
if [[ -f "$NOTES_FILE" ]]; then
|
||||
BODY=$(json_escape "$NOTES_FILE")
|
||||
else
|
||||
BODY="\"${TAG}\""
|
||||
fi
|
||||
|
||||
# Resolve stored git credential for this host (no secret echoed).
|
||||
CRED=$(printf 'protocol=https\nhost=git.codingplan.site\n\n' | git credential fill)
|
||||
USER=$(grep '^username=' <<<"$CRED" | cut -d= -f2-)
|
||||
PASS=$(grep '^password=' <<<"$CRED" | cut -d= -f2-)
|
||||
[[ -n "$USER" && -n "$PASS" ]] || { echo "no stored credential for git.codingplan.site" >&2; exit 1; }
|
||||
AUTH=(-u "$USER:$PASS")
|
||||
|
||||
# Create (or reuse) the release for this tag.
|
||||
EXISTING=$(curl -sf --max-time 20 "${AUTH[@]}" "$GITEA/repos/$REPO/releases/tags/$TAG" || true)
|
||||
if [[ -n "$EXISTING" && "$EXISTING" != *"message"* ]]; then
|
||||
RELEASE_ID=$(grep -o '"id":[0-9]*' <<<"$EXISTING" | head -1 | cut -d: -f2)
|
||||
echo "release $TAG exists (id=$RELEASE_ID), attaching assets"
|
||||
else
|
||||
CREATED=$(curl -sf --max-time 20 "${AUTH[@]}" \
|
||||
-H 'Content-Type: application/json' -X POST \
|
||||
-d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":$BODY,\"draft\":false,\"prerelease\":false}" \
|
||||
"$GITEA/repos/$REPO/releases")
|
||||
RELEASE_ID=$(grep -o '"id":[0-9]*' <<<"$CREATED" | head -1 | cut -d: -f2)
|
||||
echo "created release $TAG (id=$RELEASE_ID)"
|
||||
fi
|
||||
|
||||
for ASSET in "$@"; do
|
||||
[[ -f "$ASSET" ]] || { echo "skip missing asset: $ASSET" >&2; continue; }
|
||||
NAME=$(basename "$ASSET" | tr ' ' '.')
|
||||
STAGED=$(mktemp "${TMPDIR:-/tmp}/upload.XXXXXX.${NAME##*.}")
|
||||
cp "$ASSET" "$STAGED"
|
||||
CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 600 "${AUTH[@]}" \
|
||||
-F "attachment=@$STAGED" \
|
||||
"$GITEA/repos/$REPO/releases/$RELEASE_ID/assets?name=$NAME")
|
||||
rm -f "$STAGED"
|
||||
echo "upload $NAME -> HTTP $CODE"
|
||||
[[ "$CODE" == 2* ]] || { echo "upload failed: $NAME" >&2; exit 1; }
|
||||
done
|
||||
|
||||
echo "done: https://git.codingplan.site/$REPO/releases/tag/$TAG"
|
||||
Generated
+1
-1
@@ -1978,7 +1978,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kimiswitch"
|
||||
version = "0.7.12"
|
||||
version = "0.7.19"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "kimiswitch"
|
||||
version = "0.7.12"
|
||||
version = "0.7.19"
|
||||
description = "Kimi Switch - model config manager"
|
||||
authors = ["codingplan.site"]
|
||||
edition = "2021"
|
||||
|
||||
+20
-21
@@ -690,19 +690,20 @@ pub async fn query_provider_usage(
|
||||
|
||||
let base_url = resolve_base_url(provider);
|
||||
|
||||
// NewAPI template: query the gateway's own /api/user/self with the
|
||||
// web-console access token, bypassing usage_kinds entirely.
|
||||
// NewAPI / Sub2API template: query the gateway's own usage endpoints.
|
||||
// NewAPI needs web-console credentials (accessToken + userId); Sub2API
|
||||
// reuses the inference API key directly — both bypass usage_kinds.
|
||||
if let Some(cfg) = &provider.usage_config {
|
||||
if cfg.template_type == UsageConfig::TEMPLATE_NEWAPI {
|
||||
let template_kind = match cfg.template_type.as_str() {
|
||||
UsageConfig::TEMPLATE_NEWAPI => Some(UsageKind::BalanceNewapi),
|
||||
UsageConfig::TEMPLATE_SUB2API => Some(UsageKind::BalanceSub2Api),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(kind) = template_kind {
|
||||
// Err = transient (network) → propagate for retry, same semantics
|
||||
// as the kinds loop below. Config errors surface as Ok(failure).
|
||||
let result = services::query_kind(
|
||||
UsageKind::BalanceNewapi,
|
||||
&base_url,
|
||||
&api_key,
|
||||
Some(cfg),
|
||||
)
|
||||
.await?;
|
||||
let result =
|
||||
services::query_kind(kind, &base_url, &api_key, Some(cfg)).await?;
|
||||
if result.success {
|
||||
usage_cache()
|
||||
.lock()
|
||||
@@ -1335,7 +1336,7 @@ pub async fn kimi_oauth_poll(
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Experimental feature env-var probe (Kimi Code secondary model etc.)
|
||||
// Experimental feature env-var probe (Kimi Code experimental flags)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Read the Kimi Code environment variables that are currently set (non-empty)
|
||||
@@ -1348,6 +1349,12 @@ pub async fn kimi_oauth_poll(
|
||||
/// are probed too — the latter lets AgentSettingsPanel decide whether to
|
||||
/// dual-write the v1 engine's loop_control keys.
|
||||
///
|
||||
/// As of Kimi Code 0.43.0 the upstream registry holds 5 experimental flags
|
||||
/// (`auto_session_title` graduated in 0.43.0 — titles are always on);
|
||||
/// `secondary-model`, `persistence_minidb_readmodel`, `remote-control` and
|
||||
/// `search_worker` were promoted or removed earlier and are no longer
|
||||
/// probed here.
|
||||
///
|
||||
/// The flag id → env var mapping mirrors `EXPERIMENTAL_FLAGS` in
|
||||
/// src/lib/subagent-settings.ts; keep both lists in sync.
|
||||
///
|
||||
@@ -1355,20 +1362,12 @@ pub async fn kimi_oauth_poll(
|
||||
/// the raw values are returned and the truthy check happens on the frontend.
|
||||
#[tauri::command]
|
||||
pub fn get_experimental_env_status() -> HashMap<String, String> {
|
||||
const VARS: [(&str, &str); 12] = [
|
||||
("secondary-model", "KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL"),
|
||||
const VARS: [(&str, &str); 7] = [
|
||||
("tool-select", "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT"),
|
||||
(
|
||||
"persistence_minidb_readmodel",
|
||||
"KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL",
|
||||
),
|
||||
("tower", "KIMI_CODE_EXPERIMENTAL_TOWER"),
|
||||
("subagent_fork", "KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK"),
|
||||
("wait_for", "KIMI_CODE_EXPERIMENTAL_WAIT_FOR"),
|
||||
("auto_session_title", "KIMI_CODE_EXPERIMENTAL_AUTO_SESSION_TITLE"),
|
||||
("remote-control", "KIMI_CODE_EXPERIMENTAL_REMOTE_CONTROL"),
|
||||
("search_worker", "KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER"),
|
||||
("file_history", "KIMI_CODE_EXPERIMENTAL_FILE_HISTORY"),
|
||||
("notify_user", "KIMI_CODE_EXPERIMENTAL_NOTIFY_USER"),
|
||||
// Non-flag probes consumed by the frontend:
|
||||
("master", "KIMI_CODE_EXPERIMENTAL_FLAG"),
|
||||
("legacy", "KIMI_CODE_LEGACY_FLAG"),
|
||||
|
||||
+753
-84
@@ -1,4 +1,5 @@
|
||||
use chrono::{DateTime, Datelike, Local, TimeZone};
|
||||
use crate::db::{ArchivedSessionSnapshot, DayModelStat, DayStat};
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -102,6 +103,9 @@ pub struct RangeStats {
|
||||
pub totals: TotalsRow,
|
||||
pub daily: Vec<DailyRow>,
|
||||
pub models: Vec<ModelRow>,
|
||||
/// Model totals keyed by bare model name (provider prefix stripped), so the
|
||||
/// same model served by multiple providers merges into one row.
|
||||
pub models_by_name: Vec<ModelRow>,
|
||||
pub recent: Vec<RecentRow>,
|
||||
pub recent_total: usize,
|
||||
pub recent_limit: usize,
|
||||
@@ -274,6 +278,15 @@ pub struct ActionResponse {
|
||||
pub deleted: Option<bool>,
|
||||
}
|
||||
|
||||
/// Outcome of the bulk "archive everything older than X" command.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BulkArchiveResult {
|
||||
pub archived: usize,
|
||||
pub skipped: usize,
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PreviewResult {
|
||||
@@ -850,67 +863,8 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
};
|
||||
for line in content.lines() {
|
||||
lines_seen += 1;
|
||||
if !line.contains("\"usage.record\"") { continue; }
|
||||
let obj: serde_json::Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if obj.get("type").and_then(|v| v.as_str()) != Some("usage.record") { continue; }
|
||||
let scope = obj.get("usageScope").and_then(|v| v.as_str()).unwrap_or("turn");
|
||||
if scope != "turn" { continue; }
|
||||
|
||||
let model_raw = obj.get("model").and_then(|v| v.as_str()).unwrap_or("unknown").to_string();
|
||||
// Kimi Code writes the internal marker `__secondary__` as the model
|
||||
// key for usage records emitted by subagents bound to the
|
||||
// configured secondary model. The record stays keyed on that
|
||||
// stable marker so historical records keep their semantics if the
|
||||
// secondary config changes later; cost billing follows the
|
||||
// currently configured secondary model, and the record is flagged
|
||||
// is_secondary so the UI shows it as its own "subagent model"
|
||||
// entry.
|
||||
let is_secondary = model_raw == "__secondary__";
|
||||
let from_env = model_raw == "__kimi_env_model__";
|
||||
let price_model = if is_secondary {
|
||||
secondary_alias.clone().unwrap_or_else(|| model_raw.clone())
|
||||
} else {
|
||||
model_raw.clone()
|
||||
};
|
||||
let time = obj.get("time").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let usage = &obj["usage"];
|
||||
let input_other = usage.get("inputOther").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let output = usage.get("output").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let cache_read = usage.get("inputCacheRead").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let cache_create = usage.get("inputCacheCreation").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
|
||||
// Resolve model display
|
||||
let bare = model_raw.rsplit_once('/').map(|x| x.1).unwrap_or(&model_raw);
|
||||
let (cost, est) = cost_for_usage(input_other, output, cache_read, cache_create, &price_model);
|
||||
// Subagent records are inherently estimates: the `__secondary__`
|
||||
// marker carries no model identity, so the cost is flagged as
|
||||
// estimated even when the current secondary config resolves to a
|
||||
// priced listing.
|
||||
let est = est || is_secondary;
|
||||
let (pid, _ch, _ip, _op, _) = match_price(&price_model);
|
||||
|
||||
records.push(UsageRecord {
|
||||
time,
|
||||
model: model_raw.clone(),
|
||||
model_resolved: bare.to_string(),
|
||||
model_display: model_raw.clone(),
|
||||
provider: resolve_provider(&price_model, &alias2prov),
|
||||
from_env,
|
||||
is_secondary,
|
||||
input_other,
|
||||
output,
|
||||
input_cache_read: cache_read,
|
||||
input_cache_creation: cache_create,
|
||||
cost_usd: cost,
|
||||
cost_estimated: est,
|
||||
price_id: pid,
|
||||
});
|
||||
}
|
||||
lines_seen += content.lines().count();
|
||||
records.extend(parse_wire_usage_records(&content, &secondary_alias, &alias2prov));
|
||||
}
|
||||
|
||||
records.sort_by(|a, b| b.time.cmp(&a.time));
|
||||
@@ -923,6 +877,180 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse one `wire.jsonl` body into usage records. Extracted from
|
||||
/// `scan_usage` so a single session can be snapshotted without walking the
|
||||
/// whole sessions tree; the record filter chain is unchanged.
|
||||
fn parse_wire_usage_records(
|
||||
content: &str,
|
||||
secondary_alias: &Option<String>,
|
||||
alias2prov: &HashMap<String, String>,
|
||||
) -> Vec<UsageRecord> {
|
||||
let mut records = Vec::new();
|
||||
for line in content.lines() {
|
||||
if !line.contains("\"usage.record\"") { continue; }
|
||||
let obj: serde_json::Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if obj.get("type").and_then(|v| v.as_str()) != Some("usage.record") { continue; }
|
||||
let scope = obj.get("usageScope").and_then(|v| v.as_str()).unwrap_or("turn");
|
||||
if scope != "turn" { continue; }
|
||||
|
||||
let model_raw = obj.get("model").and_then(|v| v.as_str()).unwrap_or("unknown").to_string();
|
||||
// Kimi Code writes the internal marker `__secondary__` as the model
|
||||
// key for usage records emitted by subagents bound to the
|
||||
// configured secondary model. The record stays keyed on that
|
||||
// stable marker so historical records keep their semantics if the
|
||||
// secondary config changes later; cost billing follows the
|
||||
// currently configured secondary model, and the record is flagged
|
||||
// is_secondary so the UI shows it as its own "subagent model"
|
||||
// entry.
|
||||
let is_secondary = model_raw == "__secondary__";
|
||||
let from_env = model_raw == "__kimi_env_model__";
|
||||
let price_model = if is_secondary {
|
||||
secondary_alias.clone().unwrap_or_else(|| model_raw.clone())
|
||||
} else {
|
||||
model_raw.clone()
|
||||
};
|
||||
let time = obj.get("time").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let usage = &obj["usage"];
|
||||
let input_other = usage.get("inputOther").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let output = usage.get("output").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let cache_read = usage.get("inputCacheRead").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let cache_create = usage.get("inputCacheCreation").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
|
||||
// Resolve model display
|
||||
let bare = model_raw.rsplit_once('/').map(|x| x.1).unwrap_or(&model_raw);
|
||||
let (cost, est) = cost_for_usage(input_other, output, cache_read, cache_create, &price_model);
|
||||
// Subagent records are inherently estimates: the `__secondary__`
|
||||
// marker carries no model identity, so the cost is flagged as
|
||||
// estimated even when the current secondary config resolves to a
|
||||
// priced listing.
|
||||
let est = est || is_secondary;
|
||||
let (pid, _ch, _ip, _op, _) = match_price(&price_model);
|
||||
|
||||
records.push(UsageRecord {
|
||||
time,
|
||||
model: model_raw.clone(),
|
||||
model_resolved: bare.to_string(),
|
||||
model_display: model_raw.clone(),
|
||||
provider: resolve_provider(&price_model, &alias2prov),
|
||||
from_env,
|
||||
is_secondary,
|
||||
input_other,
|
||||
output,
|
||||
input_cache_read: cache_read,
|
||||
input_cache_creation: cache_create,
|
||||
cost_usd: cost,
|
||||
cost_estimated: est,
|
||||
price_id: pid,
|
||||
});
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Aggregate raw usage records into the per-day, per-model snapshot stored
|
||||
/// for an archived session.
|
||||
fn snapshot_from_records(records: &[UsageRecord]) -> Vec<DayStat> {
|
||||
let mut by_day: HashMap<String, (u64, HashMap<String, DayModelStat>)> = HashMap::new();
|
||||
for r in records {
|
||||
let entry = by_day
|
||||
.entry(day_key(r.time))
|
||||
.or_insert_with(|| (local_midnight_ms(r.time, 0), HashMap::new()));
|
||||
let m = entry.1.entry(r.model.clone()).or_insert_with(|| DayModelStat {
|
||||
model: r.model.clone(),
|
||||
requests: 0,
|
||||
input_other: 0,
|
||||
output: 0,
|
||||
input_cache_read: 0,
|
||||
input_cache_creation: 0,
|
||||
cost_usd: 0.0,
|
||||
});
|
||||
m.requests += 1;
|
||||
m.input_other += r.input_other;
|
||||
m.output += r.output;
|
||||
m.input_cache_read += r.input_cache_read;
|
||||
m.input_cache_creation += r.input_cache_creation;
|
||||
m.cost_usd += r.cost_usd;
|
||||
}
|
||||
let mut days: Vec<DayStat> = by_day
|
||||
.into_iter()
|
||||
.map(|(day, (day_start_ms, models))| {
|
||||
let mut models: Vec<DayModelStat> = models.into_values().collect();
|
||||
models.sort_by(|a, b| a.model.cmp(&b.model));
|
||||
DayStat { day, day_start_ms, models }
|
||||
})
|
||||
.collect();
|
||||
days.sort_by(|a, b| a.day.cmp(&b.day));
|
||||
days
|
||||
}
|
||||
|
||||
/// Synthesize usage records from stored archive snapshots. Only snapshots
|
||||
/// whose session directory is gone are synthesized: sessions still on disk
|
||||
/// are covered by the live wire.jsonl scan, and emitting both would double
|
||||
/// count their usage.
|
||||
fn synthesize_snapshot_records(rows: &[ArchivedSessionSnapshot], home: &Path) -> Vec<UsageRecord> {
|
||||
let root = sessions_root(home);
|
||||
let legacy_root = root.join(".kcd-archive");
|
||||
let alias2prov = build_alias_provider_map(home);
|
||||
let secondary_alias = read_secondary_model_alias(home);
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if root.join(&row.workspace_id).join(&row.session_id).exists() { continue; }
|
||||
if legacy_root.join(&row.workspace_id).join(&row.session_id).exists() { continue; }
|
||||
for day in &row.day_stats {
|
||||
for m in &day.models {
|
||||
let is_secondary = m.model == "__secondary__";
|
||||
let price_model = if is_secondary {
|
||||
secondary_alias.clone().unwrap_or_else(|| m.model.clone())
|
||||
} else {
|
||||
m.model.clone()
|
||||
};
|
||||
let bare = m.model.rsplit_once('/').map(|x| x.1).unwrap_or(&m.model).to_string();
|
||||
out.push(UsageRecord {
|
||||
time: day.day_start_ms,
|
||||
model: m.model.clone(),
|
||||
model_resolved: bare,
|
||||
model_display: m.model.clone(),
|
||||
provider: resolve_provider(&price_model, &alias2prov),
|
||||
from_env: m.model == "__kimi_env_model__",
|
||||
is_secondary,
|
||||
input_other: m.input_other,
|
||||
output: m.output,
|
||||
input_cache_read: m.input_cache_read,
|
||||
input_cache_creation: m.input_cache_creation,
|
||||
cost_usd: m.cost_usd,
|
||||
cost_estimated: true,
|
||||
price_id: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Append the synthesized records for `rows` to a live scan result and
|
||||
/// restore the newest-first ordering `scan_usage` produces.
|
||||
fn merge_snapshot_records(
|
||||
mut records: Vec<UsageRecord>,
|
||||
rows: &[ArchivedSessionSnapshot],
|
||||
home: &Path,
|
||||
) -> Vec<UsageRecord> {
|
||||
// Nothing archived yet: keep the scan result untouched (and skip the
|
||||
// config reads the synthesis would do).
|
||||
if rows.is_empty() { return records; }
|
||||
records.extend(synthesize_snapshot_records(rows, home));
|
||||
records.sort_by(|a, b| b.time.cmp(&a.time));
|
||||
records
|
||||
}
|
||||
|
||||
/// Live scan records plus the stored usage of archived sessions whose files
|
||||
/// have been deleted, so dashboard stats survive session deletion.
|
||||
fn records_with_archive_merge(home: &Path, records: Vec<UsageRecord>) -> Vec<UsageRecord> {
|
||||
let rows = crate::db::list_archived_sessions().unwrap_or_default();
|
||||
merge_snapshot_records(records, &rows, home)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scan cache
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -976,6 +1104,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
||||
totals: TotalsRow::default(),
|
||||
daily: vec![],
|
||||
models: vec![],
|
||||
models_by_name: vec![],
|
||||
recent: vec![],
|
||||
recent_total: 0,
|
||||
recent_limit: 500,
|
||||
@@ -985,6 +1114,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
||||
let mut totals = TotalsRow::default();
|
||||
let mut by_day: HashMap<String, (TotalsRow, HashMap<String, TotalsRow>, HashMap<String, HashMap<String, u64>>)> = HashMap::new();
|
||||
let mut by_model: HashMap<String, (ModelRow, TotalsRow)> = HashMap::new();
|
||||
let mut by_name: HashMap<String, (ModelRow, TotalsRow)> = HashMap::new();
|
||||
|
||||
for r in &filtered {
|
||||
totals.add(r);
|
||||
@@ -1017,6 +1147,28 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
||||
entry.1.add(r);
|
||||
entry.0.cost_estimated = entry.0.cost_estimated || r.cost_estimated;
|
||||
entry.0.is_secondary = entry.0.is_secondary || r.is_secondary;
|
||||
|
||||
// Provider-agnostic bucket: secondary (subagent) records keep the
|
||||
// stable "__secondary__" marker; everything else keys on the bare
|
||||
// model name so the same model across providers merges into one row.
|
||||
let nk = if r.is_secondary { "__secondary__".to_string() } else { r.model_resolved.clone() };
|
||||
let name_entry = by_name.entry(nk.clone()).or_insert_with(|| {
|
||||
let m = ModelRow {
|
||||
model: nk.clone(),
|
||||
model_display: nk.clone(),
|
||||
model_resolved: nk.clone(),
|
||||
price_id: r.price_id.clone(),
|
||||
cost_estimated: r.cost_estimated,
|
||||
is_secondary: r.is_secondary,
|
||||
requests: 0, input_other: 0, output: 0,
|
||||
input_cache_read: 0, input_cache_creation: 0,
|
||||
cost_usd: 0.0, total_tokens: 0, cache_hit_rate: 0.0,
|
||||
};
|
||||
(m, TotalsRow::default())
|
||||
});
|
||||
name_entry.1.add(r);
|
||||
name_entry.0.cost_estimated = name_entry.0.cost_estimated || r.cost_estimated;
|
||||
name_entry.0.is_secondary = name_entry.0.is_secondary || r.is_secondary;
|
||||
}
|
||||
|
||||
let total_input = totals.input_other + totals.input_cache_read + totals.input_cache_creation;
|
||||
@@ -1063,6 +1215,17 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
||||
}).collect();
|
||||
models.sort_by(|a, b| b.total_tokens.cmp(&a.total_tokens));
|
||||
|
||||
let mut models_by_name: Vec<ModelRow> = by_name.into_iter().map(|(_, (mut m, t))| {
|
||||
let ti = t.input_other + t.input_cache_read + t.input_cache_creation;
|
||||
m.cache_hit_rate = if ti > 0 { t.input_cache_read as f64 / ti as f64 } else { 0.0 };
|
||||
m.requests = t.requests;
|
||||
m.input_other = t.input_other; m.output = t.output;
|
||||
m.input_cache_read = t.input_cache_read; m.input_cache_creation = t.input_cache_creation;
|
||||
m.cost_usd = t.cost_usd; m.total_tokens = t.total_tokens;
|
||||
m
|
||||
}).collect();
|
||||
models_by_name.sort_by(|a, b| b.total_tokens.cmp(&a.total_tokens));
|
||||
|
||||
let recent_total = filtered.len();
|
||||
let recent_limit = 500;
|
||||
let recent: Vec<RecentRow> = filtered.iter().take(recent_limit).map(|r| RecentRow {
|
||||
@@ -1081,6 +1244,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
||||
totals,
|
||||
daily,
|
||||
models,
|
||||
models_by_name,
|
||||
recent,
|
||||
recent_total,
|
||||
recent_limit,
|
||||
@@ -1109,24 +1273,40 @@ impl TotalsRow {
|
||||
fn filter_by_range<'a>(records: &'a [UsageRecord], range: &str, now_ms: u64) -> Vec<&'a UsageRecord> {
|
||||
if range == "all" { return records.iter().collect(); }
|
||||
let start = range_start(range, now_ms);
|
||||
records.iter().filter(|r| r.time >= start).collect()
|
||||
match range_end(range, now_ms) {
|
||||
Some(end) => records.iter().filter(|r| r.time >= start && r.time < end).collect(),
|
||||
None => records.iter().filter(|r| r.time >= start).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound (exclusive) for bounded ranges. Only "yesterday" has one —
|
||||
/// it must not bleed into today.
|
||||
fn range_end(range: &str, now_ms: u64) -> Option<u64> {
|
||||
match range {
|
||||
"yesterday" => Some(local_midnight_ms(now_ms, 0)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// LOCAL midnight `days_ago` days before today, in epoch ms. Not UTC midnight:
|
||||
/// without local-midnight anchoring, users east of UTC see day boundaries at
|
||||
/// the wrong hour (e.g. UTC+8 users get cutoff at local 08:00).
|
||||
fn local_midnight_ms(now_ms: u64, days_ago: i64) -> u64 {
|
||||
let now_utc = DateTime::from_timestamp((now_ms / 1000) as i64, 0).unwrap_or_default();
|
||||
let now_local = now_utc.with_timezone(&Local);
|
||||
let date = now_local.date_naive() - chrono::Duration::days(days_ago);
|
||||
let day_start = date.and_hms_opt(0, 0, 0).unwrap_or_default();
|
||||
Local
|
||||
.from_local_datetime(&day_start)
|
||||
.single()
|
||||
.map(|dt| dt.timestamp() as u64 * 1000)
|
||||
.unwrap_or_else(|| day_start.and_utc().timestamp() as u64 * 1000)
|
||||
}
|
||||
|
||||
fn range_start(range: &str, now_ms: u64) -> u64 {
|
||||
match range {
|
||||
"today" => {
|
||||
// LOCAL midnight today — not UTC midnight. Without this, users east of UTC see
|
||||
// "today" begin at the wrong hour (e.g. UTC+8 users get cutoff at local 08:00).
|
||||
let now_utc = DateTime::from_timestamp((now_ms / 1000) as i64, 0).unwrap_or_default();
|
||||
let now_local = now_utc.with_timezone(&Local);
|
||||
let today_date = now_local.date_naive();
|
||||
let today_start = today_date.and_hms_opt(0, 0, 0).unwrap_or_default();
|
||||
Local
|
||||
.from_local_datetime(&today_start)
|
||||
.single()
|
||||
.map(|dt| dt.timestamp() as u64 * 1000)
|
||||
.unwrap_or_else(|| today_start.and_utc().timestamp() as u64 * 1000)
|
||||
}
|
||||
"today" => local_midnight_ms(now_ms, 0),
|
||||
"yesterday" => local_midnight_ms(now_ms, 1),
|
||||
"7d" => now_ms - 7 * 24 * 3600 * 1000,
|
||||
"30d" => now_ms - 30 * 24 * 3600 * 1000,
|
||||
_ => now_ms - 30 * 24 * 3600 * 1000,
|
||||
@@ -1277,6 +1457,147 @@ fn set_session_archived_meta(session_dir: &Path, archived: bool) -> Result<(), S
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse a `state.json` timestamp into epoch ms. kimi-code writes epoch-ms
|
||||
/// numbers, other builds write ISO-8601 strings — accept both, plus numeric
|
||||
/// strings.
|
||||
fn parse_state_time_ms(value: &serde_json::Value) -> Option<u64> {
|
||||
match value {
|
||||
serde_json::Value::Number(n) => n.as_u64().or_else(|| n.as_f64().map(|f| f.max(0.0) as u64)),
|
||||
serde_json::Value::String(s) => parse_time_string_ms(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_time_string_ms(s: &str) -> Option<u64> {
|
||||
let t = s.trim();
|
||||
if t.is_empty() { return None; }
|
||||
if let Ok(n) = t.parse::<u64>() {
|
||||
// Numeric string: epoch ms when it is already millisecond-sized.
|
||||
return Some(if n >= 1e12 as u64 { n } else { n * 1000 });
|
||||
}
|
||||
if let Ok(dt) = DateTime::parse_from_rfc3339(t) {
|
||||
return Some(dt.timestamp_millis().max(0) as u64);
|
||||
}
|
||||
for fmt in [
|
||||
"%Y-%m-%dT%H:%M:%S%.f",
|
||||
"%Y-%m-%dT%H:%M:%S",
|
||||
"%Y-%m-%d %H:%M:%S%.f",
|
||||
"%Y-%m-%d %H:%M:%S",
|
||||
] {
|
||||
if let Ok(naive) = chrono::NaiveDateTime::parse_from_str(t, fmt) {
|
||||
return Some(naive.and_utc().timestamp_millis().max(0) as u64);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read a session's `state.json` as a JSON object (None when missing or
|
||||
/// unparseable).
|
||||
fn read_state_obj(session_dir: &Path) -> Option<serde_json::Value> {
|
||||
let content = fs::read_to_string(session_dir.join("state.json")).ok()?;
|
||||
let obj: serde_json::Value = serde_json::from_str(&content).ok()?;
|
||||
if obj.is_object() { Some(obj) } else { None }
|
||||
}
|
||||
|
||||
/// Session directory mtime in epoch ms — the fallback when `state.json` has
|
||||
/// no parseable `updatedAt`.
|
||||
fn dir_mtime_ms(dir: &Path) -> Option<u64> {
|
||||
dir.metadata().ok().and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
}
|
||||
|
||||
/// Usage records of one session: every `wire.jsonl` below its directory
|
||||
/// (agent subdirectories included), with the same blob/task filtering the
|
||||
/// full-tree scan applies.
|
||||
fn parse_session_wire_usage(
|
||||
dir: &Path,
|
||||
secondary_alias: &Option<String>,
|
||||
alias2prov: &HashMap<String, String>,
|
||||
) -> Vec<UsageRecord> {
|
||||
let mut records = Vec::new();
|
||||
for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
|
||||
if entry.file_name() != "wire.jsonl" || !entry.file_type().is_file() { continue; }
|
||||
let p = entry.path();
|
||||
if p.to_string_lossy().contains("blobs") || p.to_string_lossy().contains("tasks") { continue; }
|
||||
let Ok(content) = fs::read_to_string(p) else { continue };
|
||||
records.extend(parse_wire_usage_records(&content, secondary_alias, alias2prov));
|
||||
}
|
||||
records
|
||||
}
|
||||
|
||||
/// Bulk-archive every active session whose last activity predates `cutoff_ms`
|
||||
/// (epoch ms) and store a usage snapshot per session in SQLite, so dashboard
|
||||
/// stats keep counting their history after the directories are deleted.
|
||||
/// Sessions already archived, in `.kcd-archive`, or without a readable
|
||||
/// `state.json` are left alone.
|
||||
fn archive_sessions_before_cmd(home: &Path, cutoff_ms: u64) -> BulkArchiveResult {
|
||||
let root = sessions_root(home);
|
||||
let alias2prov = build_alias_provider_map(home);
|
||||
let secondary_alias = read_secondary_model_alias(home);
|
||||
let now_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64;
|
||||
let mut result = BulkArchiveResult { archived: 0, skipped: 0, errors: Vec::new() };
|
||||
|
||||
for wid in list_workspace_dirs(home) {
|
||||
for entry in safe_read_dir(&root.join(&wid)) {
|
||||
if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) { continue; }
|
||||
let sid = entry.file_name().to_string_lossy().to_string();
|
||||
if !session_re().is_match(&sid) { continue; }
|
||||
let dir = entry.path();
|
||||
let Some(state) = read_state_obj(&dir) else {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
};
|
||||
if state.get("archived").and_then(|v| v.as_bool()).unwrap_or(false) { continue; }
|
||||
let Some(updated_ms) = state
|
||||
.get("updatedAt")
|
||||
.and_then(parse_state_time_ms)
|
||||
.or_else(|| dir_mtime_ms(&dir))
|
||||
else {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
};
|
||||
if updated_ms >= cutoff_ms {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(e) = set_session_archived_meta(&dir, true) {
|
||||
result.errors.push(format!("{wid}/{sid}: {e}"));
|
||||
continue;
|
||||
}
|
||||
let day_stats = snapshot_from_records(&parse_session_wire_usage(
|
||||
&dir, &secondary_alias, &alias2prov,
|
||||
));
|
||||
let mut total_tokens = 0u64;
|
||||
let mut total_cost_usd = 0.0f64;
|
||||
for day in &day_stats {
|
||||
for m in &day.models {
|
||||
total_tokens += m.input_other + m.output + m.input_cache_read + m.input_cache_creation;
|
||||
total_cost_usd += m.cost_usd;
|
||||
}
|
||||
}
|
||||
let snapshot = ArchivedSessionSnapshot {
|
||||
session_id: sid.clone(),
|
||||
workspace_id: wid.clone(),
|
||||
title: state.get("title").and_then(|v| v.as_str()).map(|s| s.to_string()),
|
||||
archived_at_ms: now_ms,
|
||||
updated_at_ms: Some(updated_ms),
|
||||
created_at_ms: state.get("createdAt").and_then(parse_state_time_ms),
|
||||
total_tokens,
|
||||
total_cost_usd,
|
||||
day_stats,
|
||||
};
|
||||
result.archived += 1;
|
||||
if let Err(e) = crate::db::upsert_archived_session(&snapshot) {
|
||||
result.errors.push(format!("{wid}/{sid}: snapshot: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn humanize_workspace(id: &str) -> String {
|
||||
let re = Regex::new(r"^wd_(.+)_[0-9a-fA-F]{8,}$").unwrap();
|
||||
if let Some(caps) = re.captures(id) {
|
||||
@@ -1821,6 +2142,7 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
|
||||
let r = range.unwrap_or_else(|| "30d".into());
|
||||
|
||||
let (records, meta) = scan_usage_cached(&home, refresh);
|
||||
let records = records_with_archive_merge(&home, records);
|
||||
let t1 = std::time::Instant::now();
|
||||
let stats = aggregate(&records, &r, now_ms);
|
||||
let all_stats = aggregate(&records, "all", now_ms);
|
||||
@@ -1836,7 +2158,7 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
|
||||
|
||||
let all_model_count = all_models.len();
|
||||
let mut range_totals = HashMap::new();
|
||||
for r_k in ["today", "7d", "30d", "all"] {
|
||||
for r_k in ["today", "yesterday", "7d", "30d", "all"] {
|
||||
let s = aggregate(&records, r_k, now_ms);
|
||||
range_totals.insert(r_k.to_string(), s.totals);
|
||||
}
|
||||
@@ -1928,6 +2250,7 @@ fn build_day_detail(date: &str, records: &[UsageRecord]) -> Option<DailyRow> {
|
||||
pub fn get_day_detail(home_override: Option<String>, date: String) -> Option<DailyRow> {
|
||||
let home = resolve_kimi_home(home_override);
|
||||
let (records, _) = scan_usage_cached(&home, false);
|
||||
let records = records_with_archive_merge(&home, records);
|
||||
build_day_detail(&date, &records)
|
||||
}
|
||||
|
||||
@@ -1943,6 +2266,14 @@ pub fn archive_session(home_override: Option<String>, workspace_id: String, sess
|
||||
archive_session_cmd(&home, &workspace_id, &session_id)
|
||||
}
|
||||
|
||||
/// Bulk-archive every active session whose last activity predates `cutoff_ms`
|
||||
/// (epoch ms) across all workspaces, storing a usage snapshot per session.
|
||||
#[tauri::command]
|
||||
pub fn archive_sessions_before(home_override: Option<String>, cutoff_ms: u64) -> BulkArchiveResult {
|
||||
let home = resolve_kimi_home(home_override);
|
||||
archive_sessions_before_cmd(&home, cutoff_ms)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn unarchive_session(home_override: Option<String>, workspace_id: String, session_id: String) -> Result<ActionResponse, String> {
|
||||
let home = resolve_kimi_home(home_override);
|
||||
@@ -1977,10 +2308,10 @@ mod pricing_tests {
|
||||
let idx = models_dev_cost_index();
|
||||
// The compiled-in snapshot must carry real models.dev prices.
|
||||
assert!(idx.len() > 1000, "expected >1000 priced models, got {}", idx.len());
|
||||
let kimi = idx.get("moonshotai/kimi-k2.5").copied().expect("kimi-k2.5 present");
|
||||
assert_eq!(kimi.input, 0.6);
|
||||
assert_eq!(kimi.output, 3.0);
|
||||
assert_eq!(kimi.cache_read, 0.1);
|
||||
let kimi = idx.get("moonshotai/kimi-k3").copied().expect("kimi-k3 present");
|
||||
assert_eq!(kimi.input, 3.0);
|
||||
assert_eq!(kimi.output, 15.0);
|
||||
assert_eq!(kimi.cache_read, 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1992,9 +2323,9 @@ mod pricing_tests {
|
||||
assert_eq!(input, 0.6);
|
||||
assert_eq!(output, 2.2);
|
||||
|
||||
let (id, _, _, _, est) = match_price("kimi/k2.5");
|
||||
let (id, _, _, _, est) = match_price("kimi/k3");
|
||||
assert!(!est);
|
||||
assert_eq!(id, "moonshotai/kimi-k2.5");
|
||||
assert_eq!(id, "moonshotai/kimi-k3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2018,8 +2349,8 @@ mod pricing_tests {
|
||||
let (id, _, input, output, est) = match_price("CodingPlan.site/deepseek-v4-flash");
|
||||
assert!(!est, "resolved via models.dev, not estimated");
|
||||
assert_eq!(id, "deepseek/deepseek-v4-flash");
|
||||
assert_eq!(input, 0.14);
|
||||
assert_eq!(output, 0.28);
|
||||
assert_eq!(input, 0.15);
|
||||
assert_eq!(output, 0.6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2307,3 +2638,341 @@ mod session_tests {
|
||||
assert!(list_sessions_cmd(&home, "all", None).sessions.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod range_and_model_totals_tests {
|
||||
use super::*;
|
||||
|
||||
fn rec(time: u64, model: &str, resolved: &str, secondary: bool) -> UsageRecord {
|
||||
UsageRecord {
|
||||
time,
|
||||
model: model.to_string(),
|
||||
input_other: 100,
|
||||
output: 50,
|
||||
input_cache_read: 50,
|
||||
input_cache_creation: 0,
|
||||
cost_usd: 0.01,
|
||||
cost_estimated: false,
|
||||
price_id: String::new(),
|
||||
model_resolved: resolved.to_string(),
|
||||
model_display: model.to_string(),
|
||||
provider: None,
|
||||
from_env: false,
|
||||
is_secondary: secondary,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yesterday_range_is_bounded_to_yesterday() {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
|
||||
let today_start = local_midnight_ms(now, 0);
|
||||
let yesterday_start = local_midnight_ms(now, 1);
|
||||
assert!(yesterday_start < today_start, "yesterday midnight precedes today's");
|
||||
assert_eq!(range_end("yesterday", now), Some(today_start));
|
||||
assert_eq!(range_end("today", now), None);
|
||||
assert_eq!(range_end("7d", now), None);
|
||||
|
||||
let records = vec![
|
||||
rec(yesterday_start + 1, "a/m1", "m1", false), // yesterday → in
|
||||
rec(today_start + 1, "a/m1", "m1", false), // today → out
|
||||
rec(yesterday_start.saturating_sub(1), "a/m1", "m1", false), // before → out
|
||||
];
|
||||
let stats = aggregate(&records, "yesterday", now);
|
||||
assert_eq!(stats.totals.requests, 1, "only yesterday's record counts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_by_name_merges_providers_and_keeps_secondary() {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
|
||||
let records = vec![
|
||||
rec(now, "openai/gpt-x", "gpt-x", false),
|
||||
rec(now, "azure/gpt-x", "gpt-x", false),
|
||||
rec(now, "__secondary__", "__secondary__", true),
|
||||
];
|
||||
let stats = aggregate(&records, "all", now);
|
||||
|
||||
// by_model keeps provider-qualified rows separate
|
||||
assert_eq!(stats.models.len(), 3);
|
||||
// by_name merges the two gpt-x rows, subagent stays its own row
|
||||
assert_eq!(stats.models_by_name.len(), 2);
|
||||
let gptx = stats.models_by_name.iter().find(|m| m.model == "gpt-x").expect("merged gpt-x row");
|
||||
assert_eq!(gptx.requests, 2);
|
||||
assert_eq!(gptx.total_tokens, 2 * 200);
|
||||
let sub = stats.models_by_name.iter().find(|m| m.model == "__secondary__").expect("secondary row");
|
||||
assert!(sub.is_secondary);
|
||||
// sorted by total_tokens desc — every record has equal tokens here, so
|
||||
// just assert the set is complete and totals add up.
|
||||
let total: u64 = stats.models_by_name.iter().map(|m| m.total_tokens).sum();
|
||||
assert_eq!(total, 3 * 200);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod archive_snapshot_tests {
|
||||
use super::*;
|
||||
|
||||
const WID: &str = "wd_proj_a1b2c3d4e5f6";
|
||||
const LIVE_SID: &str = "session_11111111-2222-3333-4444-555555555555";
|
||||
const GONE_SID: &str = "session_99999999-8888-7777-6666-555555555555";
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64
|
||||
}
|
||||
|
||||
fn rec(time: u64, model: &str, tokens: (u64, u64, u64, u64), cost: f64) -> UsageRecord {
|
||||
UsageRecord {
|
||||
time,
|
||||
model: model.to_string(),
|
||||
input_other: tokens.0,
|
||||
output: tokens.1,
|
||||
input_cache_read: tokens.2,
|
||||
input_cache_creation: tokens.3,
|
||||
cost_usd: cost,
|
||||
cost_estimated: false,
|
||||
price_id: String::new(),
|
||||
model_resolved: model.rsplit_once('/').map(|x| x.1).unwrap_or(model).to_string(),
|
||||
model_display: model.to_string(),
|
||||
provider: None,
|
||||
from_env: false,
|
||||
is_secondary: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot_row(
|
||||
sid: &str,
|
||||
day_start_ms: u64,
|
||||
model: &str,
|
||||
tokens: u64,
|
||||
) -> ArchivedSessionSnapshot {
|
||||
ArchivedSessionSnapshot {
|
||||
session_id: sid.to_string(),
|
||||
workspace_id: WID.to_string(),
|
||||
title: None,
|
||||
archived_at_ms: 0,
|
||||
updated_at_ms: None,
|
||||
created_at_ms: None,
|
||||
total_tokens: tokens,
|
||||
total_cost_usd: 0.0,
|
||||
day_stats: vec![DayStat {
|
||||
day: day_key(day_start_ms),
|
||||
day_start_ms,
|
||||
models: vec![DayModelStat {
|
||||
model: model.to_string(),
|
||||
requests: 2,
|
||||
input_other: tokens,
|
||||
output: 0,
|
||||
input_cache_read: 0,
|
||||
input_cache_creation: 0,
|
||||
cost_usd: 1.5,
|
||||
}],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn write_state(dir: &Path, updated_ms: u64, archived: bool) {
|
||||
let state = serde_json::json!({
|
||||
"id": dir.file_name().unwrap().to_string_lossy(),
|
||||
"createdAt": updated_ms,
|
||||
"updatedAt": updated_ms,
|
||||
"archived": archived,
|
||||
"title": "archived candidate",
|
||||
});
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
}
|
||||
|
||||
fn read_state(dir: &Path) -> serde_json::Value {
|
||||
serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_groups_records_by_local_day_and_model() {
|
||||
let now = now_ms();
|
||||
let d1 = local_midnight_ms(now, 2);
|
||||
let d2 = local_midnight_ms(now, 1);
|
||||
let records = vec![
|
||||
rec(d1 + 3_600_000, "openai/gpt-x", (100, 10, 5, 1), 0.5),
|
||||
rec(d1 + 7_200_000, "openai/gpt-x", (200, 20, 0, 0), 0.25),
|
||||
rec(d1 + 60_000, "moonshotai/kimi-k3", (1, 2, 3, 4), 0.01),
|
||||
rec(d2 + 1_000, "openai/gpt-x", (7, 7, 7, 7), 0.07),
|
||||
];
|
||||
let days = snapshot_from_records(&records);
|
||||
assert_eq!(days.len(), 2, "one bucket per local day");
|
||||
|
||||
let first = &days[0];
|
||||
assert_eq!(first.day, day_key(d1));
|
||||
assert_eq!(first.day_start_ms, d1, "day bucket starts at local midnight");
|
||||
assert_eq!(first.models.len(), 2);
|
||||
let gpt = first.models.iter().find(|m| m.model == "openai/gpt-x").unwrap();
|
||||
assert_eq!(gpt.requests, 2);
|
||||
assert_eq!(gpt.input_other, 300);
|
||||
assert_eq!(gpt.output, 30);
|
||||
assert_eq!(gpt.input_cache_read, 5);
|
||||
assert_eq!(gpt.input_cache_creation, 1);
|
||||
assert_eq!(gpt.cost_usd, 0.75);
|
||||
// Deterministic ordering: models sorted by raw model key.
|
||||
assert_eq!(first.models[0].model, "moonshotai/kimi-k3");
|
||||
|
||||
assert_eq!(days[1].day, day_key(d2));
|
||||
assert_eq!(days[1].day_start_ms, d2);
|
||||
assert_eq!(days[1].models.len(), 1);
|
||||
assert_eq!(days[1].models[0].input_other, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthesize_only_covers_sessions_whose_files_are_gone() {
|
||||
let td = tempfile::tempdir().unwrap();
|
||||
let home = td.path().join("home");
|
||||
fs::create_dir_all(home.join("sessions").join(WID).join(LIVE_SID)).unwrap();
|
||||
|
||||
let day_start = 1_700_000_000_000u64;
|
||||
let rows = vec![
|
||||
snapshot_row(LIVE_SID, day_start, "openai/gpt-x", 100),
|
||||
snapshot_row(GONE_SID, day_start, "openai/gpt-x", 200),
|
||||
];
|
||||
let out = synthesize_snapshot_records(&rows, &home);
|
||||
assert_eq!(out.len(), 1, "live session dirs stay with the live scan");
|
||||
|
||||
let r = &out[0];
|
||||
assert_eq!(r.time, day_start);
|
||||
assert_eq!(r.model, "openai/gpt-x");
|
||||
assert_eq!(r.model_resolved, "gpt-x");
|
||||
assert_eq!(r.model_display, "openai/gpt-x");
|
||||
assert_eq!(r.provider.as_deref(), Some("openai"));
|
||||
assert_eq!(r.input_other, 200);
|
||||
assert_eq!(r.cost_usd, 1.5);
|
||||
assert!(r.cost_estimated, "snapshot costs are estimates");
|
||||
assert_eq!(r.price_id, "");
|
||||
assert!(!r.is_secondary);
|
||||
assert!(!r.from_env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_appends_missing_sessions_newest_first_without_double_counting() {
|
||||
let td = tempfile::tempdir().unwrap();
|
||||
let home = td.path().join("home");
|
||||
fs::create_dir_all(home.join("sessions").join(WID).join(LIVE_SID)).unwrap();
|
||||
|
||||
let now = now_ms();
|
||||
let old_day = local_midnight_ms(now, 5);
|
||||
let new_day = local_midnight_ms(now, 1);
|
||||
let gone_old = "session_22222222-2222-3333-4444-555555555555";
|
||||
let gone_new = "session_33333333-2222-3333-4444-555555555555";
|
||||
let rows = vec![
|
||||
snapshot_row(LIVE_SID, new_day, "openai/gpt-x", 999),
|
||||
snapshot_row(gone_old, old_day, "openai/gpt-x", 10),
|
||||
snapshot_row(gone_new, new_day, "openai/gpt-x", 20),
|
||||
];
|
||||
let live = vec![rec(new_day + 5_000, "openai/gpt-x", (1, 1, 1, 1), 0.01)];
|
||||
let merged = merge_snapshot_records(live, &rows, &home);
|
||||
|
||||
assert_eq!(merged.len(), 3, "live record plus the two missing sessions");
|
||||
assert_eq!(merged[0].time, new_day + 5_000, "newest record first");
|
||||
assert_eq!(merged[1].time, new_day);
|
||||
assert_eq!(merged[2].time, old_day);
|
||||
assert_eq!(merged[1].input_other, 20);
|
||||
assert_eq!(merged[2].input_other, 10);
|
||||
assert!(
|
||||
merged.iter().all(|r| r.input_other != 999),
|
||||
"a live session's stored snapshot must never be synthesized"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_times_parse_epoch_numbers_and_iso_strings() {
|
||||
assert_eq!(
|
||||
parse_state_time_ms(&serde_json::json!(1_700_000_000_000u64)),
|
||||
Some(1_700_000_000_000)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_state_time_ms(&serde_json::json!("1700000000000")),
|
||||
Some(1_700_000_000_000)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_state_time_ms(&serde_json::json!("2025-01-02T03:04:05.000Z")),
|
||||
Some(1_735_787_045_000)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_state_time_ms(&serde_json::json!("2025-01-02T03:04:05")),
|
||||
Some(1_735_787_045_000)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_state_time_ms(&serde_json::json!("2025-01-02 03:04:05")),
|
||||
Some(1_735_787_045_000)
|
||||
);
|
||||
assert_eq!(parse_state_time_ms(&serde_json::json!(null)), None);
|
||||
assert_eq!(parse_state_time_ms(&serde_json::json!("not-a-date")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_archive_flags_old_sessions_and_snapshots_their_usage() {
|
||||
let td = tempfile::tempdir().unwrap();
|
||||
let home = td.path().join("home");
|
||||
// Redirect the SQLite store so the test never touches the user's DB.
|
||||
std::env::set_var("KIMI_SWITCH_DB_PATH", td.path().join("test.db"));
|
||||
|
||||
let ws = home.join("sessions").join(WID);
|
||||
let now = now_ms();
|
||||
let old_ms = now - 60 * 24 * 3600 * 1000;
|
||||
|
||||
let old_dir = ws.join(LIVE_SID);
|
||||
fs::create_dir_all(&old_dir).unwrap();
|
||||
write_state(&old_dir, old_ms, false);
|
||||
let wire = serde_json::json!({
|
||||
"type": "usage.record",
|
||||
"usageScope": "turn",
|
||||
"time": old_ms,
|
||||
"model": "openai/gpt-x",
|
||||
"usage": {
|
||||
"inputOther": 100,
|
||||
"output": 50,
|
||||
"inputCacheRead": 10,
|
||||
"inputCacheCreation": 5,
|
||||
},
|
||||
});
|
||||
fs::write(old_dir.join("wire.jsonl"), format!("{wire}\n")).unwrap();
|
||||
|
||||
let new_sid = "session_44444444-2222-3333-4444-555555555555";
|
||||
let new_dir = ws.join(new_sid);
|
||||
fs::create_dir_all(&new_dir).unwrap();
|
||||
write_state(&new_dir, now - 3_600_000, false);
|
||||
|
||||
let cutoff = now - 30 * 24 * 3600 * 1000;
|
||||
let res = archive_sessions_before_cmd(&home, cutoff);
|
||||
assert_eq!(res.archived, 1, "only the stale session is archived");
|
||||
assert_eq!(res.skipped, 1, "the recent session is reported as skipped");
|
||||
assert!(res.errors.is_empty(), "{:?}", res.errors);
|
||||
|
||||
// Metadata archive happened in place, the recent session is untouched.
|
||||
assert_eq!(read_state(&old_dir)["archived"], true);
|
||||
assert!(read_state(&old_dir)["archivedAt"].as_u64().unwrap() > 0);
|
||||
assert_eq!(read_state(&new_dir)["archived"], false);
|
||||
|
||||
// Usage snapshot landed in SQLite with the session's totals.
|
||||
let rows = crate::db::list_archived_sessions().unwrap();
|
||||
let row = rows.iter().find(|r| r.session_id == LIVE_SID).expect("snapshot row");
|
||||
assert_eq!(row.workspace_id, WID);
|
||||
assert_eq!(row.title.as_deref(), Some("archived candidate"));
|
||||
assert_eq!(row.updated_at_ms, Some(old_ms));
|
||||
assert_eq!(row.total_tokens, 165);
|
||||
assert!(row.total_cost_usd > 0.0);
|
||||
assert_eq!(row.day_stats.len(), 1);
|
||||
assert_eq!(row.day_stats[0].day, day_key(old_ms));
|
||||
assert_eq!(row.day_stats[0].models[0].requests, 1);
|
||||
assert_eq!(row.day_stats[0].models[0].input_other, 100);
|
||||
|
||||
// While the files are still there, the live scan owns the usage.
|
||||
let merged = records_with_archive_merge(&home, vec![]);
|
||||
assert!(merged.is_empty(), "no synthesized records while the dir exists");
|
||||
|
||||
// Once the archived directory is deleted, stats come from the snapshot.
|
||||
fs::remove_dir_all(&old_dir).unwrap();
|
||||
let merged = records_with_archive_merge(&home, vec![]);
|
||||
assert_eq!(merged.len(), 1);
|
||||
assert_eq!(merged[0].input_other, 100);
|
||||
assert_eq!(merged[0].output, 50);
|
||||
assert_eq!(day_key(merged[0].time), day_key(old_ms));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use std::path::PathBuf;
|
||||
use anyhow::Context;
|
||||
use indexmap::IndexMap;
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::models::{Agent, Config, Model, Provider, ProviderType};
|
||||
@@ -23,6 +24,13 @@ pub fn kimi_switch_data_dir() -> PathBuf {
|
||||
}
|
||||
|
||||
pub fn db_path() -> PathBuf {
|
||||
// Tests (and power users) can point the store elsewhere; production always
|
||||
// resolves to the default location under the home directory.
|
||||
if let Some(p) = std::env::var_os("KIMI_SWITCH_DB_PATH") {
|
||||
if !p.is_empty() {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
}
|
||||
kimi_switch_data_dir().join("kimi-switch.db")
|
||||
}
|
||||
|
||||
@@ -31,6 +39,10 @@ pub fn db_path() -> PathBuf {
|
||||
/// configuration. Safe to call on every startup — it is a no-op once the new
|
||||
/// directory exists.
|
||||
fn migrate_legacy_data_dir() {
|
||||
// A redirected store (tests) must never touch the real home directory.
|
||||
if std::env::var_os("KIMI_SWITCH_DB_PATH").is_some() {
|
||||
return;
|
||||
}
|
||||
let new_dir = kimi_switch_data_dir();
|
||||
if new_dir.exists() {
|
||||
return;
|
||||
@@ -106,6 +118,24 @@ pub fn init_db() -> DbResult<Connection> {
|
||||
[],
|
||||
)?;
|
||||
|
||||
// Usage snapshots taken when sessions are bulk-archived: keep the session's
|
||||
// token/cost history queryable after its directory (and wire.jsonl) is
|
||||
// deleted from disk.
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS archived_sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
workspace_id TEXT NOT NULL,
|
||||
title TEXT,
|
||||
archived_at_ms INTEGER NOT NULL,
|
||||
updated_at_ms INTEGER,
|
||||
created_at_ms INTEGER,
|
||||
total_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd REAL NOT NULL DEFAULT 0,
|
||||
day_stats TEXT NOT NULL DEFAULT '[]'
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
|
||||
// Add icon columns for provider icon picker (introduced in v0.3.1).
|
||||
// SQLite has no ADD COLUMN IF NOT EXISTS, so ignore duplicate-column errors.
|
||||
for stmt in [
|
||||
@@ -330,6 +360,104 @@ pub fn delete_setting_pub(key: &str) -> DbResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Archived-session usage snapshots
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Per-model usage totals for one calendar day of an archived session.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DayModelStat {
|
||||
/// Raw model key as written to wire.jsonl (`__secondary__` kept verbatim).
|
||||
pub model: String,
|
||||
pub requests: u64,
|
||||
pub input_other: u64,
|
||||
pub output: u64,
|
||||
pub input_cache_read: u64,
|
||||
pub input_cache_creation: u64,
|
||||
pub cost_usd: f64,
|
||||
}
|
||||
|
||||
/// One day's per-model usage, stored as JSON in `archived_sessions.day_stats`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DayStat {
|
||||
/// Local calendar day, `YYYY-MM-DD`.
|
||||
pub day: String,
|
||||
/// Local midnight of `day`, epoch ms — used as the synthesized record time.
|
||||
pub day_start_ms: u64,
|
||||
pub models: Vec<DayModelStat>,
|
||||
}
|
||||
|
||||
/// Usage snapshot of one session, taken at the moment it is archived.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ArchivedSessionSnapshot {
|
||||
pub session_id: String,
|
||||
pub workspace_id: String,
|
||||
pub title: Option<String>,
|
||||
pub archived_at_ms: u64,
|
||||
pub updated_at_ms: Option<u64>,
|
||||
pub created_at_ms: Option<u64>,
|
||||
pub total_tokens: u64,
|
||||
pub total_cost_usd: f64,
|
||||
pub day_stats: Vec<DayStat>,
|
||||
}
|
||||
|
||||
/// Insert or replace one archived-session snapshot (keyed by session id, which
|
||||
/// is a UUID and never reused).
|
||||
pub fn upsert_archived_session(row: &ArchivedSessionSnapshot) -> DbResult<()> {
|
||||
let conn = init_db()?;
|
||||
let day_stats = serde_json::to_string(&row.day_stats)?;
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO archived_sessions
|
||||
(session_id, workspace_id, title, archived_at_ms, updated_at_ms, created_at_ms, total_tokens, total_cost_usd, day_stats)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
params![
|
||||
row.session_id,
|
||||
row.workspace_id,
|
||||
row.title,
|
||||
row.archived_at_ms as i64,
|
||||
row.updated_at_ms.map(|v| v as i64),
|
||||
row.created_at_ms.map(|v| v as i64),
|
||||
row.total_tokens as i64,
|
||||
row.total_cost_usd,
|
||||
day_stats,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every stored archived-session snapshot. Unreadable `day_stats` JSON degrades
|
||||
/// to an empty breakdown instead of failing the whole list.
|
||||
pub fn list_archived_sessions() -> DbResult<Vec<ArchivedSessionSnapshot>> {
|
||||
let conn = init_db()?;
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT session_id, workspace_id, title, archived_at_ms, updated_at_ms, created_at_ms,
|
||||
total_tokens, total_cost_usd, day_stats
|
||||
FROM archived_sessions",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
let day_stats_json: String = row.get(8)?;
|
||||
Ok(ArchivedSessionSnapshot {
|
||||
session_id: row.get(0)?,
|
||||
workspace_id: row.get(1)?,
|
||||
title: row.get(2)?,
|
||||
archived_at_ms: row.get::<_, i64>(3)? as u64,
|
||||
updated_at_ms: row.get::<_, Option<i64>>(4)?.map(|v| v as u64),
|
||||
created_at_ms: row.get::<_, Option<i64>>(5)?.map(|v| v as u64),
|
||||
total_tokens: row.get::<_, i64>(6)? as u64,
|
||||
total_cost_usd: row.get(7)?,
|
||||
day_stats: serde_json::from_str(&day_stats_json).unwrap_or_default(),
|
||||
})
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(row?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn provider_type_for_str(s: &str) -> ProviderType {
|
||||
ProviderType::from_kimi_type(s)
|
||||
}
|
||||
@@ -236,6 +236,30 @@ pub fn kimi_code_to_config(value: &TomlValue) -> Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// opencode Console Go (the "Go 套餐" gateway) rejects requests that lack an
|
||||
/// `x-opencode-session` header (400: required for routing and prompt-cache
|
||||
/// affinity). When exporting a provider pointing at the Go endpoint, ensure
|
||||
/// the header exists; an existing user-set value is kept as-is.
|
||||
fn ensure_opencode_go_session_header(provider: &Provider, pt: &mut Table) {
|
||||
let is_go = provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.map(|u| u.trim_end_matches('/').starts_with("https://opencode.ai/zen/go"))
|
||||
.unwrap_or(false);
|
||||
if !is_go {
|
||||
return;
|
||||
}
|
||||
let mut headers = pt
|
||||
.get("custom_headers")
|
||||
.and_then(|v| v.as_table())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
headers
|
||||
.entry("x-opencode-session".to_string())
|
||||
.or_insert_with(|| TomlValue::String("kimi-switch".to_string()));
|
||||
pt.insert("custom_headers".to_string(), TomlValue::Table(headers));
|
||||
}
|
||||
|
||||
/// Export Kimi Switch's internal `Config` to a Kimi Code TOML config value.
|
||||
///
|
||||
/// If `existing` is provided, unknown top-level sections (e.g. `services`) are
|
||||
@@ -316,6 +340,7 @@ pub fn config_to_kimi_code(config: &Config, existing: Option<&TomlValue>) -> Tom
|
||||
pt.insert(k, v);
|
||||
}
|
||||
}
|
||||
ensure_opencode_go_session_header(provider, &mut pt);
|
||||
providers_table.insert(name.clone(), TomlValue::Table(pt));
|
||||
}
|
||||
root.insert("providers".to_string(), TomlValue::Table(providers_table));
|
||||
@@ -591,6 +616,70 @@ api_key = ""
|
||||
assert!(caps.iter().any(|v| v.as_str() == Some("thinking")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kimi_code_export_adds_opencode_go_session_header() {
|
||||
let make_provider = |base_url: &str, raw_other: Value| Provider {
|
||||
name: "p".to_string(),
|
||||
provider_type: ProviderType::Openai,
|
||||
base_url: Some(base_url.to_string()),
|
||||
api_key: Some("sk-test".to_string()),
|
||||
env: IndexMap::new(),
|
||||
note: None,
|
||||
official_url: None,
|
||||
managed: false,
|
||||
enabled: true,
|
||||
active: false,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
raw_other,
|
||||
usage_kinds: None,
|
||||
usage_config: None,
|
||||
};
|
||||
let export = |p: Provider| {
|
||||
let mut providers = IndexMap::new();
|
||||
providers.insert("p".to_string(), p);
|
||||
let config = Config {
|
||||
default_model: None,
|
||||
providers,
|
||||
models: IndexMap::new(),
|
||||
raw_other: Value::Null,
|
||||
imported_section_keys: Vec::new(),
|
||||
};
|
||||
let exported = config_to_kimi_code(&config, None);
|
||||
let root = exported.as_table().unwrap().clone();
|
||||
root.get("providers")
|
||||
.and_then(|v| v.as_table())
|
||||
.and_then(|t| t.get("p"))
|
||||
.and_then(|v| v.as_table().cloned())
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
// Go endpoint without headers → header injected.
|
||||
let p = export(make_provider("https://opencode.ai/zen/go/v1", Value::Null));
|
||||
let headers = p.get("custom_headers").unwrap().as_table().unwrap();
|
||||
assert_eq!(
|
||||
headers.get("x-opencode-session").and_then(|v| v.as_str()),
|
||||
Some("kimi-switch")
|
||||
);
|
||||
|
||||
// Existing user-set value is preserved, not overwritten.
|
||||
let raw = serde_json::json!({
|
||||
"custom_headers": { "x-opencode-session": "my-session" }
|
||||
});
|
||||
let p = export(make_provider("https://opencode.ai/zen/go/v1", raw));
|
||||
let headers = p.get("custom_headers").unwrap().as_table().unwrap();
|
||||
assert_eq!(
|
||||
headers.get("x-opencode-session").and_then(|v| v.as_str()),
|
||||
Some("my-session")
|
||||
);
|
||||
|
||||
// PAYG zen endpoint and unrelated providers are left alone.
|
||||
let p = export(make_provider("https://opencode.ai/zen/v1", Value::Null));
|
||||
assert!(p.get("custom_headers").is_none());
|
||||
let p = export(make_provider("https://api.deepseek.com/v1", Value::Null));
|
||||
assert!(p.get("custom_headers").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kimi_code_export_syncs_raw_other_top_level_sections() {
|
||||
// Regression: UI-managed top-level sections ([thinking],
|
||||
|
||||
@@ -121,6 +121,7 @@ pub fn run() {
|
||||
dashboard::get_day_detail,
|
||||
dashboard::list_sessions,
|
||||
dashboard::archive_session,
|
||||
dashboard::archive_sessions_before,
|
||||
dashboard::unarchive_session,
|
||||
dashboard::delete_session,
|
||||
dashboard::delete_workspace,
|
||||
|
||||
@@ -290,6 +290,7 @@ pub struct UsageConfig {
|
||||
impl UsageConfig {
|
||||
pub const TEMPLATE_AUTO: &'static str = "auto";
|
||||
pub const TEMPLATE_NEWAPI: &'static str = "newapi";
|
||||
pub const TEMPLATE_SUB2API: &'static str = "sub2api";
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Config {
|
||||
|
||||
@@ -521,6 +521,159 @@ fn parse_newapi(
|
||||
}])
|
||||
}
|
||||
|
||||
// ── Sub2API (Wei-Shaw/sub2api) 中转站 ────────────────────────
|
||||
// GET {base_url}/v1/usage
|
||||
// 头:Authorization: Bearer <api_key>(就是推理用的 sk- key,无需额外凭据)
|
||||
// Response(三种 mode):
|
||||
// - quota_limited:key 设了总额度/速率限制 → quota{limit,used,remaining} +
|
||||
// rate_limits[{window: 5h|1d|7d, limit, used, remaining, reset_at}]
|
||||
// - unrestricted + subscription:订阅组 → planName + subscription 的
|
||||
// daily/weekly/monthly usage/limit(USD)
|
||||
// - unrestricted + 钱包:planName="钱包余额" → balance / remaining(USD)
|
||||
//
|
||||
// 站点指纹(可选探测):GET /api/v1/settings/public 返回 data.affiliate_enabled
|
||||
// 即为 sub2api 面板。注意 NewAPI 的 /api/user/self、/api/status 在 sub2api 上
|
||||
// 全部 404 —— 两套中转站协议不互通。
|
||||
|
||||
/// 把供应商 base_url 归一成站点根(去掉结尾 `/` 与 `/v1`),网关路由挂在根路径。
|
||||
fn sub2api_site_root(base_url: &str) -> String {
|
||||
let mut base = base_url.trim_end_matches('/');
|
||||
if let Some(stripped) = base.strip_suffix("/v1") {
|
||||
base = stripped;
|
||||
}
|
||||
base.to_string()
|
||||
}
|
||||
|
||||
pub async fn query_sub2api(
|
||||
base_url: &str,
|
||||
api_key: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<UsageResult, String> {
|
||||
let url = format!("{}/v1/usage", sub2api_site_root(base_url));
|
||||
match get_json(&url, api_key, AuthStyle::Bearer, timeout).await? {
|
||||
Fetched::Body(body) => Ok(parse_sub2api(&body)),
|
||||
Fetched::Failed(err) => Ok(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// 速率窗口名 → 本地化 tier 名(前端 planLabel 会翻译;five_hour /
|
||||
/// weekly_limit 已有映射,daily_limit 新增)。
|
||||
fn sub2api_window_tier(window: &str) -> &'static str {
|
||||
match window {
|
||||
"5h" => "five_hour",
|
||||
"1d" => "daily_limit",
|
||||
"7d" => "weekly_limit",
|
||||
_ => "window",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_sub2api(body: &serde_json::Value) -> UsageResult {
|
||||
let is_valid = body
|
||||
.get("isValid")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let mode = body.get("mode").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if mode.is_empty() {
|
||||
return UsageResult::failure(
|
||||
"Missing 'mode' field in response (not a sub2api gateway?)".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut out: Vec<UsageData> = Vec::new();
|
||||
|
||||
// key 总额度(quota_limited 模式才有)
|
||||
if let Some(quota) = body.get("quota") {
|
||||
if let Some(limit) = parse_f64_field(quota, "limit").filter(|&l| l > 0.0) {
|
||||
let used = parse_f64_field(quota, "used").unwrap_or(0.0);
|
||||
let remaining = parse_f64_field(quota, "remaining").unwrap_or(limit - used);
|
||||
out.push(UsageData {
|
||||
plan_name: Some("Sub2API".to_string()),
|
||||
remaining: Some(remaining),
|
||||
total: Some(limit),
|
||||
used: Some(used),
|
||||
unit: Some("USD".to_string()),
|
||||
is_valid: Some(is_valid && remaining > 0.0),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 速率窗口(5h / 1d / 7d;reset_at 为 RFC3339,窗口过期时缺省)
|
||||
if let Some(rates) = body.get("rate_limits").and_then(|v| v.as_array()) {
|
||||
for w in rates {
|
||||
let window = w.get("window").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let Some(limit) = parse_f64_field(w, "limit").filter(|&l| l > 0.0) else {
|
||||
continue;
|
||||
};
|
||||
let used = parse_f64_field(w, "used").unwrap_or(0.0);
|
||||
let remaining = parse_f64_field(w, "remaining").unwrap_or(limit - used);
|
||||
out.push(UsageData {
|
||||
plan_name: Some(sub2api_window_tier(window).to_string()),
|
||||
remaining: Some(remaining),
|
||||
total: Some(limit),
|
||||
used: Some(used),
|
||||
unit: Some("USD".to_string()),
|
||||
is_valid: Some(is_valid && remaining > 0.0),
|
||||
resets_at: w
|
||||
.get("reset_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// unrestricted 订阅组:daily/weekly/monthly 三窗口(usage_usd vs limit_usd)
|
||||
if mode == "unrestricted" {
|
||||
if let Some(sub) = body.get("subscription") {
|
||||
for (prefix, tier) in [
|
||||
("daily", "daily_limit"),
|
||||
("weekly", "weekly_limit"),
|
||||
("monthly", "monthly_limit"),
|
||||
] {
|
||||
let Some(usage) = parse_f64_field(sub, &format!("{prefix}_usage_usd")) else {
|
||||
continue;
|
||||
};
|
||||
let Some(limit) = parse_f64_field(sub, &format!("{prefix}_limit_usd"))
|
||||
.filter(|&l| l > 0.0)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let remaining = limit - usage;
|
||||
out.push(UsageData {
|
||||
plan_name: Some(tier.to_string()),
|
||||
remaining: Some(remaining),
|
||||
total: Some(limit),
|
||||
used: Some(usage),
|
||||
unit: Some("USD".to_string()),
|
||||
is_valid: Some(is_valid && remaining > 0.0),
|
||||
resets_at: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 钱包余额(unrestricted 非订阅)或以上全部缺失时的兜底
|
||||
if out.is_empty() {
|
||||
if let Some(balance) = parse_f64_field(body, "balance")
|
||||
.or_else(|| parse_f64_field(body, "remaining"))
|
||||
{
|
||||
out.push(UsageData {
|
||||
plan_name: Some("Sub2API".to_string()),
|
||||
remaining: Some(balance),
|
||||
unit: Some("USD".to_string()),
|
||||
is_valid: Some(is_valid),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if out.is_empty() {
|
||||
UsageResult::failure("No quota/rate-limit/balance fields in response".to_string())
|
||||
} else {
|
||||
UsageResult::ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -688,4 +841,105 @@ mod tests {
|
||||
assert_eq!(data[0].remaining, Some(1.0));
|
||||
assert_eq!(data[0].used, Some(0.2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_site_root_strips_v1_and_slash() {
|
||||
assert_eq!(sub2api_site_root("https://x.com"), "https://x.com");
|
||||
assert_eq!(sub2api_site_root("https://x.com/"), "https://x.com");
|
||||
assert_eq!(sub2api_site_root("https://x.com/v1"), "https://x.com");
|
||||
assert_eq!(sub2api_site_root("https://x.com/v1/"), "https://x.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_quota_limited_parses_quota_and_windows() {
|
||||
let body = json!({
|
||||
"mode": "quota_limited",
|
||||
"isValid": true,
|
||||
"quota": { "limit": 50.0, "used": 20.0, "remaining": 30.0, "unit": "USD" },
|
||||
"remaining": 30.0,
|
||||
"unit": "USD",
|
||||
"rate_limits": [
|
||||
{ "window": "5h", "limit": 10.0, "used": 4.0, "remaining": 6.0,
|
||||
"window_start": "2026-09-13T00:00:00Z", "reset_at": "2026-09-13T05:00:00Z" },
|
||||
{ "window": "1d", "limit": 30.0, "used": 10.0, "remaining": 20.0,
|
||||
"window_start": "2026-09-13T00:00:00Z" }
|
||||
]
|
||||
});
|
||||
let result = parse_sub2api(&body);
|
||||
assert!(result.success);
|
||||
let data = result.data.unwrap();
|
||||
assert_eq!(data.len(), 3);
|
||||
assert_eq!(data[0].plan_name.as_deref(), Some("Sub2API"));
|
||||
assert_eq!(data[0].remaining, Some(30.0));
|
||||
assert_eq!(data[0].total, Some(50.0));
|
||||
assert_eq!(data[0].used, Some(20.0));
|
||||
assert_eq!(data[0].unit.as_deref(), Some("USD"));
|
||||
assert_eq!(data[1].plan_name.as_deref(), Some("five_hour"));
|
||||
assert_eq!(data[1].remaining, Some(6.0));
|
||||
assert_eq!(data[1].resets_at.as_deref(), Some("2026-09-13T05:00:00Z"));
|
||||
assert_eq!(data[2].plan_name.as_deref(), Some("daily_limit"));
|
||||
assert_eq!(data[2].resets_at, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_subscription_windows() {
|
||||
let body = json!({
|
||||
"mode": "unrestricted",
|
||||
"isValid": true,
|
||||
"planName": "claude-pro",
|
||||
"unit": "USD",
|
||||
"subscription": {
|
||||
"daily_usage_usd": 1.0, "daily_limit_usd": 10.0,
|
||||
"weekly_usage_usd": 8.0, "weekly_limit_usd": 30.0,
|
||||
"monthly_usage_usd": 55.0, "monthly_limit_usd": 60.0
|
||||
}
|
||||
});
|
||||
let result = parse_sub2api(&body);
|
||||
assert!(result.success);
|
||||
let data = result.data.unwrap();
|
||||
assert_eq!(data.len(), 3);
|
||||
assert_eq!(data[0].plan_name.as_deref(), Some("daily_limit"));
|
||||
assert_eq!(data[0].remaining, Some(9.0));
|
||||
assert_eq!(data[1].plan_name.as_deref(), Some("weekly_limit"));
|
||||
assert_eq!(data[1].remaining, Some(22.0));
|
||||
assert_eq!(data[2].plan_name.as_deref(), Some("monthly_limit"));
|
||||
assert_eq!(data[2].remaining, Some(5.0));
|
||||
assert_eq!(data[2].is_valid, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_wallet_balance() {
|
||||
let body = json!({
|
||||
"mode": "unrestricted",
|
||||
"isValid": true,
|
||||
"planName": "钱包余额",
|
||||
"remaining": 12.5,
|
||||
"unit": "USD",
|
||||
"balance": 12.5
|
||||
});
|
||||
let data = parse_sub2api(&body).data.unwrap();
|
||||
assert_eq!(data.len(), 1);
|
||||
assert_eq!(data[0].plan_name.as_deref(), Some("Sub2API"));
|
||||
assert_eq!(data[0].remaining, Some(12.5));
|
||||
assert_eq!(data[0].unit.as_deref(), Some("USD"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_missing_mode_is_deterministic_failure() {
|
||||
let body = json!({ "foo": 1 });
|
||||
let result = parse_sub2api(&body);
|
||||
assert!(!result.success);
|
||||
assert!(result.error.unwrap().contains("Missing 'mode'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub2api_exhausted_window_is_invalid() {
|
||||
let body = json!({
|
||||
"mode": "quota_limited",
|
||||
"isValid": true,
|
||||
"quota": { "limit": 10.0, "used": 10.0, "remaining": 0.0, "unit": "USD" }
|
||||
});
|
||||
let data = parse_sub2api(&body).data.unwrap();
|
||||
assert_eq!(data[0].is_valid, Some(false));
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ pub enum UsageKind {
|
||||
BalanceNovita,
|
||||
BalanceKimi,
|
||||
BalanceNewapi,
|
||||
BalanceSub2Api,
|
||||
PlanKimiCoding,
|
||||
PlanZhipu,
|
||||
PlanMinimax,
|
||||
@@ -40,6 +41,7 @@ impl UsageKind {
|
||||
UsageKind::BalanceNovita => "balance:novita",
|
||||
UsageKind::BalanceKimi => "balance:kimi",
|
||||
UsageKind::BalanceNewapi => "balance:newapi",
|
||||
UsageKind::BalanceSub2Api => "balance:sub2api",
|
||||
UsageKind::PlanKimiCoding => "plan:kimi_coding",
|
||||
UsageKind::PlanZhipu => "plan:zhipu",
|
||||
UsageKind::PlanMinimax => "plan:minimax",
|
||||
@@ -47,7 +49,7 @@ impl UsageKind {
|
||||
}
|
||||
}
|
||||
|
||||
pub const ALL: [UsageKind; 11] = [
|
||||
pub const ALL: [UsageKind; 12] = [
|
||||
UsageKind::BalanceDeepseek,
|
||||
UsageKind::BalanceSiliconflow,
|
||||
UsageKind::BalanceOpenrouter,
|
||||
@@ -55,6 +57,7 @@ impl UsageKind {
|
||||
UsageKind::BalanceNovita,
|
||||
UsageKind::BalanceKimi,
|
||||
UsageKind::BalanceNewapi,
|
||||
UsageKind::BalanceSub2Api,
|
||||
UsageKind::PlanKimiCoding,
|
||||
UsageKind::PlanZhipu,
|
||||
UsageKind::PlanMinimax,
|
||||
@@ -74,6 +77,7 @@ impl std::str::FromStr for UsageKind {
|
||||
"balance:novita" => UsageKind::BalanceNovita,
|
||||
"balance:kimi" => UsageKind::BalanceKimi,
|
||||
"balance:newapi" => UsageKind::BalanceNewapi,
|
||||
"balance:sub2api" => UsageKind::BalanceSub2Api,
|
||||
"plan:kimi_coding" => UsageKind::PlanKimiCoding,
|
||||
"plan:zhipu" => UsageKind::PlanZhipu,
|
||||
"plan:minimax" => UsageKind::PlanMinimax,
|
||||
@@ -97,6 +101,14 @@ pub fn detect_provider(base_url: &str) -> Vec<UsageKind> {
|
||||
if url.contains("openrouter.ai") {
|
||||
kinds.push(UsageKind::BalanceOpenrouter);
|
||||
}
|
||||
// codingplan.site 家族:主域(含任意子域除 ai. 外)是 Sub2API 面板
|
||||
// (/api/v1/settings/public 指纹命中,NewAPI 端点全 404);
|
||||
// ai.codingplan.site 才是 NewAPI 实例(/api/status、/api/user/self 可用)。
|
||||
if url.contains("ai.codingplan.site") {
|
||||
kinds.push(UsageKind::BalanceNewapi);
|
||||
} else if url.contains("codingplan.site") {
|
||||
kinds.push(UsageKind::BalanceSub2Api);
|
||||
}
|
||||
if url.contains("api.stepfun.com") {
|
||||
kinds.push(UsageKind::BalanceStepfun);
|
||||
}
|
||||
@@ -126,6 +138,19 @@ pub fn detect_provider(base_url: &str) -> Vec<UsageKind> {
|
||||
kinds
|
||||
}
|
||||
|
||||
/// BalanceNewapi 模板所需凭据(web 控制台 access token + user id)。
|
||||
/// 两者都必须存在且非空;返回 None 表示缺少凭据(确定性配置错误)。
|
||||
fn newapi_creds(
|
||||
usage_config: Option<&crate::models::UsageConfig>,
|
||||
) -> Option<(&str, &str)> {
|
||||
usage_config.and_then(|c| {
|
||||
c.access_token
|
||||
.as_deref()
|
||||
.zip(c.user_id.as_deref())
|
||||
.filter(|(t, u)| !t.is_empty() && !u.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// 按 kind 路由到对应查询实现。`base_url` 用于消歧同一家供应商的
|
||||
/// 国内/海外站(SiliconFlow .cn/.com、MiniMax .com/.io、智谱 bigmodel/z.ai)。
|
||||
/// `usage_config` 仅 BalanceNewapi 分支读取(access_token / user_id),
|
||||
@@ -155,22 +180,27 @@ pub async fn query_kind(
|
||||
balance::query_kimi(api_key, !lower.contains("moonshot.ai"), timeout).await
|
||||
}
|
||||
UsageKind::BalanceNewapi => {
|
||||
let (token, uid) = usage_config
|
||||
.and_then(|c| {
|
||||
c.access_token
|
||||
.as_deref()
|
||||
.zip(c.user_id.as_deref())
|
||||
.filter(|(t, u)| !t.is_empty() && !u.is_empty())
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
"newapi template requires accessToken and userId".to_string()
|
||||
})?;
|
||||
// 缺凭据是确定性配置错误 → Ok(failure)(前端按前缀本地化提示),
|
||||
// 而非 Err(Err 语义 = 瞬时网络错误,见 commands.rs newapi 分支)。
|
||||
let Some((token, uid)) = newapi_creds(usage_config) else {
|
||||
return Ok(UsageResult::failure(
|
||||
"newapi template requires accessToken and userId".to_string(),
|
||||
));
|
||||
};
|
||||
let url = usage_config
|
||||
.and_then(|c| c.base_url.as_deref())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(base_url);
|
||||
balance::query_newapi(url, token, uid, timeout).await
|
||||
}
|
||||
UsageKind::BalanceSub2Api => {
|
||||
// sub2api 复用推理 API Key,无需额外凭据;base_url 同样允许面板覆盖。
|
||||
let url = usage_config
|
||||
.and_then(|c| c.base_url.as_deref())
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(base_url);
|
||||
balance::query_sub2api(url, api_key, timeout).await
|
||||
}
|
||||
UsageKind::PlanKimiCoding => {
|
||||
coding_plan::query_kimi_coding(base_url, api_key, timeout).await
|
||||
}
|
||||
@@ -262,6 +292,28 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_provider_codingplan_site_family() {
|
||||
// codingplan.site 家族分家:主域是 Sub2API 面板(推理 key 直查 /v1/usage),
|
||||
// ai. 子域才是 NewAPI 实例。
|
||||
assert_eq!(
|
||||
detect_provider("https://codingplan.site"),
|
||||
vec![UsageKind::BalanceSub2Api]
|
||||
);
|
||||
assert_eq!(
|
||||
detect_provider("https://codingplan.site/v1"),
|
||||
vec![UsageKind::BalanceSub2Api]
|
||||
);
|
||||
assert_eq!(
|
||||
detect_provider("https://ai.codingplan.site"),
|
||||
vec![UsageKind::BalanceNewapi]
|
||||
);
|
||||
assert_eq!(
|
||||
detect_provider("https://ai.codingplan.site/v1"),
|
||||
vec![UsageKind::BalanceNewapi]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_kind_string_roundtrip() {
|
||||
use std::str::FromStr;
|
||||
@@ -272,4 +324,30 @@ mod tests {
|
||||
assert!(UsageKind::from_str("balance:unknown").is_err());
|
||||
assert!(UsageKind::from_str("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newapi_creds_requires_both_and_nonempty() {
|
||||
use crate::models::UsageConfig;
|
||||
let cfg = |token: Option<&str>, uid: Option<&str>| UsageConfig {
|
||||
enabled: true,
|
||||
template_type: "newapi".to_string(),
|
||||
base_url: None,
|
||||
access_token: token.map(str::to_string),
|
||||
user_id: uid.map(str::to_string),
|
||||
auto_query_interval_minutes: None,
|
||||
timeout_seconds: None,
|
||||
};
|
||||
// 缺 config / 缺任一项 / 空字符串 → None(确定性配置错误)
|
||||
assert_eq!(newapi_creds(None), None);
|
||||
assert_eq!(newapi_creds(Some(&cfg(None, None))), None);
|
||||
assert_eq!(newapi_creds(Some(&cfg(Some("tok"), None))), None);
|
||||
assert_eq!(newapi_creds(Some(&cfg(None, Some("uid")))), None);
|
||||
assert_eq!(newapi_creds(Some(&cfg(Some(""), Some("uid")))), None);
|
||||
assert_eq!(newapi_creds(Some(&cfg(Some("tok"), Some("")))), None);
|
||||
// 两项齐全 → Some
|
||||
assert_eq!(
|
||||
newapi_creds(Some(&cfg(Some("tok"), Some("uid")))),
|
||||
Some(("tok", "uid"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"productName": "Kimi Switch",
|
||||
"version": "0.7.12",
|
||||
"version": "0.7.19",
|
||||
"identifier": "com.kimiswitch.app",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -157,10 +157,13 @@ export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelPro
|
||||
</Card>
|
||||
|
||||
<Card title={t("permissionRules")}>
|
||||
{/* kimi-code 0.40.1 `[permission] dangerous_command_guard`. The env
|
||||
{/* kimi-code `[permission] dangerous_command_guard`. The env
|
||||
var KIMI_CODE_DANGEROUS_COMMAND_GUARD (literal "true"/"false")
|
||||
outranks this config at runtime; no env-lock UI here (deliberate
|
||||
minimal scope). Absent key = upstream default on. */}
|
||||
minimal scope). Absent key = upstream default on. Since
|
||||
kimi-code 0.41.0 the guard only gates Manual/YOLO modes —
|
||||
Auto (never-ask) mode no longer intercepts dangerous
|
||||
commands. */}
|
||||
<Checkbox
|
||||
label={t("permissionDangerousGuard")}
|
||||
checked={settings.permission?.dangerous_command_guard ?? true}
|
||||
|
||||
@@ -527,6 +527,18 @@ function ModelMapping({
|
||||
});
|
||||
};
|
||||
|
||||
const selectAllModels = () => {
|
||||
if (!discovered) return;
|
||||
setSelected(new Set(discovered.map((m) => m.id)));
|
||||
};
|
||||
|
||||
const deselectAllModels = () => setSelected(new Set());
|
||||
|
||||
const invertSelection = () => {
|
||||
if (!discovered) return;
|
||||
setSelected((prev) => new Set(discovered.filter((m) => !prev.has(m.id)).map((m) => m.id)));
|
||||
};
|
||||
|
||||
const handleAddSelected = () => {
|
||||
if (!discovered || selected.size === 0) return;
|
||||
const existingIds = new Set(models.filter((m) => m.model).map((m) => m.model));
|
||||
@@ -596,8 +608,33 @@ function ModelMapping({
|
||||
|
||||
{discovered && (
|
||||
<div className="bg-panel border border-border rounded-xl p-4 space-y-3">
|
||||
<div className="text-sm font-medium">
|
||||
{t("discoveredModels", { count: discovered.length })}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm font-medium">
|
||||
{t("discoveredModels", { count: discovered.length })}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={selectAllModels}
|
||||
className="px-2 py-0.5 text-xs border border-border rounded hover:bg-hover-2 text-content-primary transition-colors"
|
||||
>
|
||||
{t("selectAll")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={deselectAllModels}
|
||||
className="px-2 py-0.5 text-xs border border-border rounded hover:bg-hover-2 text-content-primary transition-colors"
|
||||
>
|
||||
{t("deselectAll")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={invertSelection}
|
||||
className="px-2 py-0.5 text-xs border border-border rounded hover:bg-hover-2 text-content-primary transition-colors"
|
||||
>
|
||||
{t("invertSelection")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm text-content-primary cursor-pointer">
|
||||
<input
|
||||
|
||||
@@ -69,7 +69,8 @@ function ProviderCard({
|
||||
agent,
|
||||
provider.name,
|
||||
provider.usageKinds,
|
||||
provider.usageConfig?.autoQueryIntervalMinutes
|
||||
provider.usageConfig?.autoQueryIntervalMinutes,
|
||||
provider.usageConfig?.enabled === false
|
||||
);
|
||||
const providerModels = Object.values(models).filter(
|
||||
(m) => m.provider === provider.name
|
||||
|
||||
@@ -43,22 +43,11 @@ const EFFORT_LABELS: Record<(typeof EFFORTS)[number], TranslationKey> = {
|
||||
};
|
||||
|
||||
const FLAG_LABELS: Record<string, { name: TranslationKey; desc: TranslationKey }> = {
|
||||
"secondary-model": { name: "flagSecondaryModel", desc: "flagSecondaryModelDesc" },
|
||||
wait_for: { name: "flagWaitFor", desc: "flagWaitForDesc" },
|
||||
"tool-select": { name: "flagToolSelect", desc: "flagToolSelectDesc" },
|
||||
persistence_minidb_readmodel: {
|
||||
name: "flagMinidbReadmodel",
|
||||
desc: "flagMinidbReadmodelDesc",
|
||||
},
|
||||
notify_user: { name: "flagNotifyUser", desc: "flagNotifyUserDesc" },
|
||||
tower: { name: "flagTower", desc: "flagTowerDesc" },
|
||||
subagent_fork: { name: "flagSubagentFork", desc: "flagSubagentForkDesc" },
|
||||
wait_for: { name: "flagWaitFor", desc: "flagWaitForDesc" },
|
||||
auto_session_title: {
|
||||
name: "flagAutoSessionTitle",
|
||||
desc: "flagAutoSessionTitleDesc",
|
||||
},
|
||||
"remote-control": { name: "flagRemoteControl", desc: "flagRemoteControlDesc" },
|
||||
search_worker: { name: "flagSearchWorker", desc: "flagSearchWorkerDesc" },
|
||||
file_history: { name: "flagFileHistory", desc: "flagFileHistoryDesc" },
|
||||
};
|
||||
|
||||
/** Validation-error i18n key per engine rule, for the pre-write self-check. */
|
||||
@@ -186,21 +175,6 @@ export function SubagentSettingsPage({
|
||||
// off — upgrading with force would create an invalid force+pool-table combo.
|
||||
const canUpgrade = !!pool && !isPoolView && pool.model !== undefined && !pool.force;
|
||||
const masterOn = isMasterEnvOn(env);
|
||||
const secondaryFlag = EXPERIMENTAL_FLAGS[0]; // "secondary-model"
|
||||
const otherFlags = EXPERIMENTAL_FLAGS.slice(1);
|
||||
|
||||
/** Effective state of the secondary-model flag. Mirrors the kimi-code
|
||||
* 0.40.1 priority: single-flag env > explicit [experimental] value >
|
||||
* master env (force-on only) > upstream default. The master env no
|
||||
* longer locks the toggle — only the flag's own env var does. */
|
||||
const secondaryEnabled = isFlagLockedByEnv(env, secondaryFlag)
|
||||
? forcedEnvValue(env, secondaryFlag)
|
||||
: isExperimentalFlagSet(rawOther, secondaryFlag.id)
|
||||
? flags["secondary-model"] === true
|
||||
: masterOn
|
||||
? true
|
||||
: (secondaryFlag.defaultEnabled ?? false);
|
||||
const secondaryLocked = isFlagLockedByEnv(env, secondaryFlag);
|
||||
|
||||
const aliasList = Object.keys(models).sort();
|
||||
|
||||
@@ -574,41 +548,6 @@ export function SubagentSettingsPage({
|
||||
)}
|
||||
|
||||
<div className="border-t border-border" />
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm text-content-primary">
|
||||
{t(FLAG_LABELS[secondaryFlag.id].name)}
|
||||
{!secondaryLocked &&
|
||||
!isExperimentalFlagSet(rawOther, secondaryFlag.id) &&
|
||||
secondaryFlag.defaultEnabled && (
|
||||
<span className="shrink-0 text-xs text-blue-600 dark:text-blue-400 border border-blue-500/30 rounded px-1">
|
||||
{t("flagDefaultOn")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-content-muted">
|
||||
{t(FLAG_LABELS[secondaryFlag.id].desc)}
|
||||
<code className="ml-2">{secondaryFlag.envVar}</code>
|
||||
</div>
|
||||
</div>
|
||||
{secondaryLocked && (
|
||||
<span className="text-xs text-content-muted shrink-0">
|
||||
🔒 {t("lockedByEnv")}
|
||||
</span>
|
||||
)}
|
||||
<Toggle
|
||||
checked={secondaryEnabled}
|
||||
disabled={secondaryLocked}
|
||||
ariaLabel={t(FLAG_LABELS[secondaryFlag.id].name)}
|
||||
onChange={(checked) =>
|
||||
onChange(
|
||||
setExperimentalFlag(rawOther, secondaryFlag.id, checked, {
|
||||
explicitFalse: masterOn || secondaryFlag.defaultEnabled === true,
|
||||
})
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{effectiveDefault !== undefined && (
|
||||
<div className="rounded-lg border border-border bg-input/40 px-3 py-2.5 space-y-2">
|
||||
@@ -637,9 +576,9 @@ export function SubagentSettingsPage({
|
||||
<p className="text-xs text-content-muted">{t("secondaryModelPriorityHint")}</p>
|
||||
</Card>
|
||||
|
||||
{/* Other experimental features (not subagent-related) */}
|
||||
<Card title={t("otherExperimentalFlags")}>
|
||||
{otherFlags.map(renderFlagRow)}
|
||||
{/* Experimental feature flags — one unified list */}
|
||||
<Card title={t("experimentalFlags")}>
|
||||
{EXPERIMENTAL_FLAGS.map(renderFlagRow)}
|
||||
<p className="text-xs text-content-muted">{t("experimentalFlagsHint")}</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { invoke } from "@tauri-apps/api/core";
|
||||
import { ArrowLeft, Eye, EyeOff, Loader2, Play } from "lucide-react";
|
||||
import { useTranslation } from "../i18n";
|
||||
import type { TranslationKey } from "../i18n/zh";
|
||||
import { localizeUsageError, planLabel } from "../lib/usage-display";
|
||||
import { formatAmount, localizeUsageError, planLabel } from "../lib/usage-display";
|
||||
import type { Agent, Provider, UsageConfig } from "../types";
|
||||
|
||||
interface UsageResult {
|
||||
@@ -30,12 +30,13 @@ interface UsageConfigModalProps {
|
||||
}
|
||||
|
||||
const TEMPLATES: ReadonlyArray<{
|
||||
id: "auto" | "newapi";
|
||||
id: "auto" | "newapi" | "sub2api";
|
||||
labelKey: TranslationKey;
|
||||
hintKey: TranslationKey;
|
||||
}> = [
|
||||
{ id: "auto", labelKey: "usageTemplateAuto", hintKey: "usageAutoDetectHint" },
|
||||
{ id: "newapi", labelKey: "usageTemplateNewapi", hintKey: "usageNewapiHint" },
|
||||
{ id: "sub2api", labelKey: "usageTemplateSub2api", hintKey: "usageSub2apiHint" },
|
||||
];
|
||||
|
||||
function defaultConfig(provider: Provider): UsageConfig {
|
||||
@@ -134,7 +135,7 @@ export function UsageConfigModal({ open, agent, provider, onClose, onSave }: Usa
|
||||
.map((d) => {
|
||||
const parts: string[] = [];
|
||||
if (d.planName) parts.push(planLabel(d.planName, t));
|
||||
if (d.remaining != null) parts.push(`${t("usageRemaining")} ${d.remaining}${d.unit ?? ""}`);
|
||||
if (d.remaining != null) parts.push(`${t("usageRemaining")} ${formatAmount(d.remaining, d.unit)}`);
|
||||
if (d.used != null && d.total != null && d.total > 0)
|
||||
parts.push(`${Math.round((d.used / d.total) * 100)}%`);
|
||||
return parts.join(" ");
|
||||
@@ -225,7 +226,9 @@ export function UsageConfigModal({ open, agent, provider, onClose, onSave }: Usa
|
||||
<p className="text-xs text-content-muted">
|
||||
{cfg.templateType === "newapi"
|
||||
? t("usageNewapiHint")
|
||||
: t("usageAutoDetectHint")}
|
||||
: cfg.templateType === "sub2api"
|
||||
? t("usageSub2apiHint")
|
||||
: t("usageAutoDetectHint")}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
@@ -237,9 +240,9 @@ export function UsageConfigModal({ open, agent, provider, onClose, onSave }: Usa
|
||||
<span className="text-blue-500">{"{{baseUrl}}"}</span>
|
||||
<span className="text-content-muted">=</span>
|
||||
<span className="text-content-primary break-all">
|
||||
{cfg.templateType === "newapi"
|
||||
? cfg.baseUrl || provider.base_url || "-"
|
||||
: provider.base_url || "-"}
|
||||
{cfg.templateType === "auto"
|
||||
? provider.base_url || "-"
|
||||
: cfg.baseUrl || provider.base_url || "-"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs font-mono">
|
||||
@@ -344,6 +347,21 @@ export function UsageConfigModal({ open, agent, provider, onClose, onSave }: Usa
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* sub2api: no extra credentials (reuses the inference key), optional gateway override */}
|
||||
{!isManaged && cfg.templateType === "sub2api" && (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm text-content-muted mb-1.5">{t("usageBaseUrl")}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="w-full bg-input border border-border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
|
||||
value={cfg.baseUrl ?? ""}
|
||||
placeholder={provider.base_url ?? "https://your-sub2api-site.com"}
|
||||
onChange={(e) => setCfg({ ...cfg, baseUrl: e.target.value || undefined })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* timeout + auto query interval */}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Loader2, RefreshCw } from "lucide-react";
|
||||
import { useTranslation } from "../i18n";
|
||||
import { localizeUsageError, planLabel } from "../lib/usage-display";
|
||||
import { formatAmount, localizeUsageError, planLabel } from "../lib/usage-display";
|
||||
import type { UsageData, UsageQueryState } from "../hooks/useUsageQuery";
|
||||
|
||||
interface UsageFooterProps {
|
||||
@@ -36,17 +36,6 @@ export function UsageFooter({ usage, variant = "detail" }: UsageFooterProps) {
|
||||
return null;
|
||||
};
|
||||
|
||||
const formatAmount = (
|
||||
value: number | null | undefined,
|
||||
unit?: string | null
|
||||
): string => {
|
||||
if (value == null) return "—";
|
||||
const symbol =
|
||||
unit === "CNY" ? "¥" : unit === "USD" ? "$" : unit ? `${unit} ` : "";
|
||||
const num = Number.isInteger(value) ? String(value) : value.toFixed(2);
|
||||
return `${symbol}${num}`;
|
||||
};
|
||||
|
||||
const formatReset = (resetsAt?: string | null): string | null => {
|
||||
if (!resetsAt) return null;
|
||||
const ms = new Date(resetsAt).getTime() - now;
|
||||
|
||||
@@ -8,10 +8,11 @@ import { fmtInt, fmtPct, fmtTime, fmtTokens } from "../../lib/dashboard-format";
|
||||
import { DailyBars } from "./DailyBars";
|
||||
import { DailyDetailModal } from "./DailyDetailModal";
|
||||
import { Heatmap } from "./Heatmap";
|
||||
import { ModelTotalsChart } from "./ModelTotalsChart";
|
||||
import { TrendLineChart } from "./TrendLineChart";
|
||||
import type { DailyRow, HeatmapCell } from "../../types/dashboard";
|
||||
|
||||
const RANGES: DashboardRange[] = ["today", "7d", "30d", "all"];
|
||||
const RANGES: DashboardRange[] = ["today", "yesterday", "7d", "30d", "all"];
|
||||
|
||||
/** Per-request cache hit rate: cached tokens / total input tokens. */
|
||||
function cacheHitOf(r: { inputOther: number; inputCacheRead: number }): number {
|
||||
@@ -59,13 +60,14 @@ export function DashboardPage() {
|
||||
const { range, changeRange, data, loading, error, refresh, loadStats } = useDashboard();
|
||||
const [showAllModels, setShowAllModels] = useState(false);
|
||||
const [recentPage, setRecentPage] = useState(1);
|
||||
const [trendTab, setTrendTab] = useState<"daily" | "model" | "provider">("daily");
|
||||
const [trendTab, setTrendTab] = useState<"daily" | "model" | "provider" | "totals">("daily");
|
||||
const [heatmapSelected, setHeatmapSelected] = useState<DailyRow | null>(null);
|
||||
|
||||
const daily = data?.stats.daily ?? [];
|
||||
|
||||
const RANGE_LABELS: Record<DashboardRange, string> = {
|
||||
today: t("rangeToday"),
|
||||
yesterday: t("rangeYesterday"),
|
||||
"7d": t("range7d"),
|
||||
"30d": t("range30d"),
|
||||
all: t("rangeAll"),
|
||||
@@ -192,7 +194,7 @@ export function DashboardPage() {
|
||||
</div>
|
||||
|
||||
{/* Range overview cards */}
|
||||
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
|
||||
{RANGES.map((r) => {
|
||||
const tot = rangeTotals[r];
|
||||
if (!tot) return null;
|
||||
@@ -272,13 +274,26 @@ export function DashboardPage() {
|
||||
>
|
||||
{t("tabProviderTrend")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTrendTab("totals")}
|
||||
className={`px-3 py-2 -mb-px border-b-2 text-sm font-medium transition-colors ${
|
||||
trendTab === "totals"
|
||||
? "border-blue-500 text-content-primary"
|
||||
: "border-transparent text-content-muted hover:text-content-primary"
|
||||
}`}
|
||||
>
|
||||
{t("tabModelTotals")}
|
||||
</button>
|
||||
</div>
|
||||
<span className="pb-2 text-xs text-content-muted">
|
||||
{trendTab === "daily"
|
||||
? t("trendLineSub", { n: trendDaily.length })
|
||||
: daily.length > 30
|
||||
? t("cardDailyTrendSubCapped", { n: daily.length })
|
||||
: t("cardDailyTrendSub", { n: daily.length })}
|
||||
: trendTab === "totals"
|
||||
? t("cardModelUsageSub", { n: data.stats.modelsByName.length })
|
||||
: daily.length > 30
|
||||
? t("cardDailyTrendSubCapped", { n: daily.length })
|
||||
: t("cardDailyTrendSub", { n: daily.length })}
|
||||
</span>
|
||||
</div>
|
||||
{/* Active tab content */}
|
||||
@@ -287,6 +302,10 @@ export function DashboardPage() {
|
||||
<div className="flex-1 min-h-[240px]">
|
||||
<TrendLineChart daily={trendDaily} />
|
||||
</div>
|
||||
) : trendTab === "totals" ? (
|
||||
<div className="flex-1 min-h-[240px]">
|
||||
<ModelTotalsChart rows={data.stats.modelsByName} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 min-h-[240px]">
|
||||
<DailyBars
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useTranslation } from "../../i18n";
|
||||
import { useCurrency } from "../../hooks/useCurrency";
|
||||
import { fmtInt, fmtPct, fmtTokens } from "../../lib/dashboard-format";
|
||||
import { modelColor } from "./DailyBars";
|
||||
import type { ModelRow } from "../../types/dashboard";
|
||||
|
||||
interface ModelTotalsChartProps {
|
||||
/** Provider-agnostic model totals, pre-sorted by totalTokens desc. */
|
||||
rows: ModelRow[];
|
||||
}
|
||||
|
||||
/** Horizontal ranked bars: one row per bare model name, providers merged. */
|
||||
export function ModelTotalsChart({ rows }: ModelTotalsChartProps) {
|
||||
const { t } = useTranslation();
|
||||
const { money } = useCurrency();
|
||||
|
||||
if (!rows.length) {
|
||||
return (
|
||||
<div className="flex h-48 items-center justify-center text-sm text-content-muted">
|
||||
{t("noData")}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const max = Math.max(...rows.map((m) => m.totalTokens || 0), 1);
|
||||
|
||||
return (
|
||||
<div className="flex max-h-[360px] flex-col gap-1 overflow-y-auto">
|
||||
{rows.map((m, i) => {
|
||||
const color = i < 10 ? modelColor(i) : "#6b7280";
|
||||
const name = m.isSecondary ? t("subagentModel") : m.modelDisplay || m.model;
|
||||
const tooltip = [
|
||||
name,
|
||||
`${t("kpiRequests")}: ${fmtInt(m.requests)}`,
|
||||
`${t("totalTokens")}: ${fmtInt(m.totalTokens)}`,
|
||||
`${t("colCacheHit")}: ${fmtPct(m.cacheHitRate)}`,
|
||||
`${t("cost")}: ${money(m.costUsd)}`,
|
||||
].join("\n");
|
||||
|
||||
return (
|
||||
<div
|
||||
key={m.model}
|
||||
title={tooltip}
|
||||
className="group flex items-center gap-2 rounded px-1 py-1 cursor-help hover:bg-hover"
|
||||
>
|
||||
<span
|
||||
className="inline-block h-2.5 w-2.5 rounded-sm shrink-0"
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className="w-40 shrink-0 truncate text-xs text-content-primary">
|
||||
{name}
|
||||
{m.costEstimated && (
|
||||
<span className="ml-1 text-[10px] text-yellow-600">({t("estimate")})</span>
|
||||
)}
|
||||
</span>
|
||||
<div className="flex h-4 flex-1 items-center overflow-hidden rounded-sm bg-hover-2/50">
|
||||
<div
|
||||
className="h-full rounded-sm transition-[width] group-hover:opacity-85"
|
||||
style={{
|
||||
width: `${Math.max(2, (m.totalTokens / max) * 100)}%`,
|
||||
backgroundColor: color,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className="w-16 shrink-0 text-right text-xs text-content-muted">
|
||||
{fmtTokens(m.totalTokens)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSessions } from "../../hooks/useSessions";
|
||||
import { fmtInt, fmtTime } from "../../lib/dashboard-format";
|
||||
import { useTranslation } from "../../i18n";
|
||||
import type { SessionRow, WorkspaceRow } from "../../types/sessions";
|
||||
import type { BulkArchiveResult, SessionRow, WorkspaceRow } from "../../types/sessions";
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
const v = Number(n) || 0;
|
||||
@@ -23,6 +23,44 @@ function rowKey(row: SessionRow): string {
|
||||
return `${row.workspaceId}/${row.id}`;
|
||||
}
|
||||
|
||||
type ArchiveAllMode = "month" | "half" | "week" | "custom";
|
||||
|
||||
type ArchiveAllState = {
|
||||
mode: ArchiveAllMode;
|
||||
/** YYYY-MM-DD, used when mode is "custom". */
|
||||
date: string;
|
||||
busy: boolean;
|
||||
result: BulkArchiveResult | null;
|
||||
error: string | null;
|
||||
};
|
||||
|
||||
function localDateInput(d: Date): string {
|
||||
const m = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getDate()).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${m}-${day}`;
|
||||
}
|
||||
|
||||
/** Today minus one month — the default value of the custom-date picker. */
|
||||
function defaultCustomDate(): string {
|
||||
const d = new Date();
|
||||
d.setMonth(d.getMonth() - 1);
|
||||
return localDateInput(d);
|
||||
}
|
||||
|
||||
/** Cutoff epoch ms for the selected option (custom dates start at local midnight). */
|
||||
function cutoffFor(state: ArchiveAllState): number {
|
||||
const now = new Date();
|
||||
if (state.mode === "month" || state.mode === "half" || state.mode === "week") {
|
||||
const d = new Date(now);
|
||||
if (state.mode === "month") d.setMonth(d.getMonth() - 1);
|
||||
if (state.mode === "half") d.setDate(d.getDate() - 15);
|
||||
if (state.mode === "week") d.setDate(d.getDate() - 7);
|
||||
return d.getTime();
|
||||
}
|
||||
const [y, m, day] = state.date.split("-").map(Number);
|
||||
return new Date(y || now.getFullYear(), (m || 1) - 1, day || 1, 0, 0, 0, 0).getTime();
|
||||
}
|
||||
|
||||
type ConfirmState =
|
||||
| { mode: "one"; row: SessionRow }
|
||||
| { mode: "bulk"; rows: SessionRow[] }
|
||||
@@ -52,6 +90,7 @@ export function SessionsPage() {
|
||||
refresh,
|
||||
archiveSession,
|
||||
unarchiveSession,
|
||||
archiveBefore,
|
||||
deleteSession,
|
||||
deleteWorkspace,
|
||||
getPreview,
|
||||
@@ -62,6 +101,7 @@ export function SessionsPage() {
|
||||
const [confirm, setConfirm] = useState<ConfirmState>(null);
|
||||
const [confirmBusy, setConfirmBusy] = useState(false);
|
||||
const [preview, setPreview] = useState<PreviewState>(null);
|
||||
const [archiveAll, setArchiveAll] = useState<ArchiveAllState | null>(null);
|
||||
|
||||
const workspaces = data?.workspaces ?? [];
|
||||
const sessions = data?.sessions ?? [];
|
||||
@@ -199,6 +239,30 @@ export function SessionsPage() {
|
||||
0
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!archiveAll) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setArchiveAll((s) => (s && s.busy ? s : null));
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [archiveAll]);
|
||||
|
||||
const runArchiveAll = async () => {
|
||||
if (!archiveAll || archiveAll.busy) return;
|
||||
const cutoffMs = cutoffFor(archiveAll);
|
||||
setArchiveAll((s) => (s ? { ...s, busy: true, result: null, error: null } : s));
|
||||
try {
|
||||
const res = await archiveBefore(cutoffMs);
|
||||
setArchiveAll((s) => (s ? { ...s, busy: false, result: res } : s));
|
||||
setSelected(new Set());
|
||||
} catch (e) {
|
||||
setArchiveAll((s) =>
|
||||
s ? { ...s, busy: false, error: e instanceof Error ? e.message : String(e) } : s
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
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">
|
||||
@@ -376,6 +440,23 @@ export function SessionsPage() {
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{status !== "archived" && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setArchiveAll({
|
||||
mode: "month",
|
||||
date: defaultCustomDate(),
|
||||
busy: false,
|
||||
result: null,
|
||||
error: null,
|
||||
})
|
||||
}
|
||||
className="px-2 py-1 text-xs rounded border border-border hover:bg-hover-2"
|
||||
>
|
||||
{t("sessionsArchiveAll")}
|
||||
</button>
|
||||
)}
|
||||
<select
|
||||
value={workspace}
|
||||
onChange={(e) => setWorkspace(e.target.value)}
|
||||
@@ -548,6 +629,112 @@ export function SessionsPage() {
|
||||
{data?.home && <>{data.home}</>}
|
||||
</div>
|
||||
|
||||
{/* Bulk archive dialog */}
|
||||
{archiveAll && (
|
||||
<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("archiveAllTitle")}
|
||||
</h3>
|
||||
<p className="text-sm text-content-muted">{t("archiveAllDesc")}</p>
|
||||
<div className="space-y-0.5">
|
||||
{(
|
||||
[
|
||||
["month", t("archiveOptionMonth")],
|
||||
["half", t("archiveOptionHalfMonth")],
|
||||
["week", t("archiveOptionWeek")],
|
||||
["custom", t("archiveOptionCustom")],
|
||||
] as const
|
||||
).map(([mode, label]) => (
|
||||
<label
|
||||
key={mode}
|
||||
className="flex items-center gap-2 rounded-md px-2 py-1.5 text-sm text-content-primary hover:bg-input"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="archiveAllMode"
|
||||
className="h-4 w-4 accent-blue-600"
|
||||
checked={archiveAll.mode === mode}
|
||||
disabled={archiveAll.busy}
|
||||
onChange={() =>
|
||||
setArchiveAll((s) =>
|
||||
s ? { ...s, mode, result: null, error: null } : s
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{archiveAll.mode === "custom" && (
|
||||
<input
|
||||
type="date"
|
||||
value={archiveAll.date}
|
||||
disabled={archiveAll.busy}
|
||||
onChange={(e) =>
|
||||
setArchiveAll((s) => (s ? { ...s, date: e.target.value } : s))
|
||||
}
|
||||
className="bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
|
||||
/>
|
||||
)}
|
||||
<div className="rounded-md border border-border bg-input px-3 py-2.5 text-sm text-content-muted">
|
||||
{t("archiveAllConfirm", {
|
||||
date: new Date(cutoffFor(archiveAll)).toLocaleDateString(
|
||||
locale === "zh" ? "zh-CN" : "en-US"
|
||||
),
|
||||
})}
|
||||
</div>
|
||||
{archiveAll.error && (
|
||||
<div className="rounded-md border border-red-500/40 bg-red-900/20 px-3 py-2 text-sm text-red-300">
|
||||
{t("archiveAllFailed")}: {archiveAll.error}
|
||||
</div>
|
||||
)}
|
||||
{archiveAll.result && archiveAll.result.archived === 0 && (
|
||||
<div className="rounded-md border border-border bg-input px-3 py-2 text-sm text-content-muted">
|
||||
{t("archiveAllEmpty")}
|
||||
</div>
|
||||
)}
|
||||
{archiveAll.result && archiveAll.result.archived > 0 && (
|
||||
<div className="rounded-md border border-emerald-500/40 bg-emerald-900/20 px-3 py-2 text-sm text-emerald-300">
|
||||
{t("archiveAllDone", {
|
||||
archived: archiveAll.result.archived,
|
||||
skipped: archiveAll.result.skipped,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{archiveAll.result && archiveAll.result.errors.length > 0 && (
|
||||
<div className="space-y-1 rounded-md border border-red-500/40 bg-red-900/20 px-3 py-2 text-xs text-red-300">
|
||||
{archiveAll.result.errors.slice(0, 3).map((err, i) => (
|
||||
<div key={i} className="break-all">
|
||||
{err}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 border-t border-border bg-footer px-5 py-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={archiveAll.busy}
|
||||
onClick={() => setArchiveAll(null)}
|
||||
className="px-3 py-1.5 text-sm rounded border border-border hover:bg-hover-2 disabled:opacity-50"
|
||||
>
|
||||
{archiveAll.result ? t("close") : t("cancel")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={archiveAll.busy}
|
||||
onClick={runArchiveAll}
|
||||
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-500 disabled:opacity-50"
|
||||
>
|
||||
{archiveAll.busy ? t("archiveAllRunning") : t("sessionsArchiveAll")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Confirm dialog */}
|
||||
{confirm && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
|
||||
|
||||
@@ -14,6 +14,8 @@ export type UsageKind =
|
||||
| "balance:stepfun"
|
||||
| "balance:novita"
|
||||
| "balance:kimi"
|
||||
| "balance:newapi"
|
||||
| "balance:sub2api"
|
||||
| "plan:kimi_coding"
|
||||
| "plan:zhipu"
|
||||
| "plan:minimax"
|
||||
@@ -30,6 +32,8 @@ export const SUPPORTED_USAGE_KINDS: ReadonlySet<string> = new Set<UsageKind>([
|
||||
"balance:stepfun",
|
||||
"balance:novita",
|
||||
"balance:kimi",
|
||||
"balance:newapi",
|
||||
"balance:sub2api",
|
||||
"plan:kimi_coding",
|
||||
"plan:zhipu",
|
||||
"plan:minimax",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { SummaryResult } from "../types/dashboard";
|
||||
|
||||
export type DashboardRange = "today" | "7d" | "30d" | "all";
|
||||
export type DashboardRange = "today" | "yesterday" | "7d" | "30d" | "all";
|
||||
|
||||
const RANGE_STORAGE_KEY = "kimi-switch-dashboard-range";
|
||||
|
||||
@@ -10,7 +10,7 @@ export function useDashboard() {
|
||||
const [range, setRange] = useState<DashboardRange>(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(RANGE_STORAGE_KEY) as DashboardRange | null;
|
||||
if (stored === "today" || stored === "7d" || stored === "30d" || stored === "all") {
|
||||
if (stored === "today" || stored === "yesterday" || stored === "7d" || stored === "30d" || stored === "all") {
|
||||
return stored;
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
ActionResponse,
|
||||
BulkArchiveResult,
|
||||
PreviewResult,
|
||||
SessionStatusFilter,
|
||||
SessionsResult,
|
||||
@@ -54,6 +55,17 @@ export function useSessions() {
|
||||
[refresh]
|
||||
);
|
||||
|
||||
const archiveBefore = useCallback(
|
||||
async (cutoffMs: number) => {
|
||||
const result = await invoke<BulkArchiveResult>("archive_sessions_before", {
|
||||
cutoffMs,
|
||||
});
|
||||
await refresh();
|
||||
return result;
|
||||
},
|
||||
[refresh]
|
||||
);
|
||||
|
||||
const deleteSession = useCallback(
|
||||
async (workspaceId: string, sessionId: string, sessionStatus?: string) => {
|
||||
await invoke<ActionResponse>("delete_session", {
|
||||
@@ -100,6 +112,7 @@ export function useSessions() {
|
||||
refresh,
|
||||
archiveSession,
|
||||
unarchiveSession,
|
||||
archiveBefore,
|
||||
deleteSession,
|
||||
deleteWorkspace,
|
||||
getPreview,
|
||||
|
||||
@@ -62,7 +62,8 @@ export function useUsageQuery(
|
||||
agent: Agent,
|
||||
providerName: string,
|
||||
usageKinds?: string[],
|
||||
autoIntervalMinutes?: number
|
||||
autoIntervalMinutes?: number,
|
||||
disabled?: boolean
|
||||
): UsageQueryState {
|
||||
const supported = (usageKinds?.length ?? 0) > 0;
|
||||
// Cache key includes the agent so a Kimi Code provider and a Pi provider
|
||||
@@ -79,12 +80,13 @@ export function useUsageQuery(
|
||||
|
||||
const runQuery = useCallback(
|
||||
async (forceRefresh: boolean) => {
|
||||
if (disabled) return;
|
||||
const gen = ++genRef.current;
|
||||
setStatus("loading");
|
||||
setError(undefined);
|
||||
const finish = (entry: CacheEntry) => {
|
||||
cache.set(cacheKey, entry);
|
||||
if (genRef.current !== gen) return;
|
||||
cache.set(cacheKey, entry);
|
||||
setStatus(entry.status);
|
||||
setData(entry.data);
|
||||
setError(entry.error);
|
||||
@@ -129,11 +131,21 @@ export function useUsageQuery(
|
||||
});
|
||||
}
|
||||
},
|
||||
[agent, providerName, cacheKey]
|
||||
[agent, providerName, cacheKey, disabled]
|
||||
);
|
||||
|
||||
// On mount / provider change: serve fresh cache, otherwise query once.
|
||||
useEffect(() => {
|
||||
if (disabled) {
|
||||
// Toggle back off: stop immediately and return to idle so the footer
|
||||
// hides; bump gen so an in-flight response is dropped (no stale write).
|
||||
genRef.current += 1;
|
||||
setStatus("idle");
|
||||
setData([]);
|
||||
setError(undefined);
|
||||
setUpdatedAt(null);
|
||||
return;
|
||||
}
|
||||
if (!supported) return;
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached) {
|
||||
@@ -144,7 +156,7 @@ export function useUsageQuery(
|
||||
if (Date.now() - cached.updatedAt < STALE_TTL_MS) return;
|
||||
}
|
||||
void runQuery(false);
|
||||
}, [supported, cacheKey, runQuery]);
|
||||
}, [supported, cacheKey, runQuery, disabled]);
|
||||
|
||||
// Ignore late responses after unmount.
|
||||
useEffect(() => {
|
||||
@@ -156,12 +168,12 @@ export function useUsageQuery(
|
||||
// Auto query interval — the hook is called once per provider card and both
|
||||
// variants read the same state, so there is no second mount to double-fire.
|
||||
useEffect(() => {
|
||||
if (!supported) return;
|
||||
if (!supported || disabled) return;
|
||||
const mins = autoIntervalMinutes ?? 0;
|
||||
if (mins <= 0) return;
|
||||
const id = setInterval(() => void runQuery(false), mins * 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [supported, autoIntervalMinutes, runQuery]);
|
||||
}, [supported, autoIntervalMinutes, runQuery, disabled]);
|
||||
|
||||
return {
|
||||
status,
|
||||
|
||||
+22
-17
@@ -153,7 +153,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
permissionAsk: "Ask",
|
||||
permissionDangerousGuard: "Dangerous Command Guard",
|
||||
permissionDangerousGuardDesc:
|
||||
"When on (default): Auto mode refuses dangerous commands (rm -rf, shutdown, dd of=, ...) and other modes always prompt; turning it off restores the previous behavior. Env KIMI_CODE_DANGEROUS_COMMAND_GUARD overrides this config",
|
||||
"When on (default): Manual/YOLO modes force a prompt for dangerous commands (rm -rf, shutdown, dd of=, ...) and commands that cannot be statically analyzed; Auto (never-ask) mode no longer intercepts them since kimi-code 0.41.0. Turning it off restores the previous behavior. Env KIMI_CODE_DANGEROUS_COMMAND_GUARD overrides this config",
|
||||
addRule: "+ Add rule",
|
||||
addCommonRules: "Add common rules",
|
||||
hooks: "Lifecycle Hooks",
|
||||
@@ -190,6 +190,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
statusAll: "All",
|
||||
selectAll: "Select all",
|
||||
deselectAll: "Deselect all",
|
||||
invertSelection: "Invert selection",
|
||||
selectedCount: "{n} selected",
|
||||
archive: "Archive",
|
||||
unarchive: "Unarchive",
|
||||
@@ -224,6 +225,19 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
roleUser: "User",
|
||||
roleAssistant: "Assistant",
|
||||
roleSystem: "System",
|
||||
sessionsArchiveAll: "Archive old sessions",
|
||||
archiveAllTitle: "Archive old sessions",
|
||||
archiveAllDesc:
|
||||
"Archives every active session whose last activity is older than the selected date. Files are kept and usage stats stay intact.",
|
||||
archiveOptionMonth: "Older than 1 month",
|
||||
archiveOptionHalfMonth: "Older than 15 days",
|
||||
archiveOptionWeek: "Older than 1 week",
|
||||
archiveOptionCustom: "Specific date",
|
||||
archiveAllConfirm: "Archive every active session last active before {date}. Continue?",
|
||||
archiveAllRunning: "Archiving…",
|
||||
archiveAllDone: "Archived {archived} sessions, skipped {skipped}",
|
||||
archiveAllFailed: "Archive failed",
|
||||
archiveAllEmpty: "No sessions match",
|
||||
|
||||
// Heatmap
|
||||
noData: "No data",
|
||||
@@ -288,6 +302,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
|
||||
// Dashboard — ranges / status
|
||||
rangeToday: "Today",
|
||||
rangeYesterday: "Yesterday",
|
||||
range7d: "7d",
|
||||
range30d: "30d",
|
||||
rangeAll: "All",
|
||||
@@ -309,6 +324,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
cardDailyTrendSubCapped: "Last 30 days · {n} days total",
|
||||
tabModelTrend: "Model usage trend",
|
||||
tabProviderTrend: "Provider–model usage trend",
|
||||
tabModelTotals: "Model usage totals",
|
||||
tabDailyTrend: "Daily usage trend",
|
||||
providerUnknown: "Unknown provider",
|
||||
cardDailyTrendSub: "{n} days",
|
||||
@@ -406,8 +422,10 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
usageTemplate: "Query template",
|
||||
usageTemplateAuto: "Auto-detect",
|
||||
usageTemplateNewapi: "NewAPI gateway",
|
||||
usageTemplateSub2api: "Sub2API gateway",
|
||||
usageAutoDetectHint: "Query balance / plan with the provider's API Key and Base URL",
|
||||
usageNewapiHint: "Query a NewAPI / OneAPI gateway balance (requires a web-console Access Token, not the sk- inference key)",
|
||||
usageSub2apiHint: "Query a Sub2API (Wei-Shaw/sub2api) gateway balance / quota (GET /v1/usage). Reuses the inference sk- API key — no extra credentials; the query URL is optionally overridable",
|
||||
usageOAuthManagedHint: "Official OAuth managed: queries the subscription with your Kimi Code login credentials",
|
||||
usageDetectedKinds: "Detected query kinds",
|
||||
usageNoKinds: "Not detected (switch to the NewAPI template to configure manually)",
|
||||
@@ -428,6 +446,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
usageSwitchToNewapi: "Switch to NewAPI template",
|
||||
usageUnsupportedProvider: "This provider is not supported by auto query",
|
||||
usageTier5h: "5-hour",
|
||||
usageTierDaily: "Daily",
|
||||
usageTierWeekly: "Weekly",
|
||||
usageTierMonthly: "Monthly",
|
||||
usageErrNoKey: "No API key configured",
|
||||
@@ -461,37 +480,23 @@ export const enTranslations: Record<TranslationKey, string> = {
|
||||
// Advanced settings page (WebUI quick open + experimental flags + secondary model)
|
||||
subagentSettings: "Advanced Settings",
|
||||
experimentalFlags: "Experimental Features",
|
||||
otherExperimentalFlags: "Other Experimental Features",
|
||||
experimentalFlagsHint:
|
||||
"Toggles are written to the [experimental] section of config.toml; env vars take precedence and locked toggles cannot be changed here",
|
||||
flagSecondaryModel: "Subagent Secondary Model",
|
||||
flagSecondaryModelDesc: "Newly spawned subagents bind a second (usually cheaper) model config",
|
||||
flagToolSelect: "Tool Select",
|
||||
flagToolSelectDesc: "Enable the experimental tool selection feature",
|
||||
flagMinidbReadmodel: "MiniDB Read Model",
|
||||
flagMinidbReadmodelDesc: "Enable the v2 engine MiniDB read-model backend",
|
||||
flagTower: "Tower Mode",
|
||||
flagTowerDesc: "Enable tower mode: coordinate multiple agents on a shared objective (/tower command)",
|
||||
flagSubagentFork: "Subagent Fork Context",
|
||||
flagSubagentForkDesc: "Agent/AgentSwarm tools can start a subagent with a snapshot of the calling agent's history (fork parameter)",
|
||||
flagWaitFor: "WaitFor Tool",
|
||||
flagWaitForDesc: "The agent can wait for background tasks to finish within the current turn",
|
||||
flagAutoSessionTitle: "Auto Session Title",
|
||||
flagAutoSessionTitleDesc: "Generate session titles automatically via the managed chat_title tool",
|
||||
flagRemoteControl: "Remote Control",
|
||||
flagRemoteControlDesc: "Enable the experimental remote control feature",
|
||||
flagSearchWorker: "Search Worker",
|
||||
flagSearchWorkerDesc: "Run the kap-server global search backend in a background worker host",
|
||||
flagFileHistory: "File History",
|
||||
flagFileHistoryDesc:
|
||||
"Snapshot edited files before/after each turn (last 5 turns across 30 sessions, stored in the session data dir) for real whole-file diffs",
|
||||
flagNotifyUser: "NotifyUser tool",
|
||||
flagNotifyUserDesc: "Experimental Updates panel: paginated progress messages from the main agent and subagents (off by default)",
|
||||
flagDefaultOn: "On by default",
|
||||
lockedByEnv: "Locked by env var",
|
||||
masterEnvOnHint:
|
||||
"KIMI_CODE_EXPERIMENTAL_FLAG is set: flags without an explicit [experimental] entry are forced on; explicit entries in config.toml still win",
|
||||
secondaryModelSection: "Subagent Model (Secondary Model)",
|
||||
secondaryModelDisabledHint:
|
||||
"The experimental flag \"Subagent Secondary Model\" is off and this config will not take effect — enable the toggle above first",
|
||||
secondaryModelLabel: "Secondary model",
|
||||
secondaryModelUnset: "Not configured",
|
||||
secondaryModelInheritedContext: "Inherited context",
|
||||
|
||||
+21
-17
@@ -151,7 +151,7 @@ export const zhTranslations = {
|
||||
permissionAsk: "询问",
|
||||
permissionDangerousGuard: "危险命令防护",
|
||||
permissionDangerousGuardDesc:
|
||||
"开启(默认)时:Auto 模式直接拒绝危险命令(rm -rf、shutdown、dd of= 等),其它模式强制询问;关闭后回归旧行为。环境变量 KIMI_CODE_DANGEROUS_COMMAND_GUARD 会覆盖本配置",
|
||||
"开启(默认)时:Manual/YOLO 模式下,危险命令(rm -rf、shutdown、dd of= 等)和无法静态分析的命令会强制询问;自动(永不询问)模式自 kimi-code 0.41.0 起不再拦截。关闭后回归旧行为。环境变量 KIMI_CODE_DANGEROUS_COMMAND_GUARD 会覆盖本配置",
|
||||
addRule: "+ 添加规则",
|
||||
addCommonRules: "添加常用规则",
|
||||
hooks: "生命周期钩子",
|
||||
@@ -187,6 +187,7 @@ export const zhTranslations = {
|
||||
statusAll: "全部",
|
||||
selectAll: "全选",
|
||||
deselectAll: "取消全选",
|
||||
invertSelection: "反选",
|
||||
selectedCount: "已选 {n} 项",
|
||||
archive: "归档",
|
||||
unarchive: "取消归档",
|
||||
@@ -219,6 +220,18 @@ export const zhTranslations = {
|
||||
roleUser: "用户",
|
||||
roleAssistant: "助手",
|
||||
roleSystem: "系统",
|
||||
sessionsArchiveAll: "一键归档",
|
||||
archiveAllTitle: "一键归档会话",
|
||||
archiveAllDesc: "将归档最后活跃时间早于所选日期的全部活跃会话;文件保留,统计不受影响。",
|
||||
archiveOptionMonth: "1 个月前",
|
||||
archiveOptionHalfMonth: "半个月前",
|
||||
archiveOptionWeek: "1 星期前",
|
||||
archiveOptionCustom: "指定日期",
|
||||
archiveAllConfirm: "将归档最后活跃时间早于 {date} 的全部活跃会话。确认?",
|
||||
archiveAllRunning: "正在归档…",
|
||||
archiveAllDone: "已归档 {archived} 个会话,跳过 {skipped} 个",
|
||||
archiveAllFailed: "归档失败",
|
||||
archiveAllEmpty: "没有符合条件的会话",
|
||||
|
||||
// Heatmap
|
||||
noData: "暂无数据",
|
||||
@@ -283,6 +296,7 @@ export const zhTranslations = {
|
||||
|
||||
// Dashboard — ranges / status
|
||||
rangeToday: "今天",
|
||||
rangeYesterday: "昨天",
|
||||
range7d: "7 天",
|
||||
range30d: "30 天",
|
||||
rangeAll: "全部",
|
||||
@@ -304,6 +318,7 @@ export const zhTranslations = {
|
||||
cardDailyTrendSubCapped: "近 30 天 · 共 {n} 天",
|
||||
tabModelTrend: "模型用量趋势",
|
||||
tabProviderTrend: "供应商模型用量趋势",
|
||||
tabModelTotals: "模型用量统计",
|
||||
tabDailyTrend: "每日用量趋势",
|
||||
providerUnknown: "未知供应商",
|
||||
cardDailyTrendSub: "共 {n} 天",
|
||||
@@ -401,8 +416,10 @@ export const zhTranslations = {
|
||||
usageTemplate: "查询模板",
|
||||
usageTemplateAuto: "自动检测",
|
||||
usageTemplateNewapi: "NewAPI 中转站",
|
||||
usageTemplateSub2api: "Sub2API 中转站",
|
||||
usageAutoDetectHint: "自动使用供应商的 API Key 和 Base URL 查询余额 / 套餐",
|
||||
usageNewapiHint: "查询 NewAPI / OneAPI 中转站的账号余额(需网页后台 Access Token,不是 sk- 推理 Key)",
|
||||
usageSub2apiHint: "查询 Sub2API (Wei-Shaw/sub2api) 面板的余额 / 额度(GET /v1/usage),自动复用推理 sk- API Key,无需额外凭据;可选覆盖查询地址",
|
||||
usageOAuthManagedHint: "官方 OAuth 托管:自动使用 Kimi Code 登录凭据查询订阅用量",
|
||||
usageDetectedKinds: "检测到的查询类型",
|
||||
usageNoKinds: "未识别(可切换到 NewAPI 模板手动配置)",
|
||||
@@ -423,6 +440,7 @@ export const zhTranslations = {
|
||||
usageSwitchToNewapi: "切换到 NewAPI 模板",
|
||||
usageUnsupportedProvider: "此供应商暂不支持自动查询",
|
||||
usageTier5h: "5小时",
|
||||
usageTierDaily: "每日",
|
||||
usageTierWeekly: "7天",
|
||||
usageTierMonthly: "30天",
|
||||
usageErrNoKey: "未配置 API Key",
|
||||
@@ -456,37 +474,23 @@ export const zhTranslations = {
|
||||
// Advanced settings page (WebUI quick open + experimental flags + secondary model)
|
||||
subagentSettings: "高级设置",
|
||||
experimentalFlags: "实验功能开关",
|
||||
otherExperimentalFlags: "其他实验功能",
|
||||
experimentalFlagsHint:
|
||||
"开关写入 config.toml 的 [experimental] 节;环境变量优先级更高,被锁定的开关无法在此修改",
|
||||
flagSecondaryModel: "子代理次主力模型",
|
||||
flagSecondaryModelDesc: "子代理派发时绑定第二份(通常更便宜的)模型配置",
|
||||
flagToolSelect: "工具选择",
|
||||
flagToolSelectDesc: "启用实验性工具选择功能",
|
||||
flagMinidbReadmodel: "MiniDB 读模型",
|
||||
flagMinidbReadmodelDesc: "启用 v2 引擎 MiniDB 读模型后端",
|
||||
flagTower: "Tower 模式",
|
||||
flagTowerDesc: "启用 Tower 多智能体协同模式(/tower 命令切换)",
|
||||
flagSubagentFork: "子代理 Fork 上下文",
|
||||
flagSubagentForkDesc: "Agent/AgentSwarm 工具可携带主代理会话快照启动子代理(fork 参数)",
|
||||
flagWaitFor: "WaitFor 工具",
|
||||
flagWaitForDesc: "代理可在当前回合内等待后台任务完成,而无需结束回合再被唤醒",
|
||||
flagAutoSessionTitle: "自动会话标题",
|
||||
flagAutoSessionTitleDesc: "通过托管 chat_title 工具自动生成会话标题",
|
||||
flagRemoteControl: "远程控制",
|
||||
flagRemoteControlDesc: "启用实验性远程控制功能",
|
||||
flagSearchWorker: "搜索 Worker",
|
||||
flagSearchWorkerDesc: "kap-server 全局搜索的后台 worker 宿主服务",
|
||||
flagFileHistory: "文件历史",
|
||||
flagFileHistoryDesc:
|
||||
"记录每轮编辑文件的前后快照(最近 30 个会话×最近 5 轮,存于会话数据目录),用于真实的整文件 diff",
|
||||
flagNotifyUser: "NotifyUser 工具",
|
||||
flagNotifyUserDesc: "实验性 Updates 面板:分页展示主代理与子代理的进度消息(默认关闭)",
|
||||
flagDefaultOn: "默认开启",
|
||||
lockedByEnv: "被环境变量锁定",
|
||||
masterEnvOnHint:
|
||||
"KIMI_CODE_EXPERIMENTAL_FLAG 已设置:未显式配置的实验项将被强制开启;config.toml 中的显式配置优先生效",
|
||||
secondaryModelSection: "子代理模型(次主力模型)",
|
||||
secondaryModelDisabledHint:
|
||||
"实验开关「子代理次主力模型」未启用,本配置不会生效——请先在上方打开对应开关",
|
||||
secondaryModelLabel: "次主力模型",
|
||||
secondaryModelUnset: "未配置",
|
||||
secondaryModelInheritedContext: "继承上下文长度",
|
||||
|
||||
+101548
-97210
File diff suppressed because it is too large.
Load diff
+83770
-80048
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EXPERIMENTAL_FLAGS,
|
||||
forcedEnvValue,
|
||||
getExperimentalFlags,
|
||||
getSecondaryModel,
|
||||
getSubagentModelPool,
|
||||
isExperimentalFlagSet,
|
||||
isFlagLockedByEnv,
|
||||
removeSubagentPoolEntry,
|
||||
setExperimentalFlag,
|
||||
setSecondaryModelOnly,
|
||||
@@ -163,13 +165,13 @@ describe("setSecondaryModelOnly", () => {
|
||||
|
||||
it("preserves other top-level raw_other sections", () => {
|
||||
const raw = {
|
||||
experimental: { "secondary-model": true },
|
||||
experimental: { wait_for: true },
|
||||
secondary_model: { model: "kimi-k1" },
|
||||
};
|
||||
const next = setSecondaryModelOnly(raw, "kimi-k2") as {
|
||||
experimental?: unknown;
|
||||
};
|
||||
expect(next.experimental).toEqual({ "secondary-model": true });
|
||||
expect(next.experimental).toEqual({ wait_for: true });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -455,32 +457,50 @@ describe("validateSubagentPool", () => {
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// [experimental] — flag registry (kimi-code 0.40.1) + write semantics
|
||||
// [experimental] — flag registry (kimi-code 0.42.0) + write semantics
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("experimental flag registry", () => {
|
||||
it("mirrors the 0.40.1 v2 registry (10 flags incl. file_history)", () => {
|
||||
it("mirrors the 0.43.0 v2 registry (5 flags)", () => {
|
||||
expect(EXPERIMENTAL_FLAGS.map((f) => f.id)).toEqual([
|
||||
"secondary-model",
|
||||
"wait_for",
|
||||
"tool-select",
|
||||
"persistence_minidb_readmodel",
|
||||
"notify_user",
|
||||
"tower",
|
||||
"subagent_fork",
|
||||
"wait_for",
|
||||
]);
|
||||
// Removed upstream: file_history (0.41.0, turn-level file history is
|
||||
// always on), auto_session_title (0.43.0, graduated — AI session titles
|
||||
// are always on, #3749), plus secondary-model /
|
||||
// persistence_minidb_readmodel / remote-control / search_worker
|
||||
// (0.42.0 — promoted or moved to dedicated config, the minidb read-model
|
||||
// now lives under [database]), so the adapter must not mirror them either.
|
||||
for (const id of [
|
||||
"file_history",
|
||||
"auto_session_title",
|
||||
"secondary-model",
|
||||
"persistence_minidb_readmodel",
|
||||
"remote-control",
|
||||
"search_worker",
|
||||
"file_history",
|
||||
]);
|
||||
const fh = EXPERIMENTAL_FLAGS.find((f) => f.id === "file_history");
|
||||
expect(fh?.envVar).toBe("KIMI_CODE_EXPERIMENTAL_FILE_HISTORY");
|
||||
expect(fh?.defaultEnabled).toBeUndefined();
|
||||
]) {
|
||||
expect(EXPERIMENTAL_FLAGS.some((f) => f.id === id)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("secondary-model is on by default since 0.40.1", () => {
|
||||
expect(
|
||||
EXPERIMENTAL_FLAGS.find((f) => f.id === "secondary-model")?.defaultEnabled
|
||||
).toBe(true);
|
||||
it("notify_user is opt-in: no upstream default, own env var", () => {
|
||||
const flag = EXPERIMENTAL_FLAGS.find((f) => f.id === "notify_user");
|
||||
expect(flag?.envVar).toBe("KIMI_CODE_EXPERIMENTAL_NOTIFY_USER");
|
||||
expect(flag?.defaultEnabled).toBeUndefined();
|
||||
});
|
||||
|
||||
it("notify_user is locked by its env var and forced to the env value", () => {
|
||||
const flag = EXPERIMENTAL_FLAGS.find((f) => f.id === "notify_user")!;
|
||||
expect(isFlagLockedByEnv({}, flag)).toBe(false);
|
||||
// A set env var locks the toggle even when it is falsy — it can force
|
||||
// the flag on *or* off.
|
||||
expect(isFlagLockedByEnv({ [flag.envVar]: "0" }, flag)).toBe(true);
|
||||
expect(forcedEnvValue({ [flag.envVar]: "0" }, flag)).toBe(false);
|
||||
expect(forcedEnvValue({ [flag.envVar]: "true" }, flag)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -515,13 +535,13 @@ describe("setExperimentalFlag", () => {
|
||||
|
||||
it("an explicit false coexists with other flags and keeps the section", () => {
|
||||
const next = setExperimentalFlag(
|
||||
rawExp({ "secondary-model": false }),
|
||||
rawExp({ wait_for: false }),
|
||||
"tower",
|
||||
true,
|
||||
{ explicitFalse: true }
|
||||
) as { experimental: Record<string, unknown> };
|
||||
expect(next.experimental).toEqual({
|
||||
"secondary-model": false,
|
||||
wait_for: false,
|
||||
tower: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,7 +24,7 @@ function isTruthyEnv(value: string | undefined): boolean {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ExperimentalFlagDef {
|
||||
/** Flag id as stored in config.toml `[experimental]` (e.g. "secondary-model"). */
|
||||
/** Flag id as stored in config.toml `[experimental]` (e.g. "wait_for"). */
|
||||
id: string;
|
||||
/** Single-feature env var that can force the flag (locks the UI toggle). */
|
||||
envVar: string;
|
||||
@@ -33,43 +33,27 @@ export interface ExperimentalFlagDef {
|
||||
defaultEnabled?: boolean;
|
||||
}
|
||||
|
||||
/** Known experimental flags — mirrors the kimi-code v2 flag registry
|
||||
* (the per-feature flag.ts files under packages/agent-core-v2/src:
|
||||
* secondary-model, tool-select, persistence_minidb_readmodel, tower,
|
||||
* subagent_fork, wait_for, auto_session_title, remote-control,
|
||||
* search_worker, file_history). `acp-v2` was removed upstream and is
|
||||
* dropped here. Keep the env-var list in sync with
|
||||
* `get_experimental_env_status` in src-tauri/src/commands.rs. */
|
||||
/** Known experimental flags — mirrors the kimi-code 0.43.0 v2 flag registry
|
||||
* (the per-feature flag.ts files under packages/agent-core-v2/src):
|
||||
* wait_for, tool-select, notify_user, tower, subagent_fork.
|
||||
* Removed in 0.43.0: auto_session_title (graduated — AI session titles are
|
||||
* always on, #3749). Removed in 0.42.0: secondary-model, remote-control
|
||||
* and search_worker (promoted or dropped upstream — no flag left), and
|
||||
* persistence_minidb_readmodel (now controlled by the `[database]` config
|
||||
* section). `acp-v2` was removed upstream earlier; `file_history` was
|
||||
* removed in kimi-code 0.41.0 (turn-level file history is always on, no
|
||||
* flag). Keep the env-var list in sync with `get_experimental_env_status`
|
||||
* in src-tauri/src/commands.rs. */
|
||||
export const EXPERIMENTAL_FLAGS: ExperimentalFlagDef[] = [
|
||||
{
|
||||
id: "secondary-model",
|
||||
envVar: "KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL",
|
||||
defaultEnabled: true, // on by default since kimi-code 0.40.1
|
||||
},
|
||||
{ id: "tool-select", envVar: "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT" },
|
||||
{
|
||||
id: "persistence_minidb_readmodel",
|
||||
envVar: "KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL",
|
||||
defaultEnabled: true,
|
||||
},
|
||||
{ id: "tower", envVar: "KIMI_CODE_EXPERIMENTAL_TOWER" },
|
||||
{ id: "subagent_fork", envVar: "KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK" },
|
||||
{
|
||||
id: "wait_for",
|
||||
envVar: "KIMI_CODE_EXPERIMENTAL_WAIT_FOR",
|
||||
defaultEnabled: true,
|
||||
},
|
||||
{
|
||||
id: "auto_session_title",
|
||||
envVar: "KIMI_CODE_EXPERIMENTAL_AUTO_SESSION_TITLE",
|
||||
},
|
||||
{ id: "remote-control", envVar: "KIMI_CODE_EXPERIMENTAL_REMOTE_CONTROL" },
|
||||
{
|
||||
id: "search_worker",
|
||||
envVar: "KIMI_CODE_EXPERIMENTAL_SEARCH_WORKER",
|
||||
defaultEnabled: true,
|
||||
},
|
||||
{ id: "file_history", envVar: "KIMI_CODE_EXPERIMENTAL_FILE_HISTORY" },
|
||||
{ id: "tool-select", envVar: "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT" },
|
||||
{ id: "notify_user", envVar: "KIMI_CODE_EXPERIMENTAL_NOTIFY_USER" },
|
||||
{ id: "tower", envVar: "KIMI_CODE_EXPERIMENTAL_TOWER" },
|
||||
{ id: "subagent_fork", envVar: "KIMI_CODE_EXPERIMENTAL_SUBAGENT_FORK" },
|
||||
];
|
||||
|
||||
export const EXPERIMENTAL_MASTER_ENV = "KIMI_CODE_EXPERIMENTAL_FLAG";
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { formatAmount, localizeUsageError, planLabel } from "./usage-display";
|
||||
|
||||
// Minimal TranslateFn: return the key itself so assertions read the key.
|
||||
const t = (key: string) => key;
|
||||
|
||||
describe("localizeUsageError", () => {
|
||||
it("maps known Rust error prefixes to their localization keys", () => {
|
||||
expect(
|
||||
localizeUsageError("unsupported provider: no usage query available", t)
|
||||
).toBe("usageUnsupportedProvider");
|
||||
expect(localizeUsageError("no API key configured", t)).toBe("usageErrNoKey");
|
||||
expect(localizeUsageError("usage query disabled in config panel", t)).toBe(
|
||||
"usageErrDisabled"
|
||||
);
|
||||
expect(
|
||||
localizeUsageError("no Kimi Code OAuth credentials found; run `kimi login` first", t)
|
||||
).toBe("usageErrNoOauth");
|
||||
expect(
|
||||
localizeUsageError("newapi template requires accessToken and userId", t)
|
||||
).toBe("usageErrNewapiCreds");
|
||||
expect(localizeUsageError("Authentication failed: 401 Unauthorized", t)).toBe(
|
||||
"usageInvalidKey"
|
||||
);
|
||||
});
|
||||
|
||||
it("login expired / refresh failed match case-insensitively anywhere", () => {
|
||||
expect(localizeUsageError("LOGIN expired at 12:00", t)).toBe("usageErrLoginExpired");
|
||||
expect(localizeUsageError("oauth refresh failed: 500", t)).toBe("usageErrLoginExpired");
|
||||
});
|
||||
|
||||
it("strips the kinds-loop `{kind}: ` wrapper before matching", () => {
|
||||
// commands.rs 的 kinds 循环把错误包成 "balance:newapi: ..." —— 必须仍命中。
|
||||
expect(
|
||||
localizeUsageError(
|
||||
"balance:newapi: newapi template requires accessToken and userId",
|
||||
t
|
||||
)
|
||||
).toBe("usageErrNewapiCreds");
|
||||
expect(localizeUsageError("plan:zhipu: Authentication failed: 401", t)).toBe(
|
||||
"usageInvalidKey"
|
||||
);
|
||||
expect(localizeUsageError("balance:deepseek: no API key configured", t)).toBe(
|
||||
"usageErrNoKey"
|
||||
);
|
||||
});
|
||||
|
||||
it("passes unknown errors through unchanged (kind prefix retained)", () => {
|
||||
const raw = "balance:openrouter: HTTP 429 too many requests";
|
||||
expect(localizeUsageError(raw, t)).toBe(raw);
|
||||
expect(localizeUsageError("HTTP 500 Something broke", t)).toBe(
|
||||
"HTTP 500 Something broke"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planLabel", () => {
|
||||
it("maps known tier ids and passes unknown names through", () => {
|
||||
expect(planLabel("five_hour", t)).toBe("usageTier5h");
|
||||
expect(planLabel("weekly_limit", t)).toBe("usageTierWeekly");
|
||||
expect(planLabel("monthly_limit", t)).toBe("usageTierMonthly");
|
||||
expect(planLabel("NewAPI", t)).toBe("NewAPI");
|
||||
expect(planLabel("¥", t)).toBe("¥");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatAmount", () => {
|
||||
it("maps CNY and USD to ¥/$ with two decimals", () => {
|
||||
expect(formatAmount(1.5, "CNY")).toBe("¥1.50");
|
||||
expect(formatAmount(1.5, "USD")).toBe("$1.50");
|
||||
});
|
||||
|
||||
it("treats ¤ (U+00A4) as no configured currency symbol", () => {
|
||||
expect(formatAmount(136907472.01013, "¤")).toBe("136907472.01");
|
||||
expect(formatAmount(136907472.01013, "\u{00A4}")).toBe("136907472.01");
|
||||
});
|
||||
|
||||
it("prefixes arbitrary units without a symbol", () => {
|
||||
// Non-integer so the two-decimal rule applies; rounds to 3.00.
|
||||
expect(formatAmount(3.004, "credit")).toBe("credit 3.00");
|
||||
});
|
||||
|
||||
it("renders null/undefined values as —", () => {
|
||||
expect(formatAmount(null, "¤")).toBe("—");
|
||||
expect(formatAmount(undefined, "CNY")).toBe("—");
|
||||
});
|
||||
|
||||
it("keeps integers without decimals", () => {
|
||||
expect(formatAmount(42, "CNY")).toBe("¥42");
|
||||
expect(formatAmount(100, "USD")).toBe("$100");
|
||||
expect(formatAmount(7, "")).toBe("7");
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,8 @@ export function planLabel(name: string, t: TranslateFn): string {
|
||||
switch (name) {
|
||||
case "five_hour":
|
||||
return t("usageTier5h");
|
||||
case "daily_limit":
|
||||
return t("usageTierDaily");
|
||||
case "weekly_limit":
|
||||
return t("usageTierWeekly");
|
||||
case "monthly_limit":
|
||||
@@ -35,12 +37,32 @@ export function planLabel(name: string, t: TranslateFn): string {
|
||||
* src-tauri/src/commands.rs and src-tauri/src/services/*.
|
||||
*/
|
||||
export function localizeUsageError(error: string, t: TranslateFn): string {
|
||||
if (error.startsWith("unsupported provider")) return t("usageUnsupportedProvider");
|
||||
if (error.startsWith("no API key configured")) return t("usageErrNoKey");
|
||||
if (error.startsWith("usage query disabled")) return t("usageErrDisabled");
|
||||
if (/login expired|refresh failed/i.test(error)) return t("usageErrLoginExpired");
|
||||
if (error.startsWith("no Kimi Code OAuth credentials")) return t("usageErrNoOauth");
|
||||
if (error.startsWith("newapi template requires")) return t("usageErrNewapiCreds");
|
||||
if (error.startsWith("Authentication failed")) return t("usageInvalidKey");
|
||||
// commands.rs 的 kinds 循环把单条错误包成 `{kind}: {msg}`(kind 含数字,
|
||||
// 如 plan:zhipu),先剥离再按前缀匹配;未知错误仍回退按原文展示(保留 kind
|
||||
// 前缀,属诊断细节)。
|
||||
const stripped = error.replace(/^(balance|plan):[a-z0-9_]+:\s*/, "");
|
||||
if (stripped.startsWith("unsupported provider")) return t("usageUnsupportedProvider");
|
||||
if (stripped.startsWith("no API key configured")) return t("usageErrNoKey");
|
||||
if (stripped.startsWith("usage query disabled")) return t("usageErrDisabled");
|
||||
if (/login expired|refresh failed/i.test(stripped)) return t("usageErrLoginExpired");
|
||||
if (stripped.startsWith("no Kimi Code OAuth credentials")) return t("usageErrNoOauth");
|
||||
if (stripped.startsWith("newapi template requires")) return t("usageErrNewapiCreds");
|
||||
if (stripped.startsWith("Authentication failed")) return t("usageInvalidKey");
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a usage amount with its unit. `¤` (U+00A4) is NewAPI's placeholder
|
||||
* when the site has no custom currency symbol configured — treat it as "no
|
||||
* symbol" and render only the number.
|
||||
*/
|
||||
export function formatAmount(
|
||||
value: number | null | undefined,
|
||||
unit?: string | null
|
||||
): string {
|
||||
if (value == null) return "—";
|
||||
const symbol =
|
||||
unit === "CNY" ? "¥" : unit === "USD" ? "$" : unit && unit.trim() !== "¤" ? `${unit} ` : "";
|
||||
const num = Number.isInteger(value) ? String(value) : value.toFixed(2);
|
||||
return `${symbol}${num}`;
|
||||
}
|
||||
@@ -52,6 +52,8 @@ export interface RangeStats {
|
||||
totals: TotalsRow;
|
||||
daily: DailyRow[];
|
||||
models: ModelRow[];
|
||||
/** Model totals keyed by bare model name — the same model across providers merges into one row. */
|
||||
modelsByName: ModelRow[];
|
||||
recent: RecentRow[];
|
||||
recentTotal: number;
|
||||
recentLimit: number;
|
||||
|
||||
+8
-5
@@ -75,11 +75,12 @@ export interface Config {
|
||||
/**
|
||||
* Usage query configuration (mirrors the Rust `UsageConfig`, camelCase).
|
||||
* "auto" = query kinds from usageKinds/host detect; "newapi" = query a
|
||||
* NewAPI/OneAPI gateway with accessToken + userId.
|
||||
* NewAPI/OneAPI gateway with accessToken + userId; "sub2api" = query a
|
||||
* Sub2API (Wei-Shaw/sub2api) gateway, reusing the inference API key.
|
||||
*/
|
||||
export interface UsageConfig {
|
||||
enabled: boolean;
|
||||
templateType: "auto" | "newapi";
|
||||
templateType: "auto" | "newapi" | "sub2api";
|
||||
baseUrl?: string;
|
||||
/** NewAPI web-console access token (NOT the sk- inference key). */
|
||||
accessToken?: string;
|
||||
@@ -151,9 +152,11 @@ export interface AgentSettings {
|
||||
background?: BackgroundConfig;
|
||||
permission?: {
|
||||
rules?: PermissionRule[];
|
||||
/** kimi-code 0.40.1 `[permission]` key. Default true when the key is
|
||||
* absent: Auto mode refuses dangerous commands (rm -rf, shutdown,
|
||||
* dd of=, …) and other modes always prompt; false restores the
|
||||
/** kimi-code `[permission]` key. Default true when the key is
|
||||
* absent: since 0.41.0 the guard only gates Manual/YOLO modes —
|
||||
* dangerous commands (rm -rf, shutdown, dd of=, …) and commands
|
||||
* that cannot be statically analyzed force a prompt, while Auto
|
||||
* (never-ask) mode no longer intercepts them; false restores the
|
||||
* previous behavior. Env KIMI_CODE_DANGEROUS_COMMAND_GUARD (literal
|
||||
* "true"/"false" only) outranks this config. */
|
||||
dangerous_command_guard?: boolean;
|
||||
|
||||
@@ -39,6 +39,12 @@ export interface ActionResponse {
|
||||
deleted?: boolean | null;
|
||||
}
|
||||
|
||||
export interface BulkArchiveResult {
|
||||
archived: number;
|
||||
skipped: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export interface PreviewMessage {
|
||||
role: string;
|
||||
time: number | null;
|
||||
|
||||
+10
-10
@@ -6,10 +6,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#efebe1" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#231f1a" media="(prefers-color-scheme: dark)" />
|
||||
<title>Kimi Switch — 多 LLM 供应商统一管理 · 用量监控 · 账单一目了然</title>
|
||||
<title>Kimi Switch — 多 LLM 供应商配置管理 · 用量与账单监控</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Kimi Switch / KimiCodeSwitch — Windows 桌面端多 LLM 供应商统一管理器,一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动,用量账单实时监控,开源 MIT。"
|
||||
content="Kimi Switch / KimiCodeSwitch — 桌面端 LLM 供应商配置管理器:22 个预设选好即写入 config.toml,用量与账单直读各厂商官方接口。Tauri + Rust,开源 MIT。"
|
||||
/>
|
||||
<meta
|
||||
name="keywords"
|
||||
@@ -18,20 +18,20 @@
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:title" content="Kimi Switch — 多 LLM 供应商统一管理" />
|
||||
<meta property="og:title" content="Kimi Switch — 多 LLM 供应商配置管理" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
||||
content="把 Kimi Code 的供应商配置搬进图形界面:22 个预设、用量与账单直读官方接口,免费开源 MIT。"
|
||||
/>
|
||||
<meta property="og:url" content="https://billowliu2.github.io/KimiSwitch/" />
|
||||
<meta property="og:image" content="https://billowliu2.github.io/KimiSwitch/og.png" />
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="Kimi Switch — 多 LLM 供应商统一管理" />
|
||||
<meta name="twitter:title" content="Kimi Switch — 多 LLM 供应商配置管理" />
|
||||
<meta
|
||||
name="twitter:description"
|
||||
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
||||
content="把 Kimi Code 的供应商配置搬进图形界面:22 个预设、用量与账单直读官方接口,免费开源 MIT。"
|
||||
/>
|
||||
<meta name="twitter:image" content="https://billowliu2.github.io/KimiSwitch/og.png" />
|
||||
|
||||
@@ -49,10 +49,10 @@
|
||||
"alternateName": ["KimiSwitch", "KimiCodeSwitch", "Kimi Switch", "KimiCode Switch"],
|
||||
"url": "https://billowliu2.github.io/KimiSwitch/",
|
||||
"applicationCategory": "DeveloperApplication",
|
||||
"operatingSystem": "Windows 10, Windows 11",
|
||||
"softwareVersion": "0.6.7",
|
||||
"dateModified": "2026-08-01",
|
||||
"description": "Windows 桌面端多 LLM 供应商统一管理器,一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动,用量账单实时监控,开源 MIT。",
|
||||
"operatingSystem": "Windows 10, Windows 11, macOS, Linux",
|
||||
"softwareVersion": "0.7.12",
|
||||
"dateModified": "2026-09-03",
|
||||
"description": "桌面端 LLM 供应商配置管理器:22 个预设选好即写入 config.toml,用量与账单直读各厂商官方接口。Tauri + Rust,开源 MIT。",
|
||||
"downloadUrl": "https://github.com/billowliu2/KimiSwitch/releases",
|
||||
"softwareHelp": "https://github.com/billowliu2/KimiSwitch",
|
||||
"license": "https://opensource.org/licenses/MIT",
|
||||
|
||||
@@ -87,7 +87,7 @@ export default function Footer() {
|
||||
href={link.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="group flex items-start gap-3 rounded-2xl border border-border bg-card p-4 transition-all duration-200 hover:-translate-y-0.5 hover:border-primary/40"
|
||||
className="group flex items-start gap-3 rounded-xl border border-border bg-card p-4 transition-all duration-200 hover:-translate-y-0.5 hover:border-primary/40"
|
||||
style={{ boxShadow: "var(--shadow-soft)" }}
|
||||
>
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-white">
|
||||
|
||||
@@ -24,7 +24,9 @@ export default function Nav() {
|
||||
/>
|
||||
<span>Kimi Switch</span>
|
||||
</NavLink>
|
||||
<nav className="flex items-center gap-5 overflow-x-auto overflow-y-hidden text-sm text-muted-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<nav
|
||||
aria-label="Primary"
|
||||
className="flex items-center gap-5 overflow-x-auto overflow-y-hidden text-sm text-muted-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{links.map((l) => (
|
||||
<NavLink
|
||||
key={l.to}
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function SectionShell({ id, title, subtitle, children }: SectionS
|
||||
ref={ref}
|
||||
id={id}
|
||||
aria-labelledby={`${id}-title`}
|
||||
className={`py-20 transition-all duration-700 ease-out ${
|
||||
className={`pt-16 pb-20 transition-all duration-700 ease-out ${
|
||||
inView
|
||||
? "motion-safe:opacity-100 motion-safe:translate-y-0"
|
||||
: "motion-safe:opacity-0 motion-safe:translate-y-6"
|
||||
@@ -30,7 +30,9 @@ export default function SectionShell({ id, title, subtitle, children }: SectionS
|
||||
{title}
|
||||
</h2>
|
||||
{subtitle && (
|
||||
<p className="mt-3 text-base leading-relaxed text-muted-foreground">{subtitle}</p>
|
||||
<p className="mt-3 max-w-[68ch] text-base leading-relaxed text-muted-foreground">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
|
||||
+100
-78
@@ -16,43 +16,43 @@ const zh = {
|
||||
performance: "性能",
|
||||
changelog: "更新日志",
|
||||
download: "下载",
|
||||
downloadBtn: "下载 v0.7.4",
|
||||
downloadBtn: "下载 v0.7.12",
|
||||
},
|
||||
hero: {
|
||||
badge: "v0.7.4 · 开源 MIT · Windows / macOS / Linux",
|
||||
badge: "v0.7.12 · 开源 MIT · Windows / macOS / Linux",
|
||||
titleBefore: "统一管理你的",
|
||||
titleAccent: "AI 供应商",
|
||||
titleAfter: "",
|
||||
subtitle:
|
||||
"一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动,用量与账单一目了然。",
|
||||
"Kimi Code 的供应商配置不用再手改 config.toml:22 个预设选好即写入(写入前自动备份),用量与账单直读各厂商官方接口。",
|
||||
download: "免费下载",
|
||||
source: "查看源码",
|
||||
stats: [
|
||||
{ value: "22", label: "预设供应商" },
|
||||
{ value: "5910", label: "模型价格库" },
|
||||
{ value: "100%", label: "开源免费" },
|
||||
{ value: "7495", label: "模型价格库" },
|
||||
{ value: "MIT", label: "开源协议" },
|
||||
],
|
||||
},
|
||||
features: {
|
||||
title: "核心功能",
|
||||
subtitle: "从多供应商管理到用量监控,一站搞定。",
|
||||
subtitle: "配置、切换、用量、账单、会话——都落在本机那份 ~/.kimi-code/config.toml 上。",
|
||||
items: [
|
||||
{
|
||||
id: "multi-provider",
|
||||
title: "多供应商管理",
|
||||
desc: "Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动等 22 个预设,一键添加与切换。",
|
||||
desc: "Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动等 22 个预设,Base URL 与模型映射已填好,选定即写入配置。",
|
||||
img: "screenshots/preset-picker.png",
|
||||
},
|
||||
{
|
||||
id: "custom-provider",
|
||||
title: "自定义供应商",
|
||||
desc: "自定义 Base URL / API Key / 模型映射,支持 JSON 高级编辑。",
|
||||
desc: "Base URL、API Key、模型别名逐字段编辑,也可切到 JSON 页签直接改;配置里的未知字段原样保留。",
|
||||
img: "screenshots/edit-provider-basic-managed.png",
|
||||
},
|
||||
{
|
||||
id: "usage",
|
||||
title: "用量与账单监控",
|
||||
desc: "套餐类 5 小时 / 每周用量 + 按量余额,models.dev 真实价格计算成本,卡片直显。",
|
||||
desc: "套餐的 5 小时 / 每周额度与按量余额直接显示在卡片上,成本按 models.dev 牌价折算。",
|
||||
img: "screenshots/dashboard-light.png",
|
||||
},
|
||||
{
|
||||
@@ -63,7 +63,7 @@ const zh = {
|
||||
},
|
||||
{
|
||||
id: "kimi-auth",
|
||||
title: "Kimi 一键授权登录",
|
||||
title: "Kimi 授权登录",
|
||||
desc: "应用内置设备码授权(等同 kimi login),浏览器授权即用,15 分钟过期自动续期。",
|
||||
img: "screenshots/kimi-oauth-dialog.png",
|
||||
},
|
||||
@@ -75,31 +75,31 @@ const zh = {
|
||||
},
|
||||
{
|
||||
id: "model-discovery",
|
||||
title: "智能模型发现",
|
||||
desc: "模型能力 / 上下文大小自动从 models.dev 同步,构建时自动拉取,5910 模型覆盖。",
|
||||
title: "模型自动发现",
|
||||
desc: "可用模型直接问供应商 API;显示名 / 上下文 / 能力取自 models.dev 快照(当前 7495 个模型、212 家供应商)。",
|
||||
img: "screenshots/kimi-cli-select-model.png",
|
||||
},
|
||||
{
|
||||
id: "auto-update",
|
||||
title: "自动更新",
|
||||
desc: "自动检测新版本,一键下载安装,始终保持最新。",
|
||||
desc: "启动时和每 8 小时各查一次新版本(私有镜像优先、GitHub 兜底),应用内下载并引导安装。",
|
||||
img: "screenshots/settings.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
showcase: {
|
||||
title: "界面演示",
|
||||
subtitle: "真实界面截图,所见即所得。",
|
||||
subtitle: "以下截图取自 v0.7.12 实机运行。",
|
||||
items: [
|
||||
{
|
||||
src: "screenshots/usage-config-page.png",
|
||||
title: "配置用量查询",
|
||||
desc: "NewAPI 中转站模板、超时与自动刷新、测试查询一屏搞定",
|
||||
desc: "NewAPI 中转站模板、超时与自动刷新、测试查询放在同一页",
|
||||
},
|
||||
{
|
||||
src: "screenshots/preset-picker.png",
|
||||
title: "预设供应商",
|
||||
desc: "22 个预设开箱即用,一键添加常用厂商",
|
||||
desc: "22 个预设,勾选即可添加常用厂商",
|
||||
},
|
||||
{
|
||||
src: "screenshots/kimi-oauth-dialog.png",
|
||||
@@ -125,7 +125,7 @@ const zh = {
|
||||
},
|
||||
performance: {
|
||||
title: "轻量原生",
|
||||
subtitle: "Tauri + Rust 内核,WebView2 前端,常驻托盘零负担。",
|
||||
subtitle: "Tauri + Rust,复用系统 WebView2,不打包 Chromium。下面三项是空闲状态实测。",
|
||||
metrics: [
|
||||
{ target: 93, suffix: " MB", label: "Working Set", desc: "程序空闲态工作集内存" },
|
||||
{ target: 34, suffix: " MB", label: "Private WS", desc: "独占内存(WebView2 共享部分扣除)" },
|
||||
@@ -140,6 +140,17 @@ const zh = {
|
||||
syncedNote: "数据已同步 GitHub Releases",
|
||||
fallbackNote: "内置版本记录",
|
||||
entries: [
|
||||
{
|
||||
version: "v0.7.12",
|
||||
date: "2026-09-03",
|
||||
items: [
|
||||
"适配 kimi-code 0.40.1:实验 flag 清单更新(新增 file_history / search_worker,secondary-model 默认开启)",
|
||||
"flag 优先级语义修正:显式配置优先于总开关,总开关不再锁定全部实验开关",
|
||||
"新增危险命令守卫开关:Auto 模式直接拒绝 rm -rf / shutdown 等危险命令,其它模式强制询问",
|
||||
"修复 WebUI 首次打开慢时多次点击的竞态报错",
|
||||
"models-dev 快照更新至 7495 模型 / 212 供应商",
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "v0.7.4",
|
||||
date: "2026-08-09",
|
||||
@@ -170,7 +181,7 @@ const zh = {
|
||||
"兼容 kimi-code 0.33+(v2 引擎):循环控制改用新键 max_attempts_per_step,旧配置自动迁移",
|
||||
"models.dev 模型列表与价格数据同步更新",
|
||||
"官网企业版视觉升级;出品公司标识统一为 codingplan.site",
|
||||
"macOS 安装优化:Release 附带 install-macos.sh 一键脚本,自动清除下载隔离,免去手动右键打开",
|
||||
"macOS 安装优化:Release 附带 install-macos.sh,自动清除下载隔离,免去手动右键打开",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -201,7 +212,7 @@ const zh = {
|
||||
version: "v0.6.9",
|
||||
date: "2026-08-01",
|
||||
items: [
|
||||
"最近请求新增缓存命中率列,每次请求命中一目了然",
|
||||
"最近请求新增缓存命中率列,逐条请求的命中情况直接可见",
|
||||
"中文模式费用按最新汇率换算人民币(¥)显示,英文模式保持美元",
|
||||
"仪表盘性能再优化:价格解析记忆化缓存,扫描从秒级降到百毫秒级;右上角新增加载耗时/数据量跟踪",
|
||||
],
|
||||
@@ -229,7 +240,7 @@ const zh = {
|
||||
version: "v0.6.6",
|
||||
date: "2026-08-01",
|
||||
items: [
|
||||
"模型价格对标 models.dev,覆盖 5910 个模型",
|
||||
"模型价格数据对标 models.dev,快照随版本更新",
|
||||
"新增基元律动供应商与推荐链接",
|
||||
"设置页文案与参考来源说明优化",
|
||||
],
|
||||
@@ -311,34 +322,34 @@ const zh = {
|
||||
},
|
||||
download: {
|
||||
title: "下载 Kimi Switch",
|
||||
subtitle: "当前版本 v0.7.4 · Windows / macOS / Linux 三平台已发布",
|
||||
autoUpdate: "应用内置自动检测更新,新版本发布后在设置页一键升级。",
|
||||
subtitle: "当前版本 v0.7.12 · Windows / macOS / Linux 三平台已发布",
|
||||
autoUpdate: "更新检查跑在启动时和每 8 小时的周期任务里,设置页也可以手动触发。",
|
||||
ready: "已发布",
|
||||
wip: "开发中",
|
||||
githubBtn: "GitHub 下载",
|
||||
mirrorBtn: "镜像下载",
|
||||
items: [
|
||||
{ id: "windows", name: "Windows", ready: true, note: ".msi 安装包,系统托盘常驻" },
|
||||
{ id: "macos", name: "macOS", ready: true, note: ".dmg 安装包(Apple Silicon),未签名:下载 install-macos.sh 后运行 bash install-macos.sh 一键安装" },
|
||||
{ id: "macos", name: "macOS", ready: true, note: ".dmg 安装包(Apple Silicon),未签名:下载 Release 附带的 install-macos.sh,运行 bash install-macos.sh 清除隔离属性" },
|
||||
{ id: "linux", name: "Linux", ready: true, note: ".deb / .AppImage / .rpm 三格式" },
|
||||
],
|
||||
},
|
||||
cta: {
|
||||
title: "现在就把所有供应商,放进一个应用",
|
||||
subtitle: "免费 · 开源 MIT · 一分钟完成安装",
|
||||
title: "把供应商配置、用量和账单收进一个窗口",
|
||||
subtitle: "免费 · MIT 开源 · Windows / macOS / Linux",
|
||||
download: "免费下载",
|
||||
source: "GitHub 源码",
|
||||
},
|
||||
seo: {
|
||||
home: {
|
||||
title: "Kimi Switch — 多 LLM 供应商统一管理 · 用量监控 · 账单一目了然",
|
||||
title: "Kimi Switch — 多 LLM 供应商配置管理 · 用量与账单监控",
|
||||
description:
|
||||
"Kimi Switch / KimiCodeSwitch — Windows 桌面端多 LLM 供应商统一管理器,一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动,用量账单实时监控,开源 MIT。",
|
||||
"Kimi Switch / KimiCodeSwitch — 桌面端 LLM 供应商配置管理器:22 个预设选好即写入 config.toml,用量与账单直读各厂商官方接口。Tauri + Rust,开源 MIT。",
|
||||
},
|
||||
features: {
|
||||
title: "核心功能 - Kimi Switch",
|
||||
description:
|
||||
"Kimi Switch 核心功能:多供应商管理、用量与账单监控、Kimi 一键授权登录、智能模型发现与自动更新,22 个预设开箱即用。",
|
||||
"Kimi Switch 功能页:多供应商预设与自定义配置、用量与账单监控、Kimi 设备码授权、模型自动发现与周期更新检查。",
|
||||
},
|
||||
changelog: {
|
||||
title: "更新日志 - Kimi Switch",
|
||||
@@ -380,116 +391,116 @@ const en: Dict = {
|
||||
performance: "Performance",
|
||||
changelog: "Changelog",
|
||||
download: "Download",
|
||||
downloadBtn: "Download v0.7.4",
|
||||
downloadBtn: "Download v0.7.12",
|
||||
},
|
||||
hero: {
|
||||
badge: "v0.7.4 · Open source MIT · Windows / macOS / Linux",
|
||||
badge: "v0.7.12 · Open source MIT · Windows / macOS / Linux",
|
||||
titleBefore: "One app for all your ",
|
||||
titleAccent: "AI providers",
|
||||
titleAfter: "",
|
||||
subtitle:
|
||||
"Switch between Kimi, Zhipu GLM, MiniMax, DeepSeek, OpenRouter and TokenRhythm in one click, with usage and billing at a glance.",
|
||||
"Stop hand-editing ~/.kimi-code/config.toml. Pick one of 22 provider presets and it goes straight into your config (backed up first); usage and billing read from each vendor's own API.",
|
||||
download: "Free Download",
|
||||
source: "View Source",
|
||||
source: "View source",
|
||||
stats: [
|
||||
{ value: "22", label: "Provider presets" },
|
||||
{ value: "5910", label: "Model price DB" },
|
||||
{ value: "100%", label: "Open source" },
|
||||
{ value: "7495", label: "Model price DB" },
|
||||
{ value: "MIT", label: "License" },
|
||||
],
|
||||
},
|
||||
features: {
|
||||
title: "Core Features",
|
||||
subtitle: "From multi-provider management to usage monitoring, all in one place.",
|
||||
title: "Core features",
|
||||
subtitle: "Configuration, switching, usage, billing and sessions — all against the config.toml on your machine.",
|
||||
items: [
|
||||
{
|
||||
id: "multi-provider",
|
||||
title: "Multi-Provider Management",
|
||||
desc: "22 presets including Kimi, Zhipu GLM, MiniMax, DeepSeek, OpenRouter and TokenRhythm. Add and switch in one click.",
|
||||
title: "Provider presets",
|
||||
desc: "22 presets — Kimi, Zhipu GLM, MiniMax, DeepSeek, OpenRouter, TokenRhythm and more — ship with Base URL and model mapping filled in; picking one writes it to your config.",
|
||||
img: "screenshots/preset-picker.png",
|
||||
},
|
||||
{
|
||||
id: "custom-provider",
|
||||
title: "Custom Providers",
|
||||
desc: "Custom Base URL, API Key and model mapping, with advanced JSON editing.",
|
||||
title: "Custom providers",
|
||||
desc: "Edit Base URL, API key and model aliases field by field, or switch to the raw JSON tab; unknown fields are passed through untouched.",
|
||||
img: "screenshots/edit-provider-basic-managed.png",
|
||||
},
|
||||
{
|
||||
id: "usage",
|
||||
title: "Usage & Billing",
|
||||
desc: "5-hour / weekly plan quotas plus pay-as-you-go balance, priced with real models.dev rates and shown on cards.",
|
||||
title: "Usage & billing",
|
||||
desc: "5-hour / weekly plan quotas and pay-as-you-go balance shown directly on cards, with costs computed at models.dev list prices.",
|
||||
img: "screenshots/dashboard-light.png",
|
||||
},
|
||||
{
|
||||
id: "sessions",
|
||||
title: "Session Manager",
|
||||
title: "Session manager",
|
||||
desc: "Browse, search and resume past sessions across providers.",
|
||||
img: "screenshots/sessions-light.png",
|
||||
},
|
||||
{
|
||||
id: "kimi-auth",
|
||||
title: "One-Click Kimi Login",
|
||||
title: "Kimi device-code login",
|
||||
desc: "Built-in device-code authorization (same as kimi login). Authorize in the browser; 15-minute expiry auto-renews.",
|
||||
img: "screenshots/kimi-oauth-dialog.png",
|
||||
},
|
||||
{
|
||||
id: "usage-config",
|
||||
title: "Usage Query Setup",
|
||||
title: "Usage query setup",
|
||||
desc: "Full-page config: NewAPI relay templates, timeout, auto-refresh interval, and a test query.",
|
||||
img: "screenshots/usage-config-page.png",
|
||||
},
|
||||
{
|
||||
id: "model-discovery",
|
||||
title: "Smart Model Discovery",
|
||||
desc: "Model capabilities and context sizes sync from models.dev at build time, covering 5910 models.",
|
||||
title: "Model discovery",
|
||||
desc: "Model lists are fetched from the provider API itself; display names, context sizes and capabilities come from a build-time models.dev snapshot (7495 models, 212 providers).",
|
||||
img: "screenshots/kimi-cli-select-model.png",
|
||||
},
|
||||
{
|
||||
id: "auto-update",
|
||||
title: "Auto Updates",
|
||||
desc: "Automatically detects new versions and installs them in one click.",
|
||||
title: "Auto updates",
|
||||
desc: "Checks at startup and every 8 hours (private mirror first, GitHub fallback), downloads in-app and walks you through install.",
|
||||
img: "screenshots/settings.png",
|
||||
},
|
||||
],
|
||||
},
|
||||
showcase: {
|
||||
title: "Screenshots",
|
||||
subtitle: "Real screenshots from the app. What you see is what you get.",
|
||||
subtitle: "All screenshots below are taken from the running v0.7.12 build.",
|
||||
items: [
|
||||
{
|
||||
src: "screenshots/usage-config-page.png",
|
||||
title: "Usage Query Setup",
|
||||
title: "Usage query setup",
|
||||
desc: "NewAPI relay templates, timeout and auto-refresh, plus a test query, all on one page",
|
||||
},
|
||||
{
|
||||
src: "screenshots/preset-picker.png",
|
||||
title: "Provider Presets",
|
||||
desc: "22 presets ready out of the box, add popular vendors in one click",
|
||||
title: "Provider presets",
|
||||
desc: "Tick through 22 presets to add popular vendors",
|
||||
},
|
||||
{
|
||||
src: "screenshots/kimi-oauth-dialog.png",
|
||||
title: "Kimi Authorization",
|
||||
title: "Kimi authorization",
|
||||
desc: "Device-code flow identical to kimi login, auto-renews on expiry",
|
||||
},
|
||||
{
|
||||
src: "screenshots/dashboard-daily-detail.png",
|
||||
title: "Usage Details",
|
||||
title: "Usage details",
|
||||
desc: "Daily token and cost trends",
|
||||
},
|
||||
{
|
||||
src: "screenshots/sessions-light.png",
|
||||
title: "Session Manager",
|
||||
title: "Session manager",
|
||||
desc: "Browse and resume past sessions across providers",
|
||||
},
|
||||
{
|
||||
src: "screenshots/kimi-plan-quota-card.png",
|
||||
title: "Plan Quota Card",
|
||||
desc: "5-hour / weekly quotas at a glance",
|
||||
title: "Plan quota card",
|
||||
desc: "5-hour / weekly quotas read straight off the card",
|
||||
},
|
||||
],
|
||||
},
|
||||
performance: {
|
||||
title: "Lightweight & Native",
|
||||
subtitle: "Tauri + Rust core with a WebView2 frontend. Zero tray overhead.",
|
||||
title: "Lightweight and native",
|
||||
subtitle: "Tauri + Rust on the system WebView2 — no bundled Chromium. The three numbers below are idle-state measurements.",
|
||||
metrics: [
|
||||
{ target: 93, suffix: " MB", label: "Working Set", desc: "Idle working-set memory" },
|
||||
{ target: 34, suffix: " MB", label: "Private WS", desc: "Private memory (shared WebView2 excluded)" },
|
||||
@@ -504,6 +515,17 @@ const en: Dict = {
|
||||
syncedNote: "Synced from GitHub Releases",
|
||||
fallbackNote: "Built-in release notes",
|
||||
entries: [
|
||||
{
|
||||
version: "v0.7.12",
|
||||
date: "2026-09-03",
|
||||
items: [
|
||||
"Adapted to kimi-code 0.40.1: experimental flag list updated (adds file_history / search_worker; secondary-model now on by default)",
|
||||
"Flag priority semantics fixed: explicit configuration takes precedence over the master toggle, which no longer locks every switch",
|
||||
"New dangerous-command guard toggle: Auto mode rejects rm -rf / shutdown outright, other modes force a confirmation prompt",
|
||||
"Fix race-condition errors when clicking repeatedly while the WebUI is slow to open for the first time",
|
||||
"models-dev snapshot updated to 7495 models / 212 providers",
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "v0.7.4",
|
||||
date: "2026-08-09",
|
||||
@@ -534,7 +556,7 @@ const en: Dict = {
|
||||
"Compatible with kimi-code 0.33+ (v2 engine): loop control now writes max_attempts_per_step with auto-migration",
|
||||
"models.dev model list and pricing snapshot synced",
|
||||
"Enterprise-style website refresh; publisher identity unified as codingplan.site",
|
||||
"macOS install polish: releases now ship install-macos.sh, a one-click script that clears the download quarantine",
|
||||
"macOS install polish: releases now ship install-macos.sh, which clears the download quarantine for you",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -565,7 +587,7 @@ const en: Dict = {
|
||||
version: "v0.6.9",
|
||||
date: "2026-08-01",
|
||||
items: [
|
||||
"Recent requests gain a cache-hit-rate column, per request at a glance",
|
||||
"Recent requests gain a cache-hit-rate column, shown per request",
|
||||
"Chinese UI now shows costs in CNY (latest exchange rate); English keeps USD",
|
||||
"Dashboard speedup: memoized price resolution drops the scan from seconds to milliseconds; load time / payload tracking in the top-right corner",
|
||||
],
|
||||
@@ -592,7 +614,7 @@ const en: Dict = {
|
||||
version: "v0.6.6",
|
||||
date: "2026-08-01",
|
||||
items: [
|
||||
"Model pricing aligned with models.dev, covering 5910 models",
|
||||
"Model pricing data aligned with models.dev, snapshot refreshed per release",
|
||||
"New TokenRhythm provider with referral link",
|
||||
"Settings copy and source attribution polish",
|
||||
],
|
||||
@@ -652,56 +674,56 @@ const en: Dict = {
|
||||
],
|
||||
},
|
||||
privacy: {
|
||||
title: "Your Data Stays on Your Machine",
|
||||
title: "Your data stays on your machine",
|
||||
subtitle: "Our privacy and open-source commitments in three sentences.",
|
||||
items: [
|
||||
{
|
||||
id: "local",
|
||||
title: "Local Storage",
|
||||
title: "Local storage",
|
||||
desc: "Configs and usage data live only in ~/.kimi-switch and config.toml. Nothing is uploaded.",
|
||||
},
|
||||
{
|
||||
id: "direct",
|
||||
title: "Direct Connections",
|
||||
title: "Direct connections",
|
||||
desc: "Billing queries go straight to each vendor's official API. No middlemen, no tracking.",
|
||||
},
|
||||
{
|
||||
id: "open",
|
||||
title: "Open & Auditable",
|
||||
title: "Open & auditable",
|
||||
desc: "Fully open source under MIT on GitHub. Reviews and contributions welcome.",
|
||||
},
|
||||
],
|
||||
},
|
||||
download: {
|
||||
title: "Download Kimi Switch",
|
||||
subtitle: "Current version v0.7.4 · Windows, macOS and Linux now released",
|
||||
autoUpdate: "Built-in update detection: upgrade in one click from Settings when a new version ships.",
|
||||
subtitle: "Current version v0.7.12 · Windows, macOS and Linux now released",
|
||||
autoUpdate: "Update checks run at startup and every 8 hours; Settings also has a manual check.",
|
||||
ready: "Available",
|
||||
wip: "In development",
|
||||
githubBtn: "Download from GitHub",
|
||||
mirrorBtn: "China mirror",
|
||||
items: [
|
||||
{ id: "windows", name: "Windows", ready: true, note: ".msi installer, lives in the system tray" },
|
||||
{ id: "macos", name: "macOS", ready: true, note: ".dmg installer (Apple Silicon), unsigned: download install-macos.sh and run bash install-macos.sh for one-click install" },
|
||||
{ id: "macos", name: "macOS", ready: true, note: ".dmg installer (Apple Silicon); unsigned — grab install-macos.sh from the release and run bash install-macos.sh to clear the quarantine flag" },
|
||||
{ id: "linux", name: "Linux", ready: true, note: ".deb / .AppImage / .rpm" },
|
||||
],
|
||||
},
|
||||
cta: {
|
||||
title: "Bring every provider into one app",
|
||||
subtitle: "Free · Open source MIT · One-minute install",
|
||||
title: "Put provider config, usage and billing in one window",
|
||||
subtitle: "Free · MIT licensed · Windows / macOS / Linux",
|
||||
download: "Free Download",
|
||||
source: "GitHub Source",
|
||||
source: "GitHub source",
|
||||
},
|
||||
seo: {
|
||||
home: {
|
||||
title: "Kimi Switch — Unified Management for AI Providers · Usage & Billing",
|
||||
title: "Kimi Switch — LLM provider config, usage and billing in one app",
|
||||
description:
|
||||
"Kimi Switch / KimiCodeSwitch — a Windows desktop manager for multiple LLM providers. Switch between Kimi, Zhipu GLM, MiniMax, DeepSeek, OpenRouter and TokenRhythm in one click, with usage and billing at a glance. Open source MIT.",
|
||||
"Kimi Switch / KimiCodeSwitch — a desktop manager for LLM provider configuration. 22 presets write straight into ~/.kimi-code/config.toml; usage and billing read from each vendor's own API. Open source MIT.",
|
||||
},
|
||||
features: {
|
||||
title: "Core Features - Kimi Switch",
|
||||
title: "Core features - Kimi Switch",
|
||||
description:
|
||||
"Kimi Switch core features: multi-provider management, usage & billing, one-click Kimi login, smart model discovery and auto updates. 22 presets out of the box.",
|
||||
"Kimi Switch features: provider presets and custom config, usage & billing, Kimi device-code login, model discovery and periodic update checks.",
|
||||
},
|
||||
changelog: {
|
||||
title: "Changelog - Kimi Switch",
|
||||
@@ -715,7 +737,7 @@ const en: Dict = {
|
||||
},
|
||||
},
|
||||
footer: {
|
||||
recommend: "Recommended Providers",
|
||||
recommend: "Recommended providers",
|
||||
mirror: "China mirror",
|
||||
downloads: "Total GitHub downloads: {n}",
|
||||
creditBefore: "Dashboard & session management adapted from ",
|
||||
|
||||
+10
-33
@@ -23,9 +23,9 @@
|
||||
--accent: 240 6% 94%;
|
||||
--accent-foreground: 240 9% 11%;
|
||||
--border: 240 6% 90%;
|
||||
--primary: 221 83% 53%;
|
||||
--primary: 221 74% 50%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--ring: 221 83% 53%;
|
||||
--ring: 221 74% 50%;
|
||||
/* 克制分层阴影(色相一致的 tinted shadow,非荧光发光) */
|
||||
--shadow-soft: 0 1px 2px hsl(240 9% 11% / 0.05),
|
||||
0 8px 24px hsl(240 9% 11% / 0.06);
|
||||
@@ -44,9 +44,9 @@
|
||||
--accent: 222 25% 14%;
|
||||
--accent-foreground: 220 20% 92%;
|
||||
--border: 222 22% 17%;
|
||||
--primary: 217 91% 60%;
|
||||
--primary: 216 68% 62%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--ring: 217 91% 60%;
|
||||
--ring: 216 68% 62%;
|
||||
--shadow-soft: 0 1px 2px hsl(222 47% 2% / 0.5),
|
||||
0 8px 24px hsl(222 47% 2% / 0.45);
|
||||
--shadow-lift: 0 1px 2px hsl(222 47% 2% / 0.5),
|
||||
@@ -60,24 +60,6 @@
|
||||
body {
|
||||
@apply bg-background text-foreground antialiased;
|
||||
}
|
||||
/* 科技风底纹:固定网格线,极低透明度,不干扰阅读 */
|
||||
body::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
pointer-events: none;
|
||||
background-image:
|
||||
linear-gradient(to right, hsl(var(--primary) / 0.04) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, hsl(var(--primary) / 0.04) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, black 30%, transparent 75%);
|
||||
}
|
||||
#root {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* 选中色与键盘焦点(无障碍) */
|
||||
::selection {
|
||||
background: hsl(var(--primary) / 0.16);
|
||||
@@ -96,19 +78,14 @@
|
||||
|
||||
@layer components {
|
||||
.container-page {
|
||||
@apply mx-auto w-full max-w-6xl px-6;
|
||||
@apply mx-auto w-full max-w-7xl px-5 md:px-8;
|
||||
}
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-xl px-5 py-2.5 text-sm font-medium transition-all duration-200;
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-sm font-medium transition-all duration-200;
|
||||
}
|
||||
.btn-primary {
|
||||
@apply btn bg-primary text-primary-foreground hover:bg-primary/90 hover:-translate-y-px active:translate-y-0 active:scale-[0.98];
|
||||
box-shadow: 0 1px 2px hsl(var(--primary) / 0.3),
|
||||
0 6px 16px hsl(var(--primary) / 0.22);
|
||||
}
|
||||
.btn-primary:hover {
|
||||
box-shadow: 0 1px 2px hsl(var(--primary) / 0.3),
|
||||
0 10px 24px hsl(var(--primary) / 0.3);
|
||||
box-shadow: 0 1px 2px hsl(221 45% 25% / 0.25);
|
||||
}
|
||||
.btn-ghost {
|
||||
@apply btn border border-border bg-card/60 text-foreground hover:border-foreground/25 hover:bg-accent active:scale-[0.98];
|
||||
@@ -126,14 +103,14 @@
|
||||
}
|
||||
/* 截图容器:限定最大宽高,避免撑满页面 */
|
||||
.screenshot {
|
||||
@apply overflow-hidden rounded-2xl border border-border bg-muted;
|
||||
@apply overflow-hidden rounded-xl border border-border bg-muted;
|
||||
box-shadow: var(--shadow-lift);
|
||||
}
|
||||
.screenshot > img {
|
||||
@apply block h-auto w-full;
|
||||
}
|
||||
/* 图标容器:统一的蓝色徽标容器 */
|
||||
/* 图标容器:中性底、统一描边宽度(Phosphor duotone) */
|
||||
.icon-chip {
|
||||
@apply flex h-10 w-10 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary;
|
||||
@apply flex h-10 w-10 items-center justify-center rounded-lg border border-border bg-muted text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -7,42 +7,36 @@ export default function CTA() {
|
||||
<section
|
||||
id="cta"
|
||||
aria-labelledby="cta-title"
|
||||
className="py-24"
|
||||
className="pt-20 pb-28"
|
||||
>
|
||||
<div className="container-page">
|
||||
<div className="card relative overflow-hidden p-12 text-center md:p-16">
|
||||
{/* 克制同色系光晕 + 顶部强调线(去紫,保持页面调性) */}
|
||||
{/* 左对齐 + 内容错位:不再整块居中 */}
|
||||
<div className="card relative max-w-3xl p-10 md:p-14">
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-24 left-1/2 h-64 w-[480px] -translate-x-1/2 rounded-full bg-primary/10 blur-3xl"
|
||||
className="absolute inset-x-0 top-0 h-px bg-primary/25"
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent"
|
||||
/>
|
||||
<div className="relative">
|
||||
<h2
|
||||
id="cta-title"
|
||||
className="text-3xl font-bold tracking-[-0.03em] md:text-5xl"
|
||||
<h2
|
||||
id="cta-title"
|
||||
className="text-3xl font-bold tracking-[-0.03em] md:text-4xl"
|
||||
>
|
||||
{t.cta.title}
|
||||
</h2>
|
||||
<p className="mt-4 max-w-[52ch] text-base text-muted-foreground md:text-lg">
|
||||
{t.cta.subtitle}
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap gap-3">
|
||||
<Link to="/download" className="btn-primary">
|
||||
{t.cta.download}
|
||||
</Link>
|
||||
<a
|
||||
href="https://github.com/billowliu2/KimiSwitch"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="btn-ghost"
|
||||
>
|
||||
{t.cta.title}
|
||||
</h2>
|
||||
<p className="mx-auto mt-4 max-w-2xl text-base text-muted-foreground md:text-lg">
|
||||
{t.cta.subtitle}
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap justify-center gap-3">
|
||||
<Link to="/download" className="btn-primary">
|
||||
{t.cta.download}
|
||||
</Link>
|
||||
<a
|
||||
href="https://github.com/billowliu2/KimiSwitch"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="btn-ghost"
|
||||
>
|
||||
{t.cta.source}
|
||||
</a>
|
||||
</div>
|
||||
{t.cta.source}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,27 +8,30 @@ const icons: Record<string, Icon> = {
|
||||
linux: LinuxLogo,
|
||||
};
|
||||
|
||||
const VERSION = "0.7.4";
|
||||
const VERSION = "0.7.12";
|
||||
const GITHUB = "https://github.com/billowliu2/KimiSwitch";
|
||||
const MIRROR_RELEASES = "https://git.codingplan.site/admin/KimiCodeSwitch/releases";
|
||||
const dl = (file: string) => `${GITHUB}/releases/download/v${VERSION}/${file}`;
|
||||
|
||||
/** Per-platform download assets for the current release (names match the CI
|
||||
* release workflow exactly — verified against the published v0.7.4 assets:
|
||||
* tauri-bundler on CI produces `Kimi.Switch_…` (dots) on every platform). */
|
||||
* release workflow exactly — verified against the published v0.7.12 assets:
|
||||
* tauri-bundler on CI produces `Kimi.Switch_…` (dots) on every platform,
|
||||
* except the rpm which uses `Kimi.Switch-<version>-1` (hyphens).
|
||||
* Filenames interpolate VERSION, so a release bump only changes the
|
||||
* constant above. */
|
||||
const assets: Record<string, { label: string; href: string }[]> = {
|
||||
windows: [
|
||||
{ label: "MSI", href: dl("Kimi.Switch_0.7.4_x64_en-US.msi") },
|
||||
{ label: "MSI", href: dl(`Kimi.Switch_${VERSION}_x64_en-US.msi`) },
|
||||
{ label: "镜像", href: MIRROR_RELEASES },
|
||||
],
|
||||
macos: [
|
||||
{ label: "Apple Silicon (.dmg)", href: dl("Kimi.Switch_0.7.4_aarch64.dmg") },
|
||||
{ label: "Apple Silicon (.dmg)", href: dl(`Kimi.Switch_${VERSION}_aarch64.dmg`) },
|
||||
{ label: "安装脚本", href: dl("install-macos.sh") },
|
||||
],
|
||||
linux: [
|
||||
{ label: ".deb", href: dl("Kimi.Switch_0.7.4_amd64.deb") },
|
||||
{ label: ".AppImage", href: dl("Kimi.Switch_0.7.4_amd64.AppImage") },
|
||||
{ label: ".rpm", href: dl("Kimi.Switch-0.7.4-1.x86_64.rpm") },
|
||||
{ label: ".deb", href: dl(`Kimi.Switch_${VERSION}_amd64.deb`) },
|
||||
{ label: ".AppImage", href: dl(`Kimi.Switch_${VERSION}_amd64.AppImage`) },
|
||||
{ label: ".rpm", href: dl(`Kimi.Switch-${VERSION}-1.x86_64.rpm`) },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -40,23 +43,36 @@ export default function Download() {
|
||||
title={t.download.title}
|
||||
subtitle={t.download.subtitle}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
{/* 不对称:Windows 为主推平台,横跨整行;macOS / Linux 两列在下方 */}
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
{t.download.items.map((p) => {
|
||||
const Icon = icons[p.id] ?? WindowsLogo;
|
||||
const links = assets[p.id] ?? [];
|
||||
const featured = p.id === "windows";
|
||||
return (
|
||||
<div key={p.id} className="card flex flex-col">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="icon-chip">
|
||||
<Icon className="h-5 w-5" weight="duotone" />
|
||||
<div
|
||||
key={p.id}
|
||||
className={`card flex flex-col ${
|
||||
featured
|
||||
? "md:col-span-2 md:flex-row md:items-center md:justify-between md:gap-10"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
<div className="icon-chip shrink-0">
|
||||
<Icon className="h-5 w-5" weight="duotone" />
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold tracking-tight">{p.name}</h3>
|
||||
<span className="ml-auto rounded-md border border-primary/20 bg-primary/10 px-2 py-0.5 text-[11px] font-medium tracking-wide text-primary">
|
||||
{t.download.ready}
|
||||
</span>
|
||||
</div>
|
||||
<span className="rounded-md border border-primary/20 bg-primary/10 px-2 py-0.5 text-[11px] font-medium tracking-wide text-primary">
|
||||
{t.download.ready}
|
||||
</span>
|
||||
<p className={`text-sm text-muted-foreground ${featured ? "max-w-[65ch]" : ""}`}>
|
||||
{p.note}
|
||||
</p>
|
||||
</div>
|
||||
<h3 className="mb-2 text-lg font-semibold tracking-tight">{p.name}</h3>
|
||||
<p className="text-sm text-muted-foreground">{p.note}</p>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<div className="mt-4 flex shrink-0 flex-wrap items-start gap-2 md:mt-0">
|
||||
{links.map((l) => (
|
||||
<a
|
||||
key={l.label}
|
||||
@@ -74,7 +90,7 @@ export default function Download() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="mt-6 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<p className="mt-6 flex max-w-[65ch] items-center gap-2 text-sm text-muted-foreground">
|
||||
<DownloadSimple className="h-4 w-4 text-primary" weight="duotone" />
|
||||
{t.download.autoUpdate}
|
||||
</p>
|
||||
|
||||
@@ -45,6 +45,8 @@ export default function Features() {
|
||||
key={f.id}
|
||||
style={{ transitionDelay: `${i * 60}ms` }}
|
||||
className={`card overflow-hidden p-0 transition-all duration-500 ease-out hover:border-primary/50 ${
|
||||
i % 2 === 1 ? "sm:mt-12" : ""
|
||||
} ${
|
||||
gridInView
|
||||
? "motion-safe:opacity-100 motion-safe:translate-y-0"
|
||||
: "motion-safe:opacity-0 motion-safe:translate-y-4"
|
||||
|
||||
@@ -23,15 +23,6 @@ export default function Hero() {
|
||||
aria-labelledby="hero-title"
|
||||
className="relative overflow-hidden pt-16 pb-20 md:pt-24"
|
||||
>
|
||||
{/* 克制的同色系光晕(去紫,统一蓝色 + 中性) */}
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -top-32 right-[-10%] h-[420px] w-[420px] rounded-full bg-primary/10 blur-3xl"
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute -left-40 top-1/2 h-[320px] w-[320px] rounded-full bg-primary/5 blur-3xl"
|
||||
/>
|
||||
<div className="container-page relative grid grid-cols-1 gap-10 md:grid-cols-2 md:items-center">
|
||||
<div>
|
||||
<div {...reveal(0)}>
|
||||
@@ -87,7 +78,7 @@ export default function Hero() {
|
||||
<div className="screenshot max-h-[420px]">
|
||||
<img
|
||||
src={asset("screenshots/hero.png")}
|
||||
alt="Kimi Switch: multi-LLM provider list with one-click switching"
|
||||
alt="Kimi Switch provider list, active provider pinned to the top"
|
||||
loading="eager"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -16,18 +16,23 @@ export default function Privacy() {
|
||||
title={t.privacy.title}
|
||||
subtitle={t.privacy.subtitle}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
{/* 三条承诺改为一个面板内的三行,图标左置,避免三张等宽卡片 */}
|
||||
<div className="card divide-y divide-border p-0">
|
||||
{t.privacy.items.map((it) => {
|
||||
const Icon = icons[it.id] ?? Database;
|
||||
return (
|
||||
<div key={it.id} className="card">
|
||||
<div className="icon-chip mb-3">
|
||||
<div key={it.id} className="flex items-start gap-5 p-6 md:p-7">
|
||||
<div className="icon-chip shrink-0">
|
||||
<Icon className="h-5 w-5" weight="duotone" />
|
||||
</div>
|
||||
<h3 className="mb-2 text-lg font-semibold tracking-tight">{it.title}</h3>
|
||||
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||
{it.desc}
|
||||
</p>
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-base font-semibold tracking-tight">
|
||||
{it.title}
|
||||
</h3>
|
||||
<p className="mt-1 max-w-[65ch] text-sm leading-relaxed text-muted-foreground">
|
||||
{it.desc}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -21,12 +21,18 @@ export default function Showcase() {
|
||||
key={s.src}
|
||||
style={{ transitionDelay: `${i * 60}ms` }}
|
||||
className={`transition-all duration-500 ease-out ${
|
||||
i === 0 ? "sm:col-span-2" : ""
|
||||
} ${
|
||||
gridInView
|
||||
? "motion-safe:opacity-100 motion-safe:translate-y-0"
|
||||
: "motion-safe:opacity-0 motion-safe:translate-y-4"
|
||||
}`}
|
||||
>
|
||||
<div className="screenshot group aspect-[4/3] overflow-hidden">
|
||||
<div
|
||||
className={`screenshot group overflow-hidden ${
|
||||
i === 0 ? "aspect-[16/9]" : "aspect-[4/3]"
|
||||
}`}
|
||||
>
|
||||
<img
|
||||
src={asset(s.src)}
|
||||
alt={`Kimi Switch - ${s.title}`}
|
||||
|
||||
Reference in new issue
Block a user