Compare commits

..
18 Commits
Author SHA1 Message Date
KimiSwitch Dev 9a3875d990 feat(subagent): v0.7.5 — 适配 kimi-code 0.36.0 子代理模型池(双写兼容/池管理/force/前置校验)+ 热力图详情按需加载 + models.dev 刷新(GLM-5.3)
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-15 23:21:22 +08:00
KimiSwitch Dev 89c71fbfe6 feat(dashboard): v0.7.4 — 热力图双击弹窗展示当日模型用量(Token/请求/费用/命中率)+ by_model 结构化升级
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-09 01:40:44 +08:00
KimiSwitch Dev 7c88099ce1 style(website): 下载统计并入页脚版权行(一行展示,不再单独成行) 2026-08-07 23:39:22 +08:00
KimiSwitch Dev cf9707326c feat(website): 页脚低调展示 GitHub 累计下载量(客户端实时拉取,1h 缓存) 2026-08-07 23:19:57 +08:00
KimiSwitch Dev 93c5720769 fix(website): 下载链接按 GitHub CI 实际资产名改回点号命名(Kimi.Switch_…),并修正 release 模板 dmg 文件名提示 2026-08-07 16:07:32 +08:00
KimiSwitch Dev a0e36e928d feat(webui): v0.7.3 — Kimi Code WebUI 应用内嵌窗口(单例/独立顶层窗口/服务器自动清理)+ 发布说明与网站同步
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
Release / Attach macOS install script (push) Canceled after 0s
2026-08-07 15:46:45 +08:00
KimiSwitch Dev fc09a29b9f chore(release): bump to v0.7.2 — 高级设置 + WebUI 快捷入口 + loop_control 兼容 + macOS 安装脚本
Release / Attach macOS install script (push) Canceled after 0s
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
2026-08-07 10:21:47 +08:00
KimiSwitch Dev 24d37fbbf4 chore: 设置出品公司为 codingplan.site 2026-08-06 15:09:12 +08:00
KimiSwitch Dev 54110316b4 chore(data): 同步 models.dev 最新模型数据 2026-08-06 15:00:04 +08:00
KimiSwitch Dev 75e48bc4c6 feat(website): 官网企业版视觉升级
- 引入 Geist 字体,去除紫色渐变,克制阴影与交互态
- 导航/卡片/按钮统一企业风格,各区块视觉收敛
2026-08-06 01:56:37 +08:00
KimiSwitch Dev b2f6e7a166 chore(data): 更新 models-dev 模型列表 2026-08-06 01:56:36 +08:00
KimiSwitch Dev 90cc4a16d2 fix(subagent): 实验开关改为滑动开关,修复开启态因 bg-primary 未定义而隐形
- Toggle 开启态改用已定义的 bg-blue-600(tailwind 配置无 primary 背景色,
  导致开启态滑轨透明、白色滑块在白底上不可见)
- 子代理开关移至模型下拉之后,统一使用滑动开关
2026-08-06 01:56:35 +08:00
KimiSwitch Dev 8aed04898c feat(subagent): 实验功能设置新增子代理模型配置
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
- 子代理设置页支持选择次主力模型,仅保存模型引用(不再写补丁字段),
  子代理直接继承所选模型的上下文长度与思考模式
- 界面只读展示继承的上下文长度与思考模式,移除补丁编辑项
- 仪表盘统计识别子代理请求(__secondary__):归为「子代理模型(估算)」
  并缓存次主力模型定价;自定义网关模型价格按官方同名模型跨 provider 匹配
- bump v0.7.1
2026-08-05 23:38:05 +08:00
KimiSwitch Dev 8b0daabd95 fix(tray): 托盘图标悬停气泡显示程序名(Kimi Switch) 2026-08-05 11:19:30 +08:00
KimiSwitch Dev 6e38bed092 docs(website): v0.7.0 更新日志补入 Kimi Eyes 插件站链接
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
2026-08-02 18:18:34 +08:00
KimiSwitch Dev 6df9095ee8 feat(settings): 关于页新增 Kimi Eyes 插件站链接(billowliu2.github.io/kimi-eyes) 2026-08-02 18:12:29 +08:00
KimiSwitch Dev d06fb41f48 chore: bump v0.7.0 + 官网版本文案/更新日志同步
Release / Version consistency (push) Canceled after 0s
Release / Build (macos-latest) (push) Canceled after 0s
Release / Build (ubuntu-latest) (push) Canceled after 0s
Release / Build (windows-latest) (push) Canceled after 0s
2026-08-02 17:17:12 +08:00
KimiSwitch Dev 69f9b8d603 feat(usage): 订阅套餐计价修正 + 识图能力可编辑 + 单套餐用量显示修复
- 订阅套餐零价条目按官方付费模型计价(zhipuai-coding-plan/glm-5.2 → zhipuai/glm-5.2 牌价)
- -highspeed / -free 派生变体自动回退到基础模型价格;Kimi For Coding 无牌价时按旗舰 kimi-k3 估算
- 设置页:image_in 识图能力可手动编辑,原生多模态模型不再提示 kimi-eyes 插件
- 修复仅单个套餐档位时用量卡片不显示的问题
- kimi usages 响应异常时透出原始返回(仅用量数字),便于对照接口排查
- models.dev 价格快照同步
2026-08-02 17:17:06 +08:00
55 changed files with 156723 additions and 132804 deletions

No files matched your search

+32 -1
View File
@@ -79,13 +79,44 @@ jobs:
releaseBody: |
## ${{ github.ref_name }}
### 本次更新
- **高级设置**:原「子代理设置」升级为「高级设置」,聚合子代理模型指定、实验功能开关与 WebUI 快捷入口
- **仪表盘热力图双击弹窗**:双击热力图方块即可查看当日模型用量分布,每种模型展示 Token / 请求次数 / 费用 / 命中率
- **子代理模型指定(实验功能)**:为子代理绑定次主力模型,不再默认继承主模型;实验开关改为滑动开关并修复开启态隐形
- **兼容 kimi-code 0.33+(v2 引擎)**:`loop_control` 写入新键名 `max_attempts_per_step`,旧配置自动迁移并保留旧键兼容 `KIMI_CODE_LEGACY_FLAG=1`;hooks 候选补充新事件
- models.dev 模型数据同步;官网企业版视觉升级;出品公司标识统一
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` (unsigned — first launch needs right-click → Open) + `.app`
- **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.
prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
overwrite: true
args: ${{ matrix.args }}
upload-macos-script:
name: Attach macOS install script
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Upload install-macos.sh to release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release upload "${{ github.ref_name }}" scripts/install-macos.sh --clobber
+7 -1
View File
@@ -55,7 +55,13 @@
## 下载
- **Windows**: [GitHub Releases](https://github.com/billowliu2/KimiSwitch/releases/latest) → `.msi`
- **macOS**: [GitHub Releases](https://github.com/billowliu2/KimiSwitch/releases/latest) → `.dmg`(**未签名** —— 首次启动请右键 → 打开绕过 Gatekeeper)
- **macOS**: [GitHub Releases](https://github.com/billowliu2/KimiSwitch/releases/latest) → `.dmg`(**未签名**,仅 Apple Silicon / M 系列芯片)。安装请下载 Release 附带的 `install-macos.sh` 一键处理:
```bash
bash install-macos.sh
```
或手动:把 `Kimi Switch.app` 拖入「应用程序」→ 右键 → 打开 → 点「打开」绕过 Gatekeeper。
- **Linux**: [GitHub Releases](https://github.com/billowliu2/KimiSwitch/releases/latest) → `.deb` / `.AppImage` / `.rpm`
历史版本(v0.5.x 及之前)请前往 [git.codingplan.site 仓库](https://git.codingplan.site/admin/KimiCodeSwitch/releases)。
+3 -1
View File
@@ -26,7 +26,9 @@ npm run tauri build -- --bundles app,dmg
Output: `src-tauri/target/release/bundle/{macos,dmg}/`.
Unsigned: first launch requires right-click → Open to bypass Gatekeeper.
Unsigned (no Developer ID account): downloaded copies are blocked by Gatekeeper.
For end users, attach `install-macos.sh` (auto-uploaded to each Release) or instruct:
right-click → Open, or `xattr -cr "/Applications/Kimi Switch.app"`.
### Linux (native)
+473 -10
View File
@@ -1,12 +1,12 @@
{
"name": "kimiswitch",
"version": "0.4.1",
"version": "0.7.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kimiswitch",
"version": "0.4.1",
"version": "0.7.5",
"dependencies": {
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-opener": "^2.5.0",
@@ -24,7 +24,8 @@
"postcss": "^8.4.41",
"tailwindcss": "^3.4.10",
"typescript": "^5.5.4",
"vite": "^5.4.2"
"vite": "^5.4.2",
"vitest": "^3.2.7"
}
},
"node_modules/@alloc/quick-lru": {
@@ -1502,6 +1503,24 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz",
@@ -1558,6 +1577,121 @@
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
}
},
"node_modules/@vitest/expect": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz",
"integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/spy": "3.2.7",
"@vitest/utils": "3.2.7",
"chai": "^5.2.0",
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",
"integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "3.2.7",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.17"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/pretty-format": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",
"integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz",
"integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "3.2.7",
"pathe": "^2.0.3",
"strip-literal": "^3.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",
"integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "3.2.7",
"magic-string": "^0.30.17",
"pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/spy": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",
"integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyspy": "^4.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz",
"integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "3.2.7",
"loupe": "^3.1.4",
"tinyrainbow": "^2.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmmirror.com/any-promise/-/any-promise-1.3.0.tgz",
@@ -1586,6 +1720,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/autoprefixer": {
"version": "10.5.2",
"resolved": "https://registry.npmmirror.com/autoprefixer/-/autoprefixer-10.5.2.tgz",
@@ -1696,6 +1840,16 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
"integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -1727,6 +1881,33 @@
],
"license": "CC-BY-4.0"
},
"node_modules/chai": {
"version": "5.3.3",
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
"integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"assertion-error": "^2.0.1",
"check-error": "^2.1.1",
"deep-eql": "^5.0.1",
"loupe": "^3.1.0",
"pathval": "^2.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/check-error": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
"integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 16"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz",
@@ -1820,6 +2001,16 @@
}
}
},
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
"integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/didyoumean": {
"version": "1.2.2",
"resolved": "https://registry.npmmirror.com/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -1851,6 +2042,13 @@
"node": ">= 0.4"
}
},
"node_modules/es-module-lexer": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
"integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz",
@@ -1900,6 +2098,26 @@
"node": ">=6"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -2164,6 +2382,13 @@
"loose-envify": "cli.js"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
"dev": true,
"license": "MIT"
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -2183,6 +2408,16 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz",
@@ -2227,9 +2462,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.15",
"resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.15.tgz",
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"dev": true,
"funding": [
{
@@ -2292,6 +2527,23 @@
"dev": true,
"license": "MIT"
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true,
"license": "MIT"
},
"node_modules/pathval": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
"integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14.16"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
@@ -2333,9 +2585,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.16",
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.16.tgz",
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"dev": true,
"funding": [
{
@@ -2353,7 +2605,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -2695,6 +2947,13 @@
"semver": "bin/semver.js"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
"dev": true,
"license": "ISC"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2705,6 +2964,40 @@
"node": ">=0.10.0"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
"dev": true,
"license": "MIT"
},
"node_modules/std-env": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
"dev": true,
"license": "MIT"
},
"node_modules/strip-literal": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",
"integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^9.0.1"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/strip-literal/node_modules/js-tokens": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
"integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
"dev": true,
"license": "MIT"
},
"node_modules/sucrase": {
"version": "3.35.1",
"resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz",
@@ -2802,6 +3095,20 @@
"node": ">=0.8"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
"integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -2850,6 +3157,36 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/tinypool": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
"integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.0.0 || >=20.0.0"
}
},
"node_modules/tinyrainbow": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
"integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/tinyspy": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -2982,6 +3319,132 @@
}
}
},
"node_modules/vite-node": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",
"integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cac": "^6.7.14",
"debug": "^4.4.1",
"es-module-lexer": "^1.7.0",
"pathe": "^2.0.3",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"bin": {
"vite-node": "vite-node.mjs"
},
"engines": {
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/vitest": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",
"integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.7",
"@vitest/mocker": "3.2.7",
"@vitest/pretty-format": "^3.2.7",
"@vitest/runner": "3.2.7",
"@vitest/snapshot": "3.2.7",
"@vitest/spy": "3.2.7",
"@vitest/utils": "3.2.7",
"chai": "^5.2.0",
"debug": "^4.4.1",
"expect-type": "^1.2.1",
"magic-string": "^0.30.17",
"pathe": "^2.0.3",
"picomatch": "^4.0.2",
"std-env": "^3.9.0",
"tinybench": "^2.9.0",
"tinyexec": "^0.3.2",
"tinyglobby": "^0.2.14",
"tinypool": "^1.1.1",
"tinyrainbow": "^2.0.0",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",
"vite-node": "3.2.4",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@types/debug": "^4.1.12",
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"@vitest/browser": "3.2.7",
"@vitest/ui": "3.2.7",
"happy-dom": "*",
"jsdom": "*"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@types/debug": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
}
}
},
"node_modules/vitest/node_modules/picomatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
"dev": true,
"license": "MIT",
"dependencies": {
"siginfo": "^2.0.0",
"stackback": "0.0.2"
},
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/yallist/-/yallist-3.1.1.tgz",
+4 -2
View File
@@ -1,7 +1,7 @@
{
"name": "kimiswitch",
"private": true,
"version": "0.6.9",
"version": "0.7.5",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,6 +9,7 @@
"build": "tsc && vite build",
"fetch-models-dev": "node scripts/fetch-models-dev.mjs",
"preview": "vite preview",
"test": "vitest run",
"tauri": "tauri",
"pretauri": "node scripts/fetch-models-dev.mjs || echo fetch-models-dev failed, using existing snapshot",
"tauri-dev": "tauri dev",
@@ -31,6 +32,7 @@
"postcss": "^8.4.41",
"tailwindcss": "^3.4.10",
"typescript": "^5.5.4",
"vite": "^5.4.2"
"vite": "^5.4.2",
"vitest": "^3.2.7"
}
}
+18
View File
@@ -0,0 +1,18 @@
## v0.7.1
### 实验功能设置:子代理模型配置
- 新增「子代理模型(次主力模型)」设置:选择次主力模型后,子代理默认绑定该模型,不再继承主模型
- 仅保存模型引用,子代理直接继承所选模型的上下文长度与思考模式,无需补丁配置
- 界面只读展示继承的上下文长度与思考模式
### 仪表盘用量统计
- 识别子代理请求(`__secondary__`):归为「子代理模型(估算)」独立展示,并缓存次主力模型定价,删除配置后历史记录仍稳定估算
- 自定义网关模型(未收录 models.dev)按官方同名模型跨 provider 匹配价格,不再落入兜底估算
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` (unsigned — first launch needs right-click → Open) + `.app`
- **Linux**: `.deb` / `.AppImage` / `.rpm`
+39
View File
@@ -0,0 +1,39 @@
## v0.7.2
### 高级设置与 WebUI(本次新增)
- 「子代理设置」升级为「**高级设置**」:聚合子代理模型指定、实验功能开关与 WebUI 快捷入口
- 新增 **Kimi Code WebUI 快捷打开**:高级设置页可将新版 Web 界面以独立窗口在应用内打开,也可在系统浏览器打开(kimi-code 0.33+ 内置 code-app;需要 kimi 命令在 PATH 中)
### 子代理模型指定(实验功能)
- 新增「子代理模型(次主力模型)」指定:在实验功能设置中为子代理选择次主力模型后,子代理默认绑定该模型,不再继承主模型
- 实验开关改为滑动开关,修复开启态因样式缺失而不可见的问题
- 仅保存模型引用,子代理直接继承所选模型的上下文长度与思考模式
### 模型数据与发布
- models.dev 模型列表与价格数据同步更新
- 兼容 kimi-code 0.33+(v2 引擎):`loop_control` 改用新键名 `max_attempts_per_step`(旧配置自动迁移,并保留旧键兼容 `KIMI_CODE_LEGACY_FLAG=1`)
- 官网企业版视觉升级;出品公司标识统一为 codingplan.site
- macOS 发布优化:Release 附带 `install-macos.sh` 一键安装脚本(见下方说明)
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` + `.app`(未签名,仅 Apple Silicon / M 系列芯片)
- **Linux**: `.deb` / `.AppImage` / `.rpm`
### macOS 安装说明(无开发者账号签名,需一次手动绕过)
> 原因:macOS 包未做 Developer ID 签名与公证(无 Apple 开发者账号),系统会拦截从网络下载的未签名应用(Gatekeeper)。`install-macos.sh` 通过清除「下载隔离」属性绕过该拦截,不影响功能与安全。
1. 下载 `Kimi.Switch_0.7.2_aarch64.dmg`,双击挂载后把 `Kimi Switch.app` 拖入「应用程序」文件夹
2. 下载本 Release 附带的 `install-macos.sh`,在终端运行:
```bash
bash install-macos.sh
```
脚本会自动清除下载隔离属性并启动应用,只需执行一次,之后正常使用。
3. 手动替代方案:右键 `Kimi Switch.app` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+33
View File
@@ -0,0 +1,33 @@
## v0.7.3
### Kimi Code WebUI 应用内嵌窗口(本次新增)
- 高级设置页「在应用内打开」:新版 Web 界面以**独立顶层窗口**打开(1100×750、可缩放、居中),不再跳转到外部浏览器
- **单例**:窗口最多一个,重复点击自动聚焦;最小化后再次打开可恢复
- **服务器自动管理**:复用已在运行的 `kimi web` 本地服务(不重复拉起);自己启动的服务器在窗口关闭或应用退出时自动清理,不留残留进程
- 两个入口并存:「在应用内打开」+「在浏览器打开」(浏览器入口复用已运行的本地服务器,直接打开 `http://127.0.0.1:58627`)
### 修复与打磨
- 窗口创建失败(快速双击竞态)时不再泄漏 `kimi web` 进程
- WebUI 说明文案与发布说明同步更新
### Downloads by platform
- **Windows**: `.msi` installer
- **macOS**: `.dmg` + `.app`(未签名,仅 Apple Silicon / M 系列芯片)
- **Linux**: `.deb` / `.AppImage` / `.rpm`
### macOS 安装说明(无开发者账号签名,需一次手动绕过)
> 原因:macOS 包未做 Developer ID 签名与公证(无 Apple 开发者账号),系统会拦截从网络下载的未签名应用(Gatekeeper)。`install-macos.sh` 通过清除「下载隔离」属性绕过该拦截,不影响功能与安全。
1. 下载 `Kimi.Switch_0.7.3_aarch64.dmg`,双击挂载后把 `Kimi Switch.app` 拖入「应用程序」文件夹
2. 下载本 Release 附带的 `install-macos.sh`,在终端运行:
```bash
bash install-macos.sh
```
脚本会自动清除下载隔离属性并启动应用,只需执行一次,之后正常使用。
3. 手动替代方案:右键 `Kimi Switch.app` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+30
View File
@@ -0,0 +1,30 @@
## v0.7.4
### 仪表盘热力图双击弹窗(本次新增)
- 热力图方块**双击**即可弹窗查看当日模型用量分布
- 每种模型独立展示:**Token 用量 / 请求次数 / 费用 / 缓存命中率**(此前仅有 token 数)
- 范围外日期(不在当前 7d / 30d / all 范围内的方块)不可双击、无放大效果
- 弹窗内 Escape / 点击遮罩 / 关闭按钮均可关闭
### 数据结构升级
- 后端 `[dashboard] by_model` 从纯 token 数升级为结构化对象(含 requests / cost / cacheHitRate),弹窗和柱状图双击均展示全量指标
### 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` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+37
View File
@@ -0,0 +1,37 @@
## v0.7.5
### 子代理模型池适配(kimi-code 0.36.0 新引擎)
- 适配 kimi-code v2 的 `[secondary_model]` 模型池语义:`default_model` + `[secondary_model.models]` 表 + `force`
- **双写兼容**:写入配置时 `model` 与 `default_model` 同步同值,v1 legacy 引擎(`KIMI_CODE_LEGACY_FLAG=1`)与 v2 引擎均可正常识别
- 高级设置页新增**模型池管理**:升级旧配置为模型池、增删池条目、编辑每条目的路由描述(渲染进主代理 Agent/AgentSwarm 工具描述,直接影响主模型对子代理模型的调度质量)
- 支持 **force 强制默认模型**开关(开启会清空池条目,带二次确认)
- 保存前本地校验:primary 保留别名、池条目与 default_model 一致性、别名必须已注册、force 与池互斥等 6 类错误前置拦截
- 新增 32 个单元测试覆盖池读写与校验逻辑(vitest)
### 仪表盘热力图详情改为按需加载
- 双击热力图方块改为调用后端 `get_day_detail` 按需聚合当日数据,**不再受当前 7d / 30d 范围限制**,任何有数据的日期都可查看明细
- 无数据日期双击给出提示,不再静默无响应
### 模型数据更新
- models.dev 快照刷新至 2026-08-15(6583 模型 / 185 供应商),新增 **GLM-5.3** 等一批新模型(含定价与能力标记)
### 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` → 打开 → 弹窗点「打开」;或 系统设置 → 隐私与安全性 → 仍要打开
+48
View File
@@ -0,0 +1,48 @@
#!/bin/bash
# install-macos.sh — Kimi Switch macOS 一键安装辅助脚本
#
# 背景:macOS 包未做 Developer ID 签名(无开发者账号),从网络下载后会被
# Gatekeeper 的「下载隔离(quarantine)」属性拦截。本脚本清除该属性后启动应用。
#
# 用法(把 Kimi Switch.app 拖入「应用程序」文件夹后执行):
# bash install-macos.sh
#
# 若脚本提示找不到应用,请先手动把 Kimi Switch.app 拖到 /Applications 再运行。
set -e
APP_NAME="Kimi Switch"
APP_PATH="/Applications/${APP_NAME}.app"
DOWNLOADED_DMG_NAME="KimiSwitch.dmg"
if [ ! -d "$APP_PATH" ]; then
echo "❌ 未找到 ${APP_PATH}"
echo ""
echo "请先把「${APP_NAME}.app」拖到「应用程序」文件夹,再重新运行本脚本:"
echo " 1. 双击下载的 ${DOWNLOADED_DMG_NAME}(磁盘映像会自动挂载)"
echo " 2. 把其中的 Kimi Switch.app 拖入「应用程序」文件夹"
echo " 3. 回到终端重新运行:bash install-macos.sh"
exit 1
fi
echo "① 清除「下载隔离」属性(Gatekeeper 拦截的来源)..."
xattr -cr "$APP_PATH" 2>/dev/null || true
echo " 完成"
echo "② 验证代码签名状态:"
if codesign -dv "$APP_PATH" 2>&1 | grep -q "Signature=adhoc"; then
echo " Signature=adhoc(正常,ad-hoc 签名,右键打开即可运行)"
else
echo " (未检测到签名信息,属正常,不影响本脚本的运行方式)"
fi
echo "③ 正在启动「${APP_NAME}」..."
open "$APP_PATH"
echo ""
echo "✅ 启动完成。"
echo ""
echo "如果仍提示「无法验证开发者」,请按下面任一种方式再试:"
echo " a) 右键 ${APP_NAME}.app → 打开 → 在弹出的提示中点「打开」"
echo " b) 系统设置 → 隐私与安全性 → 滚动到「安全性」→ 点「仍要打开」"
echo ""
echo "首次启动后应用即可正常使用,之后无需重复本操作。"
+1 -1
View File
@@ -1958,7 +1958,7 @@ dependencies = [
[[package]]
name = "kimiswitch"
version = "0.6.8"
version = "0.7.5"
dependencies = [
"anyhow",
"chrono",
+2 -2
View File
@@ -1,8 +1,8 @@
[package]
name = "kimiswitch"
version = "0.6.9"
version = "0.7.5"
description = "Kimi Switch - model config manager"
authors = ["you"]
authors = ["codingplan.site"]
edition = "2021"
[build-dependencies]
+219
View File
@@ -7,6 +7,7 @@ use serde::Serialize;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use tauri::Manager;
use tauri_plugin_opener::OpenerExt;
fn fmt_anyhow(err: anyhow::Error) -> String {
@@ -949,6 +950,193 @@ pub fn open_installer(app: tauri::AppHandle, path: String) -> Result<(), String>
.open_path(&path, None::<&str>)
.map_err(|e| e.to_string())
}
/// Open the Kimi Code WebUI in the system default browser. Reuses an
/// already-running local `kimi web` server (embedded window, terminal, …);
/// otherwise spawns `kimi web`, which starts the server and opens the browser.
#[tauri::command]
pub async fn open_kimi_web(app: tauri::AppHandle) -> Result<(), String> {
if kimi_web_alive(Duration::from_millis(800)).await {
// Server already running — just open the browser at the local origin.
return app
.opener()
.open_url(kimi_web_url(), None::<&str>)
.map_err(|e| e.to_string());
}
let mut cmd = std::process::Command::new("kimi");
cmd.arg("web");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// CREATE_NO_WINDOW: avoid a console window flashing next to the GUI.
cmd.creation_flags(0x08000000);
}
cmd.spawn()
.map(|_| ())
.map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"kimi executable not found on PATH — install Kimi Code CLI first".to_string()
} else {
format!("failed to start `kimi web`: {e}")
}
})
}
// ---------------------------------------------------------------------------
// Kimi Code WebUI — embedded in-app window
//
// `open_kimi_web_embedded` opens the Kimi Code Web UI inside a dedicated,
// independent top-level window (no parent/child relationship with the main
// window). At most one such window exists: re-invoking focuses it. The local
// `kimi web` server is reused when already running; otherwise one is spawned
// (`--no-open`) and terminated when the window closes or the app exits.
// ---------------------------------------------------------------------------
/// Shared state for the embedded WebUI window and the server we may have spawned.
#[derive(Default)]
pub struct KimiWebState {
/// The embedded WebUI window (at most one).
window: Mutex<Option<tauri::WebviewWindow>>,
/// The `kimi web` child spawned by this app (None when reusing a server).
child: Mutex<Option<std::process::Child>>,
}
const KIMI_WEB_PORT: u16 = 58627;
const KIMI_WEB_ORIGIN: &str = "http://127.0.0.1:58627";
const KIMI_WEB_WINDOW_LABEL: &str = "kimi-web-ui";
/// Build the Web UI URL; the home-wide bearer token rides in the `#token=`
/// fragment (same as the `kimi web` ready banner, see kimi-code
/// `cli/sub/web/access-urls.ts`).
fn kimi_web_url() -> String {
let token = dirs::home_dir()
.map(|h| h.join(".kimi-code").join("server.token"))
.and_then(|p| std::fs::read_to_string(p).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
match token {
Some(t) => format!("{KIMI_WEB_ORIGIN}/#token={t}"),
None => format!("{KIMI_WEB_ORIGIN}/"),
}
}
/// Best-effort probe of the local Kimi web server root.
async fn kimi_web_alive(timeout: Duration) -> bool {
let Ok(client) = reqwest::Client::builder().timeout(timeout).build() else {
return false;
};
client
.get(KIMI_WEB_ORIGIN)
.send()
.await
.map(|r| r.status().is_success())
.unwrap_or(false)
}
/// Kill the `kimi web` server spawned by this app (no-op when reusing one).
pub fn kill_spawned_kimi_web(state: &tauri::State<'_, KimiWebState>) {
if let Ok(mut guard) = state.child.lock() {
if let Some(mut child) = guard.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
/// Open the Kimi Code WebUI in an embedded, independent top-level window.
#[tauri::command]
pub async fn open_kimi_web_embedded(
app: tauri::AppHandle,
state: tauri::State<'_, KimiWebState>,
) -> Result<(), String> {
// Singleton: focus the existing window instead of creating a second one.
if let Ok(guard) = state.window.lock() {
if let Some(w) = guard.as_ref() {
if w.is_visible().unwrap_or(false) {
let _ = w.unminimize();
let _ = w.set_focus();
return Ok(());
}
}
}
// Reuse an already-running server, otherwise spawn `kimi web --no-open`.
if !kimi_web_alive(Duration::from_millis(800)).await {
let mut cmd = std::process::Command::new("kimi");
cmd.args(["web", "--no-open", "--port", &KIMI_WEB_PORT.to_string()]);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW — no console flash
}
let child = cmd.spawn().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
"kimi executable not found on PATH — install Kimi Code CLI first".to_string()
} else {
format!("failed to start `kimi web`: {e}")
}
})?;
if let Ok(mut guard) = state.child.lock() {
*guard = Some(child);
}
}
// Wait for the server to come up (fresh start takes a moment).
if !kimi_web_alive(Duration::from_secs(8)).await {
kill_spawned_kimi_web(&state);
return Err(format!("kimi web did not come up within 8s ({KIMI_WEB_ORIGIN})"));
}
// Create the window on the main thread (required on macOS).
let url: tauri::Url = match kimi_web_url().parse() {
Ok(u) => u,
Err(_) => return Err("invalid kimi web url".to_string()),
};
let app = app.clone();
tauri::async_runtime::spawn(async move {
let builder_app = app.clone();
let _ = app.run_on_main_thread(move || {
match tauri::WebviewWindowBuilder::new(
&builder_app,
KIMI_WEB_WINDOW_LABEL,
tauri::WebviewUrl::External(url),
)
.title("Kimi Code WebUI")
.inner_size(1100.0, 750.0)
.resizable(true)
.center()
.build()
{
Ok(window) => {
// Track the window for the singleton check.
if let Ok(mut guard) = builder_app.state::<KimiWebState>().window.lock() {
*guard = Some(window.clone());
}
// Clean up when the window closes: forget it and stop the
// `kimi web` server we spawned (reused servers are untouched).
let w = window.clone();
window.on_window_event(move |event| match event {
tauri::WindowEvent::Destroyed => {
let app = w.app_handle().clone();
let state = app.state::<KimiWebState>();
if let Ok(mut guard) = state.window.lock() {
*guard = None;
}
kill_spawned_kimi_web(&state);
}
_ => {}
});
}
Err(_) => {
// Window creation failed (e.g. rapid double-click racing
// the singleton check): don't leak the server we spawned.
kill_spawned_kimi_web(&builder_app.state::<KimiWebState>());
}
}
});
});
Ok(())
}
/// Preference for Linux is AppImage (portable, no install). If the preferred
/// extension is not present, returns None so the UI can fall back to
/// "open release page" instead of guessing a less-preferred format.
@@ -1078,3 +1266,34 @@ pub async fn kimi_oauth_poll(
) -> Result<crate::oauth::DevicePollStatus, String> {
crate::oauth::poll_device_token(&device_code, interval).await
}
// ---------------------------------------------------------------------------
// Experimental feature env-var probe (Kimi Code secondary model etc.)
// ---------------------------------------------------------------------------
/// Read the Kimi Code experimental-feature environment variables that are
/// currently set (non-empty) in this process's environment. The frontend
/// uses the result to mark config.toml `[experimental]` toggles as locked:
/// env vars outrank the config file in Kimi Code's flag resolution.
///
/// Truthy values per the CLI: `1` / `true` / `yes` / `on` (case-insensitive);
/// 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; 5] = [
"KIMI_CODE_EXPERIMENTAL_FLAG",
"KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL",
"KIMI_CODE_EXPERIMENTAL_TOOL_SELECT",
"KIMI_CODE_EXPERIMENTAL_ACP_V2",
"KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL",
];
let mut out = HashMap::new();
for name in VARS {
if let Ok(value) = std::env::var(name) {
if !value.trim().is_empty() {
out.insert(name.to_string(), value);
}
}
}
out
}
+281 -17
View File
@@ -132,8 +132,8 @@ pub struct DailyRow {
pub cost_usd: f64,
pub total_tokens: u64,
pub cache_hit_rate: f64,
/// Per-model token breakdown for stacked-bar rendering
pub by_model: HashMap<String, u64>,
/// Per-model structured breakdown (tokens / requests / cost / cacheHitRate).
pub by_model: HashMap<String, TotalsRow>,
/// Per-provider token breakdown for stacked-bar rendering
pub by_provider: HashMap<String, u64>,
/// Per-provider, per-model nested token breakdown (provider → model → tokens),
@@ -149,6 +149,9 @@ pub struct ModelRow {
pub model_resolved: String,
pub price_id: String,
pub cost_estimated: bool,
/// True when any aggregated record came from a subagent request (Kimi Code
/// `__secondary__` marker, resolved to the configured secondary model).
pub is_secondary: bool,
pub requests: usize,
pub input_other: u64,
pub output: u64,
@@ -175,6 +178,9 @@ pub struct RecentRow {
pub cost_estimated: bool,
pub price_id: String,
pub from_env: bool,
/// True when the record is a subagent request bound to the configured
/// secondary model (Kimi Code `__secondary__` marker).
pub is_secondary: bool,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -330,6 +336,9 @@ pub struct UsageRecord {
pub model_display: String,
pub provider: Option<String>,
pub from_env: bool,
/// True when the record is a subagent request bound to the configured
/// secondary model (Kimi Code `__secondary__` marker).
pub is_secondary: bool,
}
// ---------------------------------------------------------------------------
@@ -400,6 +409,26 @@ fn build_alias_provider_map(home: &Path) -> HashMap<String, String> {
map
}
/// Read `[secondary_model] model` from the Kimi Code config.toml — the alias
/// subagents bind to when the experimental secondary-model feature is on.
/// Kimi Code emits usage records with the internal marker `__secondary__` for
/// those requests; the marker is resolved to this alias so prices and display
/// line up with the actual model.
fn read_secondary_model_alias(home: &Path) -> Option<String> {
let path = home.join("config.toml");
if !path.is_file() {
return None;
}
let content = std::fs::read_to_string(&path).ok()?;
let parsed: toml::Value = toml::from_str(&content).ok()?;
parsed
.get("secondary_model")
.and_then(|s| s.get("model"))
.and_then(|m| m.as_str())
.map(|s| s.to_string())
.filter(|s| !s.is_empty())
}
/// Resolve the provider for a usage record's raw model key: prefer the `provider/`
/// prefix, then fall back to the legacy alias→provider map (config + backups).
fn resolve_provider(model_raw: &str, map: &HashMap<String, String>) -> Option<String> {
@@ -590,6 +619,20 @@ fn models_dev_lookup(model_name: &str) -> Option<(String, ModelsDevCost)> {
Some((key.clone(), *cost))
}
/// Strip a trailing derived-variant suffix ("-highspeed", "-free") from a
/// model id: plan endpoints expose e.g. `glm-5.2-highspeed`, which bills at
/// the base model's price.
fn strip_variant_suffix(model_name: &str) -> Option<String> {
for suffix in ["-highspeed", "-free"] {
if let Some(base) = model_name.strip_suffix(suffix) {
if !base.is_empty() {
return Some(base.to_string());
}
}
}
None
}
/// Strip a trailing context-size suffix ("-256k", "-128k", "-1m") from a model
/// id: context variants like "k3-256k" bill at the base model's ("k3") price.
/// Returns the stripped id (provider prefix preserved), or None when there is
@@ -629,6 +672,42 @@ fn match_price(model_name: &str) -> (String, f64, f64, f64, bool) {
result
}
/// Suffix-match a model against the models.dev index, skipping zero-priced
/// (subscription-plan) listings so a paid official entry wins. Used as the
/// fallback when the exact hit resolves to a zero-cost plan entry such as
/// `zhipuai-coding-plan/glm-5.2` or `kimi-for-coding/kimi-for-coding`.
fn priced_suffix_lookup(model_name: &str) -> Option<(String, ModelsDevCost)> {
let bare = model_name.rsplit_once('/').map(|(_, b)| b).unwrap_or(model_name);
let bare_l = bare.to_ascii_lowercase();
let mut matches: Vec<(&String, &ModelsDevCost)> = models_dev_cost_index()
.iter()
.filter(|(key, cost)| {
(cost.input > 0.0 || cost.output > 0.0)
&& key
.rsplit_once('/')
.map(|(_, model)| model.ends_with(&bare_l))
.unwrap_or(false)
})
.collect();
if matches.is_empty() {
return None;
}
matches.sort_by(|(a, _), (b, _)| {
provider_rank(a)
.cmp(&provider_rank(b))
.then_with(|| a.cmp(b))
});
let (key, cost) = matches[0];
Some((key.clone(), *cost))
}
/// Subscription-plan models without any priced counterpart in the snapshot
/// (e.g. the "Kimi For Coding" plan endpoint has no per-token price) bill at
/// the flagship model of the same family for cost estimation.
const PLAN_MODEL_FALLBACK: &[(&str, &str)] = &[
("kimi-for-coding", "moonshotai/kimi-k3"),
];
fn match_price_inner(model_name: &str) -> (String, f64, f64, f64, bool) {
let bare = match model_name.rsplit_once('/') {
Some((_, b)) => b,
@@ -640,11 +719,30 @@ fn match_price_inner(model_name: &str) -> (String, f64, f64, f64, bool) {
return (id, c.cache_read, c.input, c.output, false);
}
// Zero-priced listing (subscription-plan entries such as
// kimi-for-coding/k3-256k): bill at the base model's list price.
if let Some(base) = strip_context_suffix(model_name) {
if let Some((base_id, base_c)) = models_dev_lookup(&base) {
if base_c.input > 0.0 || base_c.output > 0.0 {
return (base_id, base_c.cache_read, base_c.input, base_c.output, false);
// zhipuai-coding-plan/glm-5.2 or kimi-for-coding/kimi-for-coding):
// bill at a priced equivalent — the full id first, then derived
// variants (-highspeed / -free), then the context-size base, then the
// curated flagship fallback.
for base in [
Some(model_name.to_string()),
strip_variant_suffix(model_name),
strip_context_suffix(model_name),
]
.into_iter()
.flatten()
{
if let Some((bid, bc)) = priced_suffix_lookup(&base) {
if bc.input > 0.0 || bc.output > 0.0 {
return (bid, bc.cache_read, bc.input, bc.output, false);
}
}
}
let bare = model_name.rsplit_once('/').map(|(_, b)| b).unwrap_or(model_name);
let bare_l = bare.to_ascii_lowercase();
for (plan, flagship) in PLAN_MODEL_FALLBACK {
if bare_l.contains(plan) {
if let Some((fid, fc)) = models_dev_lookup(flagship) {
return (fid, fc.cache_read, fc.input, fc.output, false);
}
}
}
@@ -657,6 +755,15 @@ fn match_price_inner(model_name: &str) -> (String, f64, f64, f64, bool) {
return (id, c.cache_read, c.input, c.output, false);
}
}
// 1c) still no exact match: fall back to a cross-provider bare-name
// suffix lookup in the models.dev snapshot. Custom-gateway aliases (e.g.
// "CodingPlan.site/deepseek-v4-flash", not catalogued in models.dev)
// then price against the official listing of the same model id.
if let Some((id, c)) = priced_suffix_lookup(model_name) {
if c.input > 0.0 || c.output > 0.0 {
return (id, c.cache_read, c.input, c.output, false);
}
}
// 2) legacy Kimi table (kept as a fallback for names not in models.dev).
let bare_l = bare.to_ascii_lowercase();
for p in &list_prices() {
@@ -689,9 +796,30 @@ fn cost_for_usage(input_other: u64, output: u64, cache_read: u64, cache_create:
// Scanner
// ---------------------------------------------------------------------------
/// Settings key caching the last configured secondary-model alias. Historical
/// `__secondary__` usage records carry no model identity, so billing follows
/// the currently configured secondary model; this cache keeps a stable basis
/// even after the secondary config is removed or changed.
const SECONDARY_MODEL_CACHE_KEY: &str = "dashboard.secondary_model_cache";
fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
let root = sessions_root(home);
let alias2prov = build_alias_provider_map(home);
// Resolve the `__secondary__` marker (subagent requests bound to the
// configured secondary model) to the real model alias once per scan.
// Prefer the current config; fall back to the persisted cache so records
// keep a stable billing basis after the secondary config is removed or
// changed. When the config still declares a secondary model, refresh the
// cache with it.
let current_secondary = read_secondary_model_alias(home);
let cached_secondary = crate::db::get_setting_pub(SECONDARY_MODEL_CACHE_KEY)
.ok()
.flatten()
.filter(|s| !s.is_empty());
let secondary_alias = current_secondary.clone().or(cached_secondary);
if let Some(alias) = &current_secondary {
let _ = crate::db::set_setting_pub(SECONDARY_MODEL_CACHE_KEY, alias);
}
let mut records = Vec::new();
let mut files_scanned = 0;
let mut lines_seen = 0;
@@ -731,6 +859,21 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
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);
@@ -740,16 +883,22 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
// 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, &model_raw);
let (pid, _ch, _ip, _op, _) = match_price(&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(&model_raw, &alias2prov),
from_env: model_raw == "__kimi_env_model__",
provider: resolve_provider(&price_model, &alias2prov),
from_env,
is_secondary,
input_other,
output,
input_cache_read: cache_read,
@@ -831,7 +980,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, u64>, HashMap<String, HashMap<String, u64>>)> = HashMap::new();
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();
for r in &filtered {
@@ -839,8 +988,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
let dk = day_key(r.time);
let (day_totals, day_models, day_prov_models) = by_day.entry(dk.clone()).or_default();
day_totals.add(r);
*day_models.entry(r.model.clone()).or_insert(0) +=
r.input_other + r.output + r.input_cache_read + r.input_cache_creation;
day_models.entry(r.model.clone()).or_default().add(r);
let provider_key = r.provider.clone().unwrap_or_else(|| "unknown".to_string());
*day_prov_models
.entry(provider_key)
@@ -856,6 +1004,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
model_resolved: r.model_resolved.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,
@@ -864,6 +1013,7 @@ 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;
}
let total_input = totals.input_other + totals.input_cache_read + totals.input_cache_creation;
@@ -873,12 +1023,22 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
.map(|(date, (t, by_model, by_provider_model))| {
let ti = t.input_other + t.input_cache_read + t.input_cache_creation;
let ch = if ti > 0 { t.input_cache_read as f64 / ti as f64 } else { 0.0 };
// Per-model cache_hit_rate (not cumulative; computed from the
// model's own input token split).
let by_model_finalized: HashMap<String, TotalsRow> = by_model
.into_iter()
.map(|(k, mut mt)| {
let mi = mt.input_other + mt.input_cache_read + mt.input_cache_creation;
mt.cache_hit_rate = if mi > 0 { mt.input_cache_read as f64 / mi as f64 } else { 0.0 };
(k, mt)
})
.collect();
DailyRow {
date, requests: t.requests,
input_other: t.input_other, output: t.output,
input_cache_read: t.input_cache_read, input_cache_creation: t.input_cache_creation,
cost_usd: t.cost_usd, total_tokens: t.total_tokens, cache_hit_rate: ch,
by_model,
by_model: by_model_finalized,
by_provider: by_provider_model
.iter()
.map(|(p, m)| (p.clone(), m.values().sum::<u64>()))
@@ -910,6 +1070,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
total_tokens: r.input_other + r.output + r.input_cache_read + r.input_cache_creation,
cost_usd: r.cost_usd, cost_estimated: r.cost_estimated,
price_id: r.price_id.clone(), from_env: r.from_env,
is_secondary: r.is_secondary,
}).collect();
RangeStats {
@@ -1592,10 +1753,9 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
let t2 = std::time::Instant::now();
let scan_ms = t1.duration_since(t0).as_secs_f64() * 1000.0;
let aggregate_ms = t2.duration_since(t1).as_secs_f64() * 1000.0;
let total_ms = t2.duration_since(t0).as_secs_f64() * 1000.0;
eprintln!(
"[dashboard] get_summary range={} records={} scan={:.0}ms aggregate={:.0}ms total={:.0}ms",
r, records.len(), scan_ms, aggregate_ms, total_ms
r, records.len(), scan_ms, aggregate_ms, t2.duration_since(t0).as_secs_f64() * 1000.0
);
SummaryResult {
@@ -1613,6 +1773,68 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
}
}
/// Aggregate a single calendar day into a `DailyRow` — lazy detail for the
/// heatmap double-click modal. Returns `None` when the date has no records.
fn build_day_detail(date: &str, records: &[UsageRecord]) -> Option<DailyRow> {
let mut t = TotalsRow::default();
let mut by_model: HashMap<String, TotalsRow> = HashMap::new();
let mut by_provider_model: HashMap<String, HashMap<String, u64>> = HashMap::new();
let mut found = false;
for r in records {
if day_key(r.time) != date {
continue;
}
found = true;
t.add(r);
by_model.entry(r.model.clone()).or_default().add(r);
let p = r.provider.clone().unwrap_or_else(|| "unknown".to_string());
*by_provider_model
.entry(p)
.or_default()
.entry(r.model.clone())
.or_insert(0) += r.input_other + r.output + r.input_cache_read + r.input_cache_creation;
}
if !found {
return None;
}
let ti = t.input_other + t.input_cache_read + t.input_cache_creation;
let ch = if ti > 0 { t.input_cache_read as f64 / ti as f64 } else { 0.0 };
let by_model: HashMap<String, TotalsRow> = by_model
.into_iter()
.map(|(k, mut mt)| {
let mi = mt.input_other + mt.input_cache_read + mt.input_cache_creation;
mt.cache_hit_rate = if mi > 0 { mt.input_cache_read as f64 / mi as f64 } else { 0.0 };
(k, mt)
})
.collect();
Some(DailyRow {
date: date.to_string(),
requests: t.requests,
input_other: t.input_other,
output: t.output,
input_cache_read: t.input_cache_read,
input_cache_creation: t.input_cache_creation,
cost_usd: t.cost_usd,
total_tokens: t.total_tokens,
cache_hit_rate: ch,
by_model,
by_provider: by_provider_model
.iter()
.map(|(p, m)| (p.clone(), m.values().sum::<u64>()))
.collect(),
by_provider_model,
})
}
/// Lazy per-day detail for the heatmap double-click modal (fetched on demand,
/// so `get_summary` stays lean). Returns null when the date has no records.
#[tauri::command]
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);
build_day_detail(&date, &records)
}
#[tauri::command]
pub fn list_sessions(home_override: Option<String>, status: Option<String>, workspace: Option<String>) -> SessionsResult {
let home = resolve_kimi_home(home_override);
@@ -1691,6 +1913,19 @@ mod pricing_tests {
assert!(est, "unknown models must be flagged as estimated");
}
#[test]
fn custom_gateway_alias_bills_at_official_listing() {
// Custom-gateway aliases not catalogued in models.dev (e.g. the user's
// aggregated gateway "CodingPlan.site/deepseek-v4-flash") must resolve
// via the cross-provider bare-name lookup to a priced official entry
// instead of falling into the last-resort estimate.
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);
}
#[test]
fn ambiguous_ids_prefer_official_provider() {
// glm-4.6 ships under resellers too (e.g. 302ai); the official zhipuai
@@ -1717,6 +1952,35 @@ mod pricing_tests {
assert_eq!(strip_context_suffix("kimi-k2-thinking"), None);
}
#[test]
fn subscription_plan_models_bill_at_priced_equivalent() {
// zhipuai-coding-plan/glm-5.2 is a zero-cost plan entry; the priced
// official zhipuai/glm-5.2 must win.
let (id, ch, input, output, est) = match_price("zhipuai-coding-plan/glm-5.2");
assert!(!est);
assert_eq!(id, "zhipuai/glm-5.2");
assert_eq!(input, 1.4);
assert_eq!(output, 4.4);
assert_eq!(ch, 0.26);
// Kimi For Coding has no priced counterpart at all → curated flagship.
let (id, _, input, _, est) = match_price("kimi-code/kimi-for-coding");
assert!(!est);
assert_eq!(id, "moonshotai/kimi-k3");
assert_eq!(input, 3.0);
// -highspeed variants strip back to the priced base model.
let (id, _, input, _, est) = match_price("zhipuai-coding-plan/glm-5.2-highspeed");
assert!(!est);
assert_eq!(id, "zhipuai/glm-5.2");
assert_eq!(input, 1.4);
assert_eq!(
strip_variant_suffix("glm-5.2-highspeed").as_deref(),
Some("glm-5.2")
);
assert_eq!(strip_variant_suffix("glm-5.2"), None);
}
#[test]
fn cache_write_price_preferred_when_present() {
// glm-4.6 has cache_write: 0 → cache creation billed at 0, not input.
+103
View File
@@ -343,6 +343,39 @@ pub fn config_to_kimi_code(config: &Config, existing: Option<&TomlValue>) -> Tom
}
root.insert("models".to_string(), TomlValue::Table(models_table));
// Sync UI-managed top-level sections (thinking, experimental,
// secondary_model, ...) from config.raw_other back into the root.
// At import time every top-level key except default_model/providers/
// models was collected into raw_other, so raw_other is the authoritative
// snapshot of those sections. This both persists UI edits to those
// sections and drops sections the user explicitly removed (absent from
// raw_other but still present in `existing`).
let mut managed_keys = std::collections::HashSet::new();
if let TomlValue::Table(extra) =
json_to_toml(&config.raw_other).unwrap_or(TomlValue::Table(Table::new()))
{
for (k, v) in extra {
if k == "default_model" || k == "providers" || k == "models" {
continue;
}
managed_keys.insert(k.clone());
root.insert(k, v);
}
}
let stale_keys: Vec<String> = root
.keys()
.filter(|k| {
*k != "default_model"
&& *k != "providers"
&& *k != "models"
&& !managed_keys.contains(*k)
})
.cloned()
.collect();
for k in stale_keys {
root.remove(&k);
}
TomlValue::Table(root)
}
@@ -552,6 +585,76 @@ api_key = ""
assert!(caps.iter().any(|v| v.as_str() == Some("thinking")));
}
#[test]
fn kimi_code_export_syncs_raw_other_top_level_sections() {
// Regression: UI-managed top-level sections ([thinking],
// [experimental], [secondary_model], ...) collected into raw_other at
// import time must be written back on export; sections removed from
// raw_other must be dropped from the output.
let toml_str = r#"
default_model = "glm-5.2"
default_thinking = true
[providers."glmzhongzhuan"]
type = "anthropic"
api_key = "sk-test"
[models."glm-5.2"]
provider = "glmzhongzhuan"
model = "glm-5.2"
max_context_size = 900000
[thinking]
enabled = true
[experimental]
secondary-model = true
[secondary_model]
model = "glm-5.2"
default_effort = "low"
"#;
let value: TomlValue = toml_str.parse().unwrap();
let mut config = kimi_code_to_config(&value);
// raw_other collected the unknown top-level sections
let raw = config.raw_other.as_object().unwrap();
assert!(raw.contains_key("thinking"));
assert!(raw.contains_key("experimental"));
assert!(raw.contains_key("secondary_model"));
// UI edit: flip the experimental flag off and drop secondary_model
let mut raw = config.raw_other.as_object().unwrap().clone();
raw.insert(
"experimental".to_string(),
serde_json::json!({"secondary-model": false}),
);
raw.remove("secondary_model");
config.raw_other = serde_json::Value::Object(raw);
let exported = config_to_kimi_code(&config, Some(&value));
let root = exported.as_table().unwrap();
// Updated section is written back
let exp = root.get("experimental").unwrap().as_table().unwrap();
assert_eq!(
exp.get("secondary-model").and_then(|v| v.as_bool()),
Some(false)
);
// Removed section is dropped
assert!(root.get("secondary_model").is_none());
// Untouched sections are preserved
let thinking = root.get("thinking").unwrap().as_table().unwrap();
assert_eq!(
thinking.get("enabled").and_then(|v| v.as_bool()),
Some(true)
);
assert_eq!(
root.get("default_thinking").and_then(|v| v.as_bool()),
Some(true)
);
}
#[test]
fn kimi_code_export_does_not_inject_thinking_from_supports_1m() {
let mut providers = IndexMap::new();
+16 -2
View File
@@ -44,6 +44,7 @@ pub fn run() {
let icon = app.default_window_icon().unwrap().clone();
TrayIconBuilder::new()
.icon(icon)
.tooltip("Kimi Switch")
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
@@ -108,11 +109,15 @@ pub fn run() {
commands::download_update,
commands::open_installer,
commands::open_external_url,
commands::open_kimi_web,
commands::open_kimi_web_embedded,
commands::kimi_oauth_start,
commands::kimi_oauth_poll,
commands::get_experimental_env_status,
dashboard::get_paths,
dashboard::get_prices,
dashboard::get_summary,
dashboard::get_day_detail,
dashboard::list_sessions,
dashboard::archive_session,
dashboard::unarchive_session,
@@ -120,6 +125,15 @@ pub fn run() {
dashboard::delete_workspace,
dashboard::get_session_preview,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
.manage(commands::KimiWebState::default())
.build(tauri::generate_context!())
.expect("error while running tauri application")
.run(|app: &tauri::AppHandle, event| {
// Ensure a `kimi web` server spawned for the embedded WebUI window
// is stopped when the app exits (windows already destroyed first).
if let tauri::RunEvent::Exit = event {
let state = app.state::<commands::KimiWebState>();
commands::kill_spawned_kimi_web(&state);
}
});
}
+14 -1
View File
@@ -79,7 +79,20 @@ pub async fn query_kimi_coding(api_key: &str, timeout: Duration) -> Result<Usage
)
.await?
{
Fetched::Body(body) => Ok(UsageResult::ok(parse_kimi_coding(&body))),
Fetched::Body(body) => {
let tiers = parse_kimi_coding(&body);
if tiers.is_empty() {
// 响应里没有可解析的套餐档位(limits/usage 缺失或字段变了)。
// 把原始响应(仅用量数字,无密钥)透出,方便对照接口结构修复。
let preview = serde_json::to_string(&body)
.unwrap_or_else(|_| "<unserializable body>".into());
let trimmed: String = preview.chars().take(400).collect();
return Ok(UsageResult::failure(format!(
"kimi usages 响应无套餐数据,原始返回: {trimmed}"
)));
}
Ok(UsageResult::ok(tiers))
}
Fetched::Failed(err) => Ok(err),
}
}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"productName": "Kimi Switch",
"version": "0.6.9",
"version": "0.7.5",
"identifier": "com.kimiswitch.app",
"build": {
"beforeDevCommand": "npm run dev",
@@ -37,6 +37,7 @@
"icons/icon.ico",
"icons/icon.icns"
],
"publisher": "codingplan.site",
"windows": {
"webviewInstallMode": {
"type": "downloadBootstrapper"
+21 -2
View File
@@ -5,6 +5,7 @@ import { useConfig } from "./hooks/useConfig";
import { useUpdateCheck } from "./hooks/useUpdateCheck";
import { ProviderList } from "./components/ProviderList";
import { ProviderEdit } from "./components/ProviderEdit";
import { SubagentSettingsPage } from "./components/SubagentSettingsPage";
import { DashboardPage } from "./components/dashboard/DashboardPage";
import { SessionsPage } from "./components/sessions/SessionsPage";
import { SettingsModal } from "./components/SettingsModal";
@@ -70,7 +71,7 @@ export default function App() {
updateConfig,
} = useConfig(agent);
const [view, setView] = useState<"list" | "edit" | "dashboard" | "sessions">("list");
const [view, setView] = useState<"list" | "edit" | "subagent" | "dashboard" | "sessions">("list");
const [editingProvider, setEditingProvider] = useState<string>("");
const [loadTimeout, setLoadTimeout] = useState(false);
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
@@ -573,7 +574,7 @@ export default function App() {
type="button"
onClick={() => setView("list")}
className={`px-3 py-1 text-sm rounded transition-colors ${
view === "list" || view === "edit"
view === "list" || view === "edit" || view === "subagent"
? "bg-blue-600 text-white"
: "text-content-muted hover:text-content-primary"
}`}
@@ -649,6 +650,15 @@ export default function App() {
<DashboardPage />
) : view === "sessions" ? (
<SessionsPage />
) : view === "subagent" ? (
<SubagentSettingsPage
rawOther={config.raw_other}
models={config.models}
onChange={(nextRawOther) =>
updateConfig((cfg) => ({ ...cfg, raw_other: nextRawOther }))
}
onBack={() => setView("list")}
/>
) : view === "list" ? (
<ProviderList
providers={providers}
@@ -813,6 +823,15 @@ export default function App() {
>
{t("openConfigDir")}
</button>
{view === "list" && (
<button
type="button"
onClick={() => setView("subagent")}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("subagentSettings")}
</button>
)}
</div>
</footer>
)}
+25 -104
View File
@@ -1,8 +1,8 @@
import type { ReactNode } from "react";
import { useTranslation } from "../i18n";
import type { TranslationKey } from "../i18n/zh";
import { getAgentSettings, setAgentSettings } from "../lib/agent-settings";
import type { AgentSettings, Hook, PermissionRule } from "../types";
import { Card, Checkbox, NumberField, Segmented } from "./ui/controls";
interface AgentSettingsPanelProps {
rawOther: unknown;
@@ -24,7 +24,18 @@ const PERMISSION_LABELS: Record<(typeof PERMISSION_DECISIONS)[number], Translati
ask: "permissionAsk",
};
const COMMON_EVENTS = ["PreToolUse", "PostToolUse"] as const;
// kimi-code 0.33+ added TurnStarted / UserPromptQueued / TaskStarted /
// SessionHeartbeat hook events (plus SessionStart / SessionEnd).
const COMMON_EVENTS = [
"PreToolUse",
"PostToolUse",
"TurnStarted",
"UserPromptQueued",
"TaskStarted",
"SessionHeartbeat",
"SessionStart",
"SessionEnd",
] as const;
export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelProps) {
const { t } = useTranslation();
@@ -91,9 +102,18 @@ export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelPro
<Card title={t("loopControlSettings")}>
<NumberField
label={t("maxRetriesPerStep")}
value={settings.loop_control?.max_retries_per_step ?? 3}
onChange={(v) => updateLoopControl({ max_retries_per_step: v })}
label={t("maxAttemptsPerStep")}
value={
settings.loop_control?.max_attempts_per_step ??
settings.loop_control?.max_retries_per_step ??
3
}
onChange={(v) =>
updateLoopControl({
max_attempts_per_step: v,
max_retries_per_step: v,
})
}
/>
<NumberField
label={t("reservedContextSize")}
@@ -275,102 +295,3 @@ export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelPro
</div>
);
}
function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="bg-panel border border-border rounded-xl p-4 space-y-3">
<h4 className="text-content-muted text-sm font-medium">{title}</h4>
{children}
</div>
);
}
function Checkbox({
label,
checked,
disabled,
onChange,
}: {
label: string;
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<label
className={`flex items-center gap-2 text-sm ${
disabled ? "text-content-muted" : "text-content-primary"
}`}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="rounded border-border bg-input text-blue-600 focus:ring-blue-500"
/>
{label}
</label>
);
}
function NumberField({
label,
value,
onChange,
}: {
label: string;
value?: number;
onChange: (value: number | undefined) => void;
}) {
return (
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{label}</span>
<input
type="number"
value={value ?? ""}
onChange={(e) => {
const raw = e.target.value;
onChange(raw === "" ? undefined : Number(raw));
}}
className="w-32 bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</label>
);
}
function Segmented({
options,
value,
onChange,
disabled,
}: {
options: { key: string; label: string }[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}) {
return (
<div
className={`flex items-center rounded overflow-hidden border border-border ${
disabled ? "opacity-50" : ""
}`}
>
{options.map((opt) => (
<button
key={opt.key}
type="button"
disabled={disabled}
onClick={() => onChange(opt.key)}
className={`px-3 py-1 text-sm ${
value === opt.key
? "bg-blue-600 text-white"
: "bg-input text-content-muted hover:bg-hover-2"
}`}
>
{opt.label}
</button>
))}
</div>
);
}
+16 -7
View File
@@ -699,6 +699,7 @@ function ModelMapping({
<td className="px-4 py-2">
<CapabilitiesCell
capabilities={m.capabilities || []}
nativeImage={getModelRef(m.model)?.image === true}
onChange={(next) =>
onModelChange({ ...m, capabilities: next })
}
@@ -822,9 +823,13 @@ function JsonPreview({
function CapabilitiesCell({
capabilities,
onChange,
nativeImage,
}: {
capabilities: string[];
onChange: (next: string[]) => void;
/** 模型本身是否原生支持图像输入(models.dev `image` 能力)。原生多模态
* 模型无需 kimi-eyes 插件,提示不展示。 */
nativeImage?: boolean;
}) {
const { t } = useTranslation();
@@ -838,13 +843,12 @@ function CapabilitiesCell({
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
{/* Only `thinking` is user-editable. The other capabilities
(always_thinking / image_in / video_in / tool_use) are still
auto-derived from models.dev via `capabilitiesFromRef` and saved
to config.toml — they just aren't exposed for manual editing.
To restore the full editor, drop the `.filter(...)` below and
re-add the custom-capabilities input (see git history). */}
{KNOWN_CAPABILITIES.filter((cap) => cap === "thinking").map((cap) => (
{/* `thinking` 与 `image_in`(识图)可手动编辑;其余能力
(always_thinking / video_in / tool_use) 仍由 models.dev 自动派生,
保存时照常写入 config.toml。 */}
{KNOWN_CAPABILITIES.filter(
(cap) => cap === "thinking" || cap === "image_in",
).map((cap) => (
<label
key={cap}
className="flex items-center gap-1 text-xs text-content-muted cursor-pointer"
@@ -858,6 +862,11 @@ function CapabilitiesCell({
{t(CAPABILITY_LABELS[cap])}
</label>
))}
{capabilities.includes("image_in") && !nativeImage && (
<span className="w-full text-[11px] text-content-muted">
{t("capImageInHint")}
</span>
)}
</div>
);
}
+12
View File
@@ -384,6 +384,18 @@ export function SettingsModal({
billowliu2.github.io/KimiSwitch
</button>
</div>
<div>
{t("kimiEyesSite")}:{" "}
<button
type="button"
onClick={() =>
openExternal("https://billowliu2.github.io/kimi-eyes")
}
className="text-blue-500 hover:text-blue-400 underline bg-transparent p-0 border-0 cursor-pointer"
>
billowliu2.github.io/kimi-eyes
</button>
</div>
<div>
{t("attributionPorted")}{" "}
<button
+586
View File
@@ -0,0 +1,586 @@
import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { useTranslation } from "../i18n";
import type { TranslationKey } from "../i18n/zh";
import type { ExperimentalEnvStatus, Model } from "../types";
import {
EXPERIMENTAL_FLAGS,
clearSecondaryModel,
forcedEnvValue,
getExperimentalFlags,
getSubagentModelPool,
isFlagLockedByEnv,
isMasterEnvOn,
removeSubagentPoolEntry,
setExperimentalFlag,
setSecondaryModelOnly,
setSubagentDefault,
setSubagentForce,
upsertSubagentPoolEntry,
validateSubagentPool,
type ExperimentalFlagDef,
type PoolValidationError,
type ValidationErrorKey,
} from "../lib/subagent-settings";
import { Card, Toggle } from "./ui/controls";
interface SubagentSettingsPageProps {
/** config.raw_other — hosts the `[experimental]` and `[secondary_model]` sections. */
rawOther: unknown;
/** All configured models (alias → entry) for the secondary-model picker. */
models: Record<string, Model>;
onChange: (nextRawOther: unknown) => void;
onBack: () => void;
}
const EFFORTS = ["low", "medium", "high", "max"] as const;
const EFFORT_LABELS: Record<(typeof EFFORTS)[number], TranslationKey> = {
low: "thinkingLow",
medium: "thinkingMedium",
high: "thinkingHigh",
max: "thinkingMax",
};
const FLAG_LABELS: Record<string, { name: TranslationKey; desc: TranslationKey }> = {
"secondary-model": { name: "flagSecondaryModel", desc: "flagSecondaryModelDesc" },
"tool-select": { name: "flagToolSelect", desc: "flagToolSelectDesc" },
"acp-v2": { name: "flagAcpV2", desc: "flagAcpV2Desc" },
persistence_minidb_readmodel: {
name: "flagMinidbReadmodel",
desc: "flagMinidbReadmodelDesc",
},
};
/** Validation-error i18n key per engine rule, for the pre-write self-check. */
const POOL_ERROR_KEYS: Record<ValidationErrorKey, TranslationKey> = {
primaryReserved: "secondaryPoolErrorPrimaryReserved",
defaultRequired: "secondaryPoolErrorDefaultRequired",
defaultNotInPool: "secondaryPoolErrorDefaultNotInPool",
aliasNotInModels: "secondaryPoolErrorAliasNotInModels",
forceRequiresDefault: "secondaryPoolErrorForceRequiresDefault",
forceExcludesModels: "secondaryPoolErrorForceExcludesModels",
};
/**
* One row of the subagent model pool: default radio + alias + editable
* description (saved on blur/Enter via the parent's write chain) + remove.
* The description input keeps a local draft so typing is not persisted per
* keystroke; everything else is derived from `rawOther` on each render.
*/
function PoolEntryRow({
alias,
displayName,
description,
isDefault,
canRemove,
onSetDefault,
onSave,
onRemove,
}: {
alias: string;
displayName: string | null;
description: string;
isDefault: boolean;
canRemove: boolean;
onSetDefault: (alias: string) => void;
onSave: (alias: string, description: string) => void;
onRemove: (alias: string) => void;
}) {
const { t } = useTranslation();
const [draft, setDraft] = useState(description);
const commit = () => {
if (draft === description) return;
onSave(alias, draft);
};
return (
<div className="flex items-center gap-2 text-sm">
<input
type="radio"
checked={isDefault}
aria-label={t("setDefault")}
onChange={() => onSetDefault(alias)}
className="shrink-0 accent-blue-600 focus:ring-blue-500"
/>
<span className="shrink-0 font-medium text-content-primary">{alias}</span>
{displayName && (
<span className="shrink-0 text-xs text-content-muted">{displayName}</span>
)}
{isDefault && (
<span className="shrink-0 text-xs text-blue-600 dark:text-blue-400 border border-blue-500/30 rounded px-1">
{t("default")}
</span>
)}
<input
type="text"
value={draft}
placeholder={t("secondaryPoolDescPlaceholder")}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
(e.currentTarget as HTMLInputElement).blur();
} else if (e.key === "Escape") {
setDraft(description);
(e.currentTarget as HTMLInputElement).blur();
}
}}
className="flex-1 min-w-0 bg-input border border-border rounded px-2 py-1 text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
{canRemove && (
<button
type="button"
onClick={() => onRemove(alias)}
className="shrink-0 px-2 py-1 text-xs border border-border rounded hover:bg-hover-2 text-content-muted focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryPoolRemove")}
</button>
)}
</div>
);
}
export function SubagentSettingsPage({
rawOther,
models,
onChange,
onBack,
}: SubagentSettingsPageProps) {
const { t } = useTranslation();
const [env, setEnv] = useState<ExperimentalEnvStatus | null>(null);
/** Pre-write validation failures (fallback guard; normal flows stay clear). */
const [poolErrors, setPoolErrors] = useState<PoolValidationError[]>([]);
/** Local draft for the "add pool entry" select (reset after each pick). */
const [addSelection, setAddSelection] = useState("");
useEffect(() => {
invoke<ExperimentalEnvStatus>("get_experimental_env_status")
.then(setEnv)
.catch(() => setEnv({}));
}, []);
const flags = getExperimentalFlags(rawOther);
const pool = getSubagentModelPool(rawOther);
const poolKeys = pool ? Object.keys(pool.models) : [];
// View selection: no/empty section or a bare legacy `model` → simple view;
// a `models` table or `default_model` → pool management view.
const isPoolView =
!!pool && (poolKeys.length > 0 || pool.defaultModel !== undefined);
// Effective default: v2 pool key first, legacy v1 recipe key as fallback.
const effectiveDefault = pool ? pool.defaultModel ?? pool.model : undefined;
// "Upgrade" only makes sense for the bare legacy form and when `force` is
// 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 (env overrides config). */
const secondaryEnabled = masterOn
? true
: isFlagLockedByEnv(env, secondaryFlag)
? forcedEnvValue(env, secondaryFlag)
: flags["secondary-model"] === true;
const secondaryLocked = masterOn || isFlagLockedByEnv(env, secondaryFlag);
const aliasList = Object.keys(models).sort();
const aliasLabel = (alias: string): string =>
models[alias]?.display_name
? `${alias}(${models[alias].display_name})`
: alias;
// Rows of the pool view: every `models` table key plus the effective default
// when it is not already in the table (the implicit single-entry form).
const implicitDefault =
pool && effectiveDefault && !(effectiveDefault in pool.models)
? [effectiveDefault]
: [];
const poolEntries = [...poolKeys, ...implicitDefault];
// Aliases that can still be added to the pool (not already in the table).
const addableAliases = aliasList.filter((a) => !(a in (pool?.models ?? {})));
// Inherited settings shown for the picked model: subagents bind the pointed
// entry directly (no patch fields), so context size and effort come from the
// model entry / global [thinking], not from a `[secondary_model]` patch.
const selectedEntry = effectiveDefault ? models[effectiveDefault] : undefined;
const inheritedContext = selectedEntry?.max_context_size;
const modelEffort =
selectedEntry &&
typeof (selectedEntry.raw_other as Record<string, unknown> | undefined)
?.default_effort === "string"
? ((selectedEntry.raw_other as Record<string, unknown>).default_effort as string)
: undefined;
const thinkingEffort = (() => {
const ro = rawOther as Record<string, unknown> | undefined;
const thinking = ro?.thinking as Record<string, unknown> | undefined;
return thinking && typeof thinking.effort === "string" && thinking.effort
? thinking.effort
: undefined;
})();
const inheritedEffort = modelEffort ?? thinkingEffort;
const fmtContext = (n: number): string =>
n >= 1_000_000
? `${(n / 1_000_000).toFixed(1)}M`
: n >= 1000
? `${Math.round(n / 1000)}K`
: String(n);
const effortLabel = (e: string): string => {
const key = EFFORT_LABELS[e as (typeof EFFORTS)[number]];
return key ? t(key) : e;
};
/**
* Fallback guard before any pool-related write: validate the *target* state
* against the engine rules (mirrored by `validateSubagentPool`) and block the
* write when it would produce an invalid config. Normal UI flows never trip
* this — it protects against stale/divergent configs.
*/
const validateWrite = (nextRaw: unknown): boolean => {
const nextPool = getSubagentModelPool(nextRaw);
const errors = nextPool ? validateSubagentPool(nextPool, aliasList) : [];
setPoolErrors(errors);
return errors.length === 0;
};
const handleUpgrade = () => {
if (!effectiveDefault) return;
const nextRaw = setSubagentDefault(rawOther, effectiveDefault);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleSetDefault = (alias: string) => {
if (alias === effectiveDefault) return;
const nextRaw = setSubagentDefault(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleSaveDescription = (alias: string, description: string) => {
const nextRaw = upsertSubagentPoolEntry(rawOther, alias, description);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleRemoveEntry = (alias: string) => {
const nextRaw = removeSubagentPoolEntry(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleAddEntry = (alias: string) => {
const nextRaw = upsertSubagentPoolEntry(rawOther, alias, "");
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleForceChange = (next: boolean) => {
if (!pool) return;
// Turning force on drops the `models` table — confirm when it is non-empty.
if (next && Object.keys(pool.models).length > 0) {
if (!confirm(t("secondaryPoolForceConfirm"))) return;
}
const nextRaw = setSubagentForce(rawOther, next);
if (validateWrite(nextRaw)) onChange(nextRaw);
};
const handleClear = () => {
setPoolErrors([]);
onChange(clearSecondaryModel(rawOther));
};
const renderFlagRow = (flag: ExperimentalFlagDef) => {
const labels = FLAG_LABELS[flag.id];
const locked = masterOn || isFlagLockedByEnv(env, flag);
const on = masterOn
? true
: isFlagLockedByEnv(env, flag)
? forcedEnvValue(env, flag)
: flags[flag.id] === true;
return (
<div key={flag.id} className="flex items-center gap-3">
<div className="flex-1 min-w-0">
<div className="text-sm text-content-primary">{t(labels.name)}</div>
<div className="text-xs text-content-muted">
{t(labels.desc)}
<code className="ml-2">{flag.envVar}</code>
</div>
</div>
{locked && (
<span className="text-xs text-content-muted shrink-0">
🔒 {t("lockedByEnv")}
</span>
)}
<Toggle
checked={on}
disabled={locked}
ariaLabel={t(labels.name)}
onChange={(checked) =>
onChange(setExperimentalFlag(rawOther, flag.id, checked))
}
/>
</div>
);
};
return (
<div className="h-full flex flex-col bg-app">
{/* Header */}
<div className="flex items-center gap-3 px-4 py-3 border-b border-border bg-panel">
<button
type="button"
onClick={onBack}
className="p-2 rounded-lg hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
← {t("back")}
</button>
<h2 className="font-semibold text-lg">{t("subagentSettings")}</h2>
</div>
<div className="flex-1 overflow-auto p-6 space-y-4">
{masterOn && (
<div className="bg-green-100 dark:bg-green-900/20 border border-green-300 dark:border-green-500/30 rounded-lg px-4 py-2 text-sm text-green-700 dark:text-green-400">
{t("masterEnvOnHint")}
</div>
)}
{/* Kimi Code WebUI quick open */}
<Card title={t("webuiSection")}>
<p className="text-xs text-content-muted">{t("webuiDesc")}</p>
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
onClick={async () => {
try {
await invoke("open_kimi_web_embedded");
} catch (err) {
alert(err instanceof Error ? err.message : String(err));
}
}}
className="px-3 py-1.5 text-sm rounded bg-blue-600 text-white hover:bg-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("openWebUIEmbedded")}
</button>
<button
type="button"
onClick={async () => {
try {
await invoke("open_kimi_web");
} catch (err) {
alert(err instanceof Error ? err.message : String(err));
}
}}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("openWebUIBrowser")}
</button>
</div>
</Card>
{/* Subagent: secondary model picker / pool + inherited settings */}
<Card title={t("secondaryModelSection")}>
{isPoolView && pool ? (
<>
{pool.force ? (
/* Force on: the `models` table was dropped — only the pinned
default is shown, entries and "add" are hidden. */
<div className="rounded-lg border border-border bg-input/40 px-3 py-2.5">
<div className="text-sm font-medium text-content-primary">
🔒{" "}
{t("secondaryPoolForceOn", {
alias: aliasLabel(effectiveDefault ?? ""),
})}
</div>
</div>
) : (
<>
<div className="space-y-2">
{poolEntries.map((alias) => (
<PoolEntryRow
key={alias}
alias={alias}
displayName={models[alias]?.display_name ?? null}
description={pool.models[alias] ?? ""}
isDefault={alias === effectiveDefault}
canRemove={alias in pool.models}
onSetDefault={handleSetDefault}
onSave={handleSaveDescription}
onRemove={handleRemoveEntry}
/>
))}
</div>
<p className="text-xs text-content-muted">
{t("secondaryPoolDescHint")}
</p>
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="shrink-0 text-content-muted">
{t("secondaryPoolAddLabel")}
</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={addSelection}
onChange={(e) => {
const alias = e.target.value;
setAddSelection("");
if (alias) handleAddEntry(alias);
}}
>
<option value="">{t("secondaryPoolAddPlaceholder")}</option>
{addableAliases.map((alias) => (
<option key={alias} value={alias}>
{aliasLabel(alias)}
</option>
))}
</select>
</label>
</>
)}
<div className="flex items-center gap-3">
<div className="flex-1 min-w-0">
<div className="text-sm text-content-primary">
{t("secondaryPoolForce")}
</div>
<div className="text-xs text-content-muted">
{t("secondaryPoolForceDesc")}
</div>
</div>
<Toggle
checked={pool.force}
ariaLabel={t("secondaryPoolForce")}
onChange={handleForceChange}
/>
</div>
<button
type="button"
onClick={handleClear}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryModelClear")}
</button>
</>
) : (
<>
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="shrink-0 text-content-muted">
{t("secondaryModelLabel")}
</span>
<select
className="flex-1 max-w-md bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
value={effectiveDefault ?? ""}
onChange={(e) => {
const alias = e.target.value;
if (alias === "") {
setPoolErrors([]);
onChange(clearSecondaryModel(rawOther));
} else {
// Only the model reference is persisted — no patch fields.
// Subagents bind the pointed entry directly and inherit
// its settings; usage records stay keyed on the real
// alias instead of the synthesized `__secondary__` entry.
const nextRaw = setSecondaryModelOnly(rawOther, alias);
if (validateWrite(nextRaw)) onChange(nextRaw);
}
}}
>
<option value="">{t("secondaryModelUnset")}</option>
{aliasList.map((alias) => (
<option key={alias} value={alias}>
{aliasLabel(alias)}
</option>
))}
</select>
{pool?.force && (
<span className="shrink-0 text-xs text-content-muted">
🔒 {t("secondaryModelForceBadge")}
</span>
)}
</label>
{canUpgrade && (
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleUpgrade}
className="px-3 py-1.5 text-sm border border-border rounded hover:bg-hover-2 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
{t("secondaryPoolUpgrade")}
</button>
<span className="text-xs text-content-muted">
{t("secondaryPoolUpgradeDesc")}
</span>
</div>
)}
</>
)}
{poolErrors.length > 0 && (
<div
role="alert"
className="bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-500/30 rounded-lg px-3 py-2 text-sm text-red-700 dark:text-red-400 space-y-1"
>
{poolErrors.map((err, i) => (
<div key={i}>{t(POOL_ERROR_KEYS[err.key], err.params)}</div>
))}
</div>
)}
<div className="border-t border-border" />
<div className="flex items-center gap-3">
<div className="flex-1 min-w-0">
<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))
}
/>
</div>
{effectiveDefault !== undefined && (
<div className="rounded-lg border border-border bg-input/40 px-3 py-2.5 space-y-2">
<div className="flex items-baseline gap-2 text-sm">
<span className="shrink-0 text-content-muted">
{t("secondaryModelInheritedContext")}
</span>
<span className="font-medium text-content-primary">
{inheritedContext ? fmtContext(inheritedContext) : "—"}
</span>
</div>
<div className="flex items-baseline gap-2 text-sm">
<span className="shrink-0 text-content-muted">
{t("secondaryModelInheritedEffort")}
</span>
<span className="font-medium text-content-primary">
{inheritedEffort ? effortLabel(inheritedEffort) : "—"}
</span>
</div>
<p className="text-xs text-content-muted">
{t("secondaryModelInheritedHint")}
</p>
</div>
)}
<p className="text-xs text-content-muted">{t("secondaryModelPriorityHint")}</p>
</Card>
{/* Other experimental features (not subagent-related) */}
<Card title={t("otherExperimentalFlags")}>
{otherFlags.map(renderFlagRow)}
<p className="text-xs text-content-muted">{t("experimentalFlagsHint")}</p>
</Card>
</div>
</div>
);
}
+3 -1
View File
@@ -357,7 +357,9 @@ export function UsageFooter({
// success, or error/loading with last-good data (ghost).
// Compact header already shows the primary entry; detail only adds value
// when there are multiple tiers (e.g. 5h + weekly) or on error ghost.
if (data.length <= 1 && status === "success") return null;
// NOTE: single-tier plans (e.g. only five_hour) must still render — hiding
// them made kimi-for-coding look like it had no plan quota at all.
if (data.length === 0 && status === "success") return null;
const ghost = status !== "success";
return (
<div
+10 -1
View File
@@ -59,6 +59,10 @@ export function DailyBars({ daily, dimension, names, unknownProviderLabel }: Dai
if (dimension === "provider") {
return key === "unknown" ? unknownProviderLabel : key;
}
// Subagent records (Kimi Code `__secondary__` marker) show their own label.
if (key === "__secondary__") {
return t("subagentModel");
}
return shortModel(key);
};
@@ -93,7 +97,12 @@ export function DailyBars({ daily, dimension, names, unknownProviderLabel }: Dai
const h = Math.max(4, Math.round(((d.totalTokens || 0) / max) * 170));
const total = d.totalTokens || 1;
const breakdown = dimension === "provider" ? d.byProvider : d.byModel;
const breakdown =
dimension === "provider"
? d.byProvider
: Object.fromEntries(
Object.entries(d.byModel || {}).map(([k, v]) => [k, v.totalTokens])
);
const segments = Object.entries(breakdown || {})
.map(([key, tokens]) => ({
key,
+27 -18
View File
@@ -25,6 +25,10 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
const { t } = useTranslation();
const { money } = useCurrency();
/** Subagent records (Kimi Code `__secondary__` marker) show their own label. */
const modelName = (model: string) =>
model === "__secondary__" ? t("subagentModel") : shortModel(model);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
@@ -44,12 +48,15 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
const total = day.totalTokens || 1;
const isProvider = dimension === "provider";
// Flat per-model breakdown (model tab)
// Flat per-model breakdown (model tab) — structured TotalsRow per model
const modelSegments = Object.entries(day.byModel || {})
.map(([model, tokens]) => ({
.map(([model, row]) => ({
model,
tokens,
pct: (tokens / total) * 100,
tokens: row.totalTokens,
requests: row.requests,
costUsd: row.costUsd,
cacheHitRate: row.cacheHitRate,
pct: ((row.totalTokens || 0) / total) * 100,
}))
.sort((a, b) => b.tokens - a.tokens);
@@ -143,7 +150,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
<div className="mt-1 ml-5 space-y-0.5">
{p.models.map((m) => (
<div key={m.model} className="flex items-baseline justify-between gap-2 text-xs">
<span className="truncate text-content-muted" title={m.model}>{shortModel(m.model)}</span>
<span className="truncate text-content-muted" title={m.model}>{modelName(m.model)}</span>
<span className="shrink-0 text-content-muted tabular-nums">{fmtTokens(m.tokens)}</span>
</div>
))}
@@ -161,20 +168,22 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
{modelSegments.length === 0 ? (
<div className="py-6 text-center text-sm text-content-muted">{t("noData")}</div>
) : (
<div className="space-y-1.5 max-h-72 overflow-y-auto pr-1">
<div className="space-y-2 max-h-72 overflow-y-auto pr-1">
{modelSegments.map((s, i) => (
<div key={s.model} className="flex items-center gap-3 text-sm">
<span className="inline-block h-2.5 w-2.5 rounded-sm shrink-0" style={{ backgroundColor: modelColor(i) }} />
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-2">
<span className="truncate text-content-primary" title={s.model}>{shortModel(s.model)}</span>
<span className="shrink-0 text-xs text-content-muted tabular-nums">
{fmtTokens(s.tokens)} <span className="text-content-muted">· {s.pct.toFixed(1)}%</span>
</span>
</div>
<div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-border">
<div className="h-full rounded-full transition-all" style={{ width: `${Math.max(2, s.pct)}%`, backgroundColor: modelColor(i) }} />
</div>
<div key={s.model} className="rounded-lg bg-hover/50 px-3 py-2">
<div className="flex items-center gap-2 text-sm">
<span className="inline-block h-2.5 w-2.5 rounded-sm shrink-0" style={{ backgroundColor: modelColor(i) }} />
<span className="truncate flex-1 text-content-primary" title={s.model}>{modelName(s.model)}</span>
<span className="shrink-0 text-xs text-content-muted tabular-nums">{s.pct.toFixed(1)}%</span>
</div>
<div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-border">
<div className="h-full rounded-full transition-all" style={{ width: `${Math.max(2, s.pct)}%`, backgroundColor: modelColor(i) }} />
</div>
<div className="mt-1.5 flex flex-wrap gap-x-4 gap-y-0.5 text-xs text-content-muted tabular-nums">
<span>{t("totalTokens")}: <span className="text-content-primary font-medium">{fmtTokens(s.tokens)}</span></span>
<span>{t("requests")}: <span className="text-content-primary font-medium">{s.requests.toLocaleString()}</span></span>
{s.costUsd > 0 && <span>{t("cost")}: <span className="text-content-primary font-medium">{money(s.costUsd)}</span></span>}
<span>{t("cacheHitRate")}: <span className="text-content-primary font-medium">{fmtPct(s.cacheHitRate)}</span></span>
</div>
</div>
))}
+48 -4
View File
@@ -1,11 +1,15 @@
import { useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { invoke } from "@tauri-apps/api/core";
import { useDashboard, type DashboardRange } from "../../hooks/useDashboard";
import { useCurrency } from "../../hooks/useCurrency";
import { useTranslation } from "../../i18n";
import { fmtInt, fmtPct, fmtTime, fmtTokens } from "../../lib/dashboard-format";
import { DailyBars } from "./DailyBars";
import { DailyDetailModal } from "./DailyDetailModal";
import { Heatmap } from "./Heatmap";
import { TrendLineChart } from "./TrendLineChart";
import type { DailyRow, HeatmapCell } from "../../types/dashboard";
const RANGES: DashboardRange[] = ["today", "7d", "30d", "all"];
@@ -56,6 +60,9 @@ export function DashboardPage() {
const [showAllModels, setShowAllModels] = useState(false);
const [recentPage, setRecentPage] = useState(1);
const [trendTab, setTrendTab] = useState<"daily" | "model" | "provider">("daily");
const [heatmapSelected, setHeatmapSelected] = useState<DailyRow | null>(null);
const daily = data?.stats.daily ?? [];
const RANGE_LABELS: Record<DashboardRange, string> = {
today: t("rangeToday"),
@@ -92,13 +99,29 @@ export function DashboardPage() {
if (!data) return null;
const totals = data.stats.totals;
const daily = data.stats.daily;
const models = data.stats.models;
const recent = data.stats.recent;
const heatmap = data.heatmap;
const rangeTotals = data.rangeTotals;
const visibleModels = showAllModels ? models : models.slice(0, 8);
const onHeatmapCellDoubleClick = async (cell: HeatmapCell) => {
try {
const row = await invoke<DailyRow | null>("get_day_detail", {
date: cell.date,
});
if (row) {
setHeatmapSelected(row);
} else {
setHeatmapSelected(null);
alert(t("dayDetailNoData", { date: cell.date }));
}
} catch (err) {
setHeatmapSelected(null);
alert(err instanceof Error ? err.message : String(err));
}
};
// Recent pagination
const RECENT_PAGE_SIZE = 30;
const recentTotal = data.stats.recentTotal;
@@ -206,7 +229,7 @@ export function DashboardPage() {
{/* Heatmap — full row */}
<Card title={t("cardHeatmap")} subtitle={t("cardHeatmapSub")}>
<Heatmap heatmap={heatmap} />
<Heatmap heatmap={heatmap} onCellDoubleClick={onHeatmapCellDoubleClick} />
</Card>
{/* Usage-trend tabs + Model table side by side */}
@@ -310,7 +333,9 @@ export function DashboardPage() {
}}
/>
<div className="flex items-center gap-1.5 min-w-0">
<span className="text-content-primary whitespace-nowrap truncate">{m.modelDisplay || m.model}</span>
<span className="text-content-primary whitespace-nowrap truncate">
{m.isSecondary ? t("subagentModel") : m.modelDisplay || m.model}
</span>
{m.costEstimated && (
<span className="text-[10px] text-yellow-600 shrink-0">({t("estimate")})</span>
)}
@@ -371,7 +396,13 @@ export function DashboardPage() {
<td className="py-1.5 pr-4 text-content-muted whitespace-nowrap">
{fmtTime(r.time)}
</td>
<td className="py-1.5 pr-4 text-content-primary">{r.modelDisplay || r.model}</td>
<td className="py-1.5 pr-4 text-content-primary">
<span className="flex items-center gap-1.5 min-w-0">
<span className="truncate">
{r.isSecondary ? t("subagentModel") : r.modelDisplay || r.model}
</span>
</span>
</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputOther)}</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.output)}</td>
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputCacheRead)}</td>
@@ -443,6 +474,19 @@ export function DashboardPage() {
{data.meta.home}
</div>
</div>
{/* Heatmap double-click detail modal */}
{heatmapSelected &&
createPortal(
<DailyDetailModal
day={heatmapSelected}
dimension="model"
colorMap={{}}
unknownProviderLabel={t("providerUnknown")}
onClose={() => setHeatmapSelected(null)}
/>,
document.body,
)}
</div>
);
}
+6 -2
View File
@@ -7,6 +7,8 @@ import type { HeatmapCell, HeatmapData } from "../../types/dashboard";
interface HeatmapProps {
heatmap: HeatmapData;
/** Called when a cell with data (level > 0) is double-clicked. */
onCellDoubleClick?: (cell: HeatmapCell) => void;
}
const LEVEL_BG = [
@@ -30,7 +32,7 @@ interface HoverState {
y: number;
}
export function Heatmap({ heatmap }: HeatmapProps) {
export function Heatmap({ heatmap, onCellDoubleClick }: HeatmapProps) {
const { t, lang } = useTranslation();
const cells = heatmap?.cells || [];
const monthLabels = heatmap?.monthLabels || [];
@@ -172,6 +174,7 @@ export function Heatmap({ heatmap }: HeatmapProps) {
);
}
const level = cell.level ?? 0;
const hasDetail = level > 0;
return (
<button
key={cell.date}
@@ -182,7 +185,8 @@ export function Heatmap({ heatmap }: HeatmapProps) {
onMouseLeave={hideTooltip}
onFocus={() => showTooltipFromFocus(cell)}
onBlur={hideTooltip}
className={`rounded-[3px] ring-1 ring-inset ring-white/5 transition-transform hover:scale-[1.35] focus:scale-[1.35] outline-none ${LEVEL_BG[level] || LEVEL_BG[0]}`}
onDoubleClick={hasDetail && onCellDoubleClick ? () => onCellDoubleClick(cell) : undefined}
className={`rounded-[3px] ring-1 ring-inset ring-white/5 transition-transform outline-none ${LEVEL_BG[level] || LEVEL_BG[0]} ${hasDetail && onCellDoubleClick ? "cursor-pointer hover:scale-[1.35] focus:scale-[1.35]" : "cursor-default"}`}
style={{ width: CELL, height: CELL }}
/>
);
+137
View File
@@ -0,0 +1,137 @@
import type { ReactNode } from "react";
/** Shared small form controls used by settings panels (Agent settings,
* Subagent settings, ...). Extracted from AgentSettingsPanel.tsx so new
* panels can reuse the same look without duplicating code. */
export function Card({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="bg-panel border border-border rounded-xl p-4 space-y-3">
<h4 className="text-content-muted text-sm font-medium">{title}</h4>
{children}
</div>
);
}
export function Checkbox({
label,
checked,
disabled,
onChange,
}: {
label: string;
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
}) {
return (
<label
className={`flex items-center gap-2 text-sm ${
disabled ? "text-content-muted" : "text-content-primary"
}`}
>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="rounded border-border bg-input text-blue-600 focus:ring-blue-500"
/>
{label}
</label>
);
}
/** Pill-style toggle switch with a sliding knob. */
export function Toggle({
checked,
disabled,
onChange,
ariaLabel,
}: {
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
ariaLabel?: string;
}) {
return (
<button
type="button"
role="switch"
aria-checked={checked}
aria-label={ariaLabel}
disabled={disabled}
onClick={() => onChange(!checked)}
className={`relative h-5 w-9 shrink-0 rounded-full transition-colors duration-200 focus:ring-2 focus:ring-blue-500 focus:outline-none ${
checked ? "bg-blue-600" : "bg-border"
} ${disabled ? "cursor-not-allowed opacity-50" : ""}`}
>
<span
className={`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition-transform duration-200 ${
checked ? "translate-x-4" : "translate-x-0"
}`}
/>
</button>
);
}
export function NumberField({
label,
value,
onChange,
}: {
label: string;
value?: number;
onChange: (value: number | undefined) => void;
}) {
return (
<label className="flex items-center gap-3 text-sm text-content-primary">
<span className="text-content-muted">{label}</span>
<input
type="number"
value={value ?? ""}
onChange={(e) => {
const raw = e.target.value;
onChange(raw === "" ? undefined : Number(raw));
}}
className="w-32 bg-input border border-border rounded px-2 py-1 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
/>
</label>
);
}
export function Segmented({
options,
value,
onChange,
disabled,
}: {
options: { key: string; label: string }[];
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}) {
return (
<div
className={`flex items-center rounded overflow-hidden border border-border ${
disabled ? "opacity-50" : ""
}`}
>
{options.map((opt) => (
<button
key={opt.key}
type="button"
disabled={disabled}
onClick={() => onChange(opt.key)}
className={`px-3 py-1 text-sm ${
value === opt.key
? "bg-blue-600 text-white"
: "bg-input text-content-muted hover:bg-hover-2"
}`}
>
{opt.label}
</button>
))}
</div>
);
}
+70 -1
View File
@@ -136,7 +136,7 @@ export const enTranslations: Record<TranslationKey, string> = {
thinkingMax: "Max",
thinkingContextHint: "Thinking uses more context. Ensure the model context length and reserved size are sufficient.",
loopControlSettings: "Loop Control",
maxRetriesPerStep: "Max retries per step",
maxAttemptsPerStep: "Max attempts per step",
reservedContextSize: "Reserved context size",
backgroundSettings: "Background Tasks",
maxRunningTasks: "Max running tasks",
@@ -163,6 +163,7 @@ export const enTranslations: Record<TranslationKey, string> = {
capThinking: "Thinking",
capAlwaysThinking: "Always Thinking",
capImageIn: "Image Input",
capImageInHint: "Text models actually need the plugin-kimi-eyes:kimi-eyes plugin for image recognition",
capVideoIn: "Video Input",
capToolUse: "Tool Use",
customCapabilities: "Other capabilities (comma-separated)",
@@ -226,6 +227,7 @@ export const enTranslations: Record<TranslationKey, string> = {
// Daily detail modal
dayDetail: "Daily usage detail",
dayDetailNoData: "No usage data for {date}",
close: "Close",
totalTokens: "Total tokens",
cost: "Cost",
@@ -262,6 +264,7 @@ export const enTranslations: Record<TranslationKey, string> = {
lastChecked: "Last checked",
appDescription: "Windows desktop LLM provider config manager",
settingsWebsite: "Official website",
kimiEyesSite: "Kimi Eyes plugin site",
referenceProject: "Reference project",
// Validation errors
@@ -318,6 +321,7 @@ export const enTranslations: Record<TranslationKey, string> = {
colCacheRead: "Cache read",
unitTimes: "requests",
estimate: "est.",
subagentModel: "Subagent model",
collapse: "Collapse",
expandAll: "Expand all ({n})",
@@ -445,4 +449,69 @@ export const enTranslations: Record<TranslationKey, string> = {
trendLineShowRequests: "Show requests",
trendLineTooltip: "{date}\nTokens: {tokens}\nCache hit: {cache}\nRequests: {req}",
trendLineNoData: "No data",
// 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",
flagAcpV2: "ACP v2 Protocol",
flagAcpV2Desc: "Enable Agent Communication Protocol v2",
flagMinidbReadmodel: "MiniDB Read Model",
flagMinidbReadmodelDesc: "Enable the v2 engine MiniDB read-model backend",
lockedByEnv: "Locked by env var",
masterEnvOnHint: "KIMI_CODE_EXPERIMENTAL_FLAG is set: all experimental features are forced on by the env var",
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",
secondaryModelInheritedEffort: "Inherited effort",
secondaryModelInheritedHint:
"Subagents bind the selected model directly and inherit its context size and effort — no patch needed",
secondaryModelHint:
"Second model config bound to subagents by default; when unset, subagents inherit the primary model. Only the model reference is stored; subagents inherit all of that model's settings",
secondaryModelPriorityHint:
"Priority (v2): tool model param (pool alias or primary) > default_model > inherit primary; (v1 legacy): tool param > model_preference > model > inherit primary",
// Subagent model pool (secondary_model v2 keys)
secondaryPoolUpgrade: "Upgrade to model pool",
secondaryPoolUpgradeDesc:
"Writes default_model in sync with model (dual-write for both engines); more pool entries can be added afterwards",
secondaryPoolAddLabel: "Add pool entry",
secondaryPoolAddPlaceholder: "Select a model to add to the pool…",
secondaryPoolRemove: "Remove",
secondaryPoolDescPlaceholder: "Subagent routing description for this model…",
secondaryPoolDescHint:
"The description is rendered into the main agent's tool description (Agent/AgentSwarm) and directly affects how well the main model routes to subagent models",
secondaryPoolForce: "Force default model",
secondaryPoolForceDesc:
"When enabled, all subagents are forced onto the default model; force excludes pool entries, which are removed",
secondaryPoolForceOn: "Force is on: subagents always use \"{alias}\"",
secondaryPoolForceConfirm:
"Enabling force removes every pool entry, keeping only the default model. Continue?",
secondaryModelClear: "Clear subagent config",
secondaryModelForceBadge: "Force on: subagents always use this model",
secondaryPoolErrorPrimaryReserved:
"\"{alias}\" is a reserved alias and cannot be a pool entry",
secondaryPoolErrorDefaultRequired: "default_model is required when pool entries exist",
secondaryPoolErrorDefaultNotInPool: "Default model \"{alias}\" is not in the pool",
secondaryPoolErrorAliasNotInModels: "Model \"{alias}\" is not registered in [models]",
secondaryPoolErrorForceRequiresDefault:
"A default model is required before enabling force",
secondaryPoolErrorForceExcludesModels:
"force is mutually exclusive with pool entries",
// Kimi Code WebUI quick open
webuiSection: "Kimi Code WebUI",
webuiDesc:
"Open the new Web UI in an independent in-app window, or in your system browser (built into kimi-code 0.33+). Requires the kimi CLI on PATH.",
openWebUIEmbedded: "Open in App",
openWebUIBrowser: "Open in Browser",
};
+67 -1
View File
@@ -134,7 +134,7 @@ export const zhTranslations = {
thinkingMax: "最大",
thinkingContextHint: "启用思考会占用更多上下文,请确保模型上下文长度和预留空间足够。",
loopControlSettings: "循环控制",
maxRetriesPerStep: "单步重试次数",
maxAttemptsPerStep: "单步最大尝试次数",
reservedContextSize: "上下文预留大小",
backgroundSettings: "后台任务",
maxRunningTasks: "最大并发数",
@@ -161,6 +161,7 @@ export const zhTranslations = {
capThinking: "思考",
capAlwaysThinking: "始终思考",
capImageIn: "图像输入",
capImageInHint: "文本推理模型实际需要搭配 plugin-kimi-eyes:kimi-eyes 插件才能识图",
capVideoIn: "视频输入",
capToolUse: "工具调用",
customCapabilities: "其他能力(逗号分隔)",
@@ -221,6 +222,7 @@ export const zhTranslations = {
// Daily detail modal
dayDetail: "每日用量详情",
dayDetailNoData: "「{date}」当日无用量数据",
close: "关闭",
totalTokens: "总 Token",
cost: "费用",
@@ -257,6 +259,7 @@ export const zhTranslations = {
lastChecked: "上次检查",
appDescription: "Windows 桌面端 LLM 供应商配置管理器",
settingsWebsite: "官方网站",
kimiEyesSite: "Kimi Eyes 插件站",
referenceProject: "引用项目",
// Validation errors
@@ -313,6 +316,7 @@ export const zhTranslations = {
colCacheRead: "缓存读",
unitTimes: "次",
estimate: "估算",
subagentModel: "子代理模型",
collapse: "收起",
expandAll: "展开全部 ({n})",
@@ -440,6 +444,68 @@ export const zhTranslations = {
trendLineShowRequests: "显示请求数",
trendLineTooltip: "{date}\nToken: {tokens}\n命中率: {cache}\n请求: {req}",
trendLineNoData: "暂无数据",
// Advanced settings page (WebUI quick open + experimental flags + secondary model)
subagentSettings: "高级设置",
experimentalFlags: "实验功能开关",
otherExperimentalFlags: "其他实验功能",
experimentalFlagsHint:
"开关写入 config.toml 的 [experimental] 节;环境变量优先级更高,被锁定的开关无法在此修改",
flagSecondaryModel: "子代理次主力模型",
flagSecondaryModelDesc: "子代理派发时绑定第二份(通常更便宜的)模型配置",
flagToolSelect: "工具选择",
flagToolSelectDesc: "启用实验性工具选择功能",
flagAcpV2: "ACP v2 协议",
flagAcpV2Desc: "启用 Agent Communication Protocol v2",
flagMinidbReadmodel: "MiniDB 读模型",
flagMinidbReadmodelDesc: "启用 v2 引擎 MiniDB 读模型后端",
lockedByEnv: "被环境变量锁定",
masterEnvOnHint: "KIMI_CODE_EXPERIMENTAL_FLAG 已设置:全部实验功能被环境变量强制开启",
secondaryModelSection: "子代理模型(次主力模型)",
secondaryModelDisabledHint:
"实验开关「子代理次主力模型」未启用,本配置不会生效——请先在上方打开对应开关",
secondaryModelLabel: "次主力模型",
secondaryModelUnset: "未配置",
secondaryModelInheritedContext: "继承上下文长度",
secondaryModelInheritedEffort: "继承思考模式",
secondaryModelInheritedHint:
"子代理直接绑定所选模型,继承其上下文长度与思考设置,无需单独配置补丁",
secondaryModelHint:
"子代理默认绑定的第二份模型配置;未配置时子代理继承主模型;仅保存模型引用,子代理继承该模型的全部设置",
secondaryModelPriorityHint:
"优先级(v2):工具 model 参数(池别名或 primary)> default_model > 继承主模型;(v1 legacy):工具参数 > model_preference > model > 继承主模型",
// Subagent model pool (secondary_model v2 keys)
secondaryPoolUpgrade: "升级为模型池",
secondaryPoolUpgradeDesc:
"为旧式配置补写 default_model,与 model 双写一致;之后可继续添加多个池条目",
secondaryPoolAddLabel: "添加池条目",
secondaryPoolAddPlaceholder: "选择要加入模型池的模型…",
secondaryPoolRemove: "移除",
secondaryPoolDescPlaceholder: "该模型的子代理路由描述…",
secondaryPoolDescHint:
"描述会渲染进主 Agent 的工具描述(Agent/AgentSwarm),直接影响主模型挑选子代理模型的路由质量",
secondaryPoolForce: "强制使用默认模型",
secondaryPoolForceDesc:
"开启后所有子代理固定使用默认模型;force 与模型池条目互斥,条目将被移除",
secondaryPoolForceOn: "force 已开启:子代理固定使用「{alias}」",
secondaryPoolForceConfirm:
"开启 force 将移除模型池中的所有条目,只保留默认模型。确定继续?",
secondaryModelClear: "不再配置",
secondaryModelForceBadge: "force 已开启:子代理固定使用该模型",
secondaryPoolErrorPrimaryReserved: "「{alias}」是保留别名,不能用作模型池条目",
secondaryPoolErrorDefaultRequired: "存在模型池条目时 default_model 必填",
secondaryPoolErrorDefaultNotInPool: "默认模型「{alias}」不在模型池中",
secondaryPoolErrorAliasNotInModels: "模型「{alias}」未在 [models] 中注册",
secondaryPoolErrorForceRequiresDefault: "开启 force 前必须设置默认模型",
secondaryPoolErrorForceExcludesModels: "force 与模型池条目互斥",
// Kimi Code WebUI quick open
webuiSection: "Kimi Code WebUI",
webuiDesc:
"以独立窗口在应用内打开新版 Web 界面,也可以选择在系统浏览器打开(kimi-code 0.33+ 内置 code-app;需要 kimi 命令在 PATH 中)。",
openWebUIEmbedded: "在应用内打开",
openWebUIBrowser: "在浏览器打开",
} as const;
export type TranslationKey = keyof typeof zhTranslations;
+19 -5
View File
@@ -7,7 +7,7 @@ const DEFAULT_SETTINGS: AgentSettings = {
keep: "all",
},
loop_control: {
max_retries_per_step: 3,
max_attempts_per_step: 3,
reserved_context_size: 50000,
},
background: {
@@ -32,15 +32,29 @@ function getSection<T>(rawOther: unknown, key: string): T | undefined {
}
export function getAgentSettings(rawOther: unknown): AgentSettings {
const sectionLoop = getSection<AgentSettings["loop_control"]>(
rawOther,
"loop_control"
);
const loop: AgentSettings["loop_control"] = {
...DEFAULT_SETTINGS.loop_control,
...sectionLoop,
};
// kimi-code 0.33+ (v2 engine) renamed max_retries_per_step →
// max_attempts_per_step; migrate legacy values so they still show and edit.
if (
sectionLoop &&
sectionLoop.max_attempts_per_step === undefined &&
sectionLoop.max_retries_per_step !== undefined
) {
loop.max_attempts_per_step = sectionLoop.max_retries_per_step;
}
return {
thinking: {
...DEFAULT_SETTINGS.thinking,
...getSection<AgentSettings["thinking"]>(rawOther, "thinking"),
},
loop_control: {
...DEFAULT_SETTINGS.loop_control,
...getSection<AgentSettings["loop_control"]>(rawOther, "loop_control"),
},
loop_control: loop,
background: {
...DEFAULT_SETTINGS.background,
...getSection<AgentSettings["background"]>(rawOther, "background"),
+84332 -73347
View File
File diff suppressed because it is too large. Load diff
+68738 -59201
View File
File diff suppressed because it is too large. Load diff
+426
View File
@@ -0,0 +1,426 @@
import { describe, expect, it } from "vitest";
import {
getSecondaryModel,
getSubagentModelPool,
removeSubagentPoolEntry,
setSecondaryModelOnly,
setSubagentDefault,
setSubagentForce,
setSubagentModelPool,
upsertSubagentPoolEntry,
validateSubagentPool,
type SubagentModelPool,
} from "./subagent-settings";
// ---------------------------------------------------------------------------
// Helpers — drill into the `[secondary_model]` section of the written result
// ---------------------------------------------------------------------------
function rawWith(section: Record<string, unknown>): unknown {
return { secondary_model: section };
}
function section(raw: unknown): Record<string, unknown> {
const root = raw as { secondary_model?: unknown };
const sec = root?.secondary_model;
return sec && typeof sec === "object" && !Array.isArray(sec)
? (sec as Record<string, unknown>)
: {};
}
function modelsOf(raw: unknown): Record<string, unknown> {
const m = section(raw)["models"];
return m && typeof m === "object" && !Array.isArray(m)
? (m as Record<string, unknown>)
: {};
}
// ---------------------------------------------------------------------------
// Reading — four config combinations + effective-default normalization
// ---------------------------------------------------------------------------
describe("getSecondaryModel / getSubagentModelPool", () => {
it("returns an empty config / undefined pool when the section is absent or empty", () => {
expect(getSecondaryModel({})).toEqual({});
expect(getSubagentModelPool({})).toBeUndefined();
expect(getSubagentModelPool(rawWith({}))).toBeUndefined();
});
it("legacy `model` alone forms the effective default", () => {
const raw = rawWith({ model: "kimi-k2" });
expect(getSecondaryModel(raw)).toEqual({ model: "kimi-k2" });
const pool = getSubagentModelPool(raw);
expect(pool).toEqual({ model: "kimi-k2", models: {}, force: false });
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k2");
});
it("`default_model` alone forms the effective default", () => {
const raw = rawWith({ default_model: "kimi-k2" });
expect(getSecondaryModel(raw)).toEqual({ default_model: "kimi-k2" });
const pool = getSubagentModelPool(raw);
expect(pool?.defaultModel).toBe("kimi-k2");
expect(pool?.model).toBeUndefined();
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k2");
});
it("a divergent `model` + `default_model` resolves the effective default to `default_model`", () => {
const raw = rawWith({ model: "kimi-k2", default_model: "kimi-k1" });
expect(getSecondaryModel(raw)).toEqual({
model: "kimi-k2",
default_model: "kimi-k1",
});
const pool = getSubagentModelPool(raw);
expect(pool?.model).toBe("kimi-k2");
expect(pool?.defaultModel).toBe("kimi-k1");
expect(pool?.defaultModel ?? pool?.model).toBe("kimi-k1");
});
it("reads the models table filtering non-string values, and force", () => {
const raw = rawWith({
default_model: "kimi-k2",
models: { "kimi-k2": "Kimi K2", "kimi-k2-thinking": 42, broken: true },
force: true,
});
expect(getSecondaryModel(raw).models).toEqual({ "kimi-k2": "Kimi K2" });
expect(getSecondaryModel(raw).force).toBe(true);
expect(getSubagentModelPool(raw)).toMatchObject({
models: { "kimi-k2": "Kimi K2" },
force: true,
});
});
it("reports `force` only when true and tolerates a malformed models table", () => {
expect(getSecondaryModel(rawWith({ force: false })).force).toBeUndefined();
expect(getSubagentModelPool(rawWith({ force: false }))?.force).toBe(false);
const pool = getSubagentModelPool(rawWith({ models: "nope", model: "kimi-k2" }));
expect(pool?.models).toEqual({});
expect(pool?.model).toBe("kimi-k2");
});
});
// ---------------------------------------------------------------------------
// setSecondaryModelOnly — pool-aware pick
// ---------------------------------------------------------------------------
describe("setSecondaryModelOnly", () => {
it("creates the section when absent", () => {
const next = setSecondaryModelOnly({}, "kimi-k2");
expect(section(next)).toEqual({ model: "kimi-k2" });
});
it("without a pool: writes only `model`, drops known patch fields, keeps unknown fields", () => {
const raw = rawWith({
model: "old",
default_effort: "high",
max_output_size: 64000,
max_context_size: 128000,
custom_field: "keep",
});
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(section(next)).toEqual({ model: "kimi-k2", custom_field: "keep" });
});
it("pool via default_model: syncs both keys, adds a missing alias to the table, preserves the rest", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1" },
force: true,
unknown_field: "keep",
});
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
models: { "kimi-k1": "K1", "kimi-k2": "" },
force: true,
unknown_field: "keep",
});
});
it("pool via models table: keeps existing descriptions", () => {
const raw = rawWith({ models: { "kimi-k1": "K1", "kimi-k2": "K2" } });
const next = setSecondaryModelOnly(raw, "kimi-k2");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k2");
expect(section(next).model).toBe("kimi-k2");
});
it("heals a divergent legacy + pool default to the picked alias", () => {
const raw = rawWith({
model: "kimi-k1",
default_model: "kimi-k2",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
});
const next = setSecondaryModelOnly(raw, "kimi-k1");
expect(section(next).model).toBe("kimi-k1");
expect(section(next).default_model).toBe("kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
});
it("preserves other top-level raw_other sections", () => {
const raw = {
experimental: { "secondary-model": true },
secondary_model: { model: "kimi-k1" },
};
const next = setSecondaryModelOnly(raw, "kimi-k2") as {
experimental?: unknown;
};
expect(next.experimental).toEqual({ "secondary-model": true });
});
});
// ---------------------------------------------------------------------------
// Pool mutations — rebuild / upsert / remove / default
// ---------------------------------------------------------------------------
describe("pool mutations", () => {
it("setSubagentModelPool rebuilds with dual-written default (effective wins) and force", () => {
const raw = rawWith({ model: "stale", custom: "keep" });
const next = setSubagentModelPool(raw, {
defaultModel: "kimi-k2",
model: "kimi-k1", // divergent — effective default (`defaultModel`) wins
models: { "kimi-k2": "K2" },
force: true,
});
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
models: { "kimi-k2": "K2" },
force: true,
custom: "keep",
});
});
it("setSubagentModelPool omits the models table when the pool has no entries", () => {
const next = setSubagentModelPool(rawWith({}), {
defaultModel: "kimi-k2",
models: {},
force: false,
});
expect(section(next)).toEqual({
default_model: "kimi-k2",
model: "kimi-k2",
force: false,
});
});
it("setSubagentModelPool is idempotent", () => {
const pool: SubagentModelPool = {
defaultModel: "kimi-k2",
models: { "kimi-k2": "K2" },
force: true,
};
const once = setSubagentModelPool(rawWith({ custom: "keep" }), pool);
const twice = setSubagentModelPool(once, pool);
expect(once).toEqual(twice);
});
it("upsertSubagentPoolEntry adds and updates aliases, preserving the rest", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1" },
force: false,
});
const added = upsertSubagentPoolEntry(raw, "kimi-k2", "K2");
expect(modelsOf(added)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
const updated = upsertSubagentPoolEntry(added, "kimi-k2", "K2 thinking");
expect(modelsOf(updated)).toEqual({
"kimi-k1": "K1",
"kimi-k2": "K2 thinking",
});
expect(section(updated).default_model).toBe("kimi-k1");
});
it("removeSubagentPoolEntry keeps the default when removing a non-default alias", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2", "kimi-k3": "K3" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k3");
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k1");
expect(section(next).model).toBe("kimi-k1");
});
it("removeSubagentPoolEntry falls the default back to the first remaining key", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k2": "K2" });
expect(section(next).default_model).toBe("kimi-k2");
expect(section(next).model).toBe("kimi-k2");
});
it("removeSubagentPoolEntry collapses an emptied pool to the implicit form", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1" },
});
const next = removeSubagentPoolEntry(raw, "kimi-k1");
const sec = section(next);
expect(sec).not.toHaveProperty("models");
expect(sec.default_model).toBe("kimi-k1");
expect(sec.model).toBe("kimi-k1");
});
it("setSubagentDefault syncs both keys and adds a missing alias with an empty description", () => {
const raw = rawWith({ models: { "kimi-k2": "K2" } });
const next = setSubagentDefault(raw, "kimi-k1");
expect(section(next).default_model).toBe("kimi-k1");
expect(section(next).model).toBe("kimi-k1");
expect(modelsOf(next)).toEqual({ "kimi-k2": "K2", "kimi-k1": "" });
});
});
// ---------------------------------------------------------------------------
// setSubagentForce — mutual exclusion with the models table
// ---------------------------------------------------------------------------
describe("setSubagentForce", () => {
it("turning force on drops the models table but keeps the default and unknown fields", () => {
const raw = rawWith({
default_model: "kimi-k1",
model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
custom: "keep",
});
const next = setSubagentForce(raw, true);
const sec = section(next);
expect(sec).not.toHaveProperty("models");
expect(sec.force).toBe(true);
expect(sec.default_model).toBe("kimi-k1");
expect(sec.model).toBe("kimi-k1");
expect(sec.custom).toBe("keep");
});
it("turning force off leaves the models table untouched", () => {
const raw = rawWith({
default_model: "kimi-k1",
models: { "kimi-k1": "K1", "kimi-k2": "K2" },
force: true,
});
const next = setSubagentForce(raw, false);
expect(section(next).force).toBe(false);
expect(modelsOf(next)).toEqual({ "kimi-k1": "K1", "kimi-k2": "K2" });
});
it("is idempotent in both directions", () => {
const raw = rawWith({ force: false, custom: "keep" });
expect(setSubagentForce(raw, true)).toEqual(
setSubagentForce(setSubagentForce(raw, true), true)
);
expect(setSubagentForce(raw, false)).toEqual(
setSubagentForce(setSubagentForce(raw, false), false)
);
});
});
// ---------------------------------------------------------------------------
// validateSubagentPool — mirror of the 6 engine rules
// ---------------------------------------------------------------------------
describe("validateSubagentPool", () => {
const aliases = ["kimi-k1", "kimi-k2", "kimi-k3"];
const pool = (p: Partial<SubagentModelPool>): SubagentModelPool => ({
models: {},
force: false,
...p,
});
it("accepts a valid pool", () => {
expect(
validateSubagentPool(
pool({
defaultModel: "kimi-k2",
models: { "kimi-k2": "K2", "kimi-k3": "K3" },
}),
aliases
)
).toEqual([]);
});
it("accepts the implicit single-entry form when the model resolves", () => {
expect(validateSubagentPool(pool({ model: "kimi-k2" }), aliases)).toEqual([]);
});
it("accepts force with a model fallback when no pool table exists", () => {
expect(
validateSubagentPool(pool({ force: true, model: "kimi-k2" }), aliases)
).toEqual([]);
});
it("flags `primary` as a reserved pool key", () => {
const byDefault = validateSubagentPool(pool({ defaultModel: "primary" }), aliases);
expect(byDefault).toContainEqual({
key: "primaryReserved",
params: { alias: "primary" },
});
const byEntry = validateSubagentPool(
pool({ defaultModel: "kimi-k1", models: { primary: "" } }),
aliases
);
expect(byEntry).toContainEqual({
key: "primaryReserved",
params: { alias: "primary" },
});
});
it("requires `default_model` when the models table exists", () => {
// Strict mirror of the engine: a `model` fallback does not satisfy the
// `default_model` requirement once a `models` table is present.
expect(
validateSubagentPool(
pool({ model: "kimi-k2", models: { "kimi-k2": "K2" } }),
aliases
)
).toEqual([{ key: "defaultRequired" }]);
});
it("flags a default that is not a key of the pool table", () => {
const errors = validateSubagentPool(
pool({ defaultModel: "kimi-k3", models: { "kimi-k2": "K2" } }),
aliases
);
expect(errors).toContainEqual({
key: "defaultNotInPool",
params: { alias: "kimi-k3" },
});
});
it("flags pool keys that do not resolve in the [models] registry", () => {
const errors = validateSubagentPool(
pool({ defaultModel: "kimi-k2", models: { "kimi-k2": "K2", ghost: "?" } }),
aliases
);
expect(errors).toContainEqual({
key: "aliasNotInModels",
params: { alias: "ghost" },
});
// the implicit single-entry default is checked against the registry too
const implicit = validateSubagentPool(pool({ model: "ghost" }), aliases);
expect(implicit).toContainEqual({
key: "aliasNotInModels",
params: { alias: "ghost" },
});
});
it("flags force without any default", () => {
expect(validateSubagentPool(pool({ force: true }), aliases)).toEqual([
{ key: "forceRequiresDefault" },
]);
});
it("flags force coexisting with the models table", () => {
const errors = validateSubagentPool(
pool({ force: true, defaultModel: "kimi-k2", models: { "kimi-k2": "K2" } }),
aliases
);
expect(errors).toContainEqual({ key: "forceExcludesModels" });
});
});
+430
View File
@@ -0,0 +1,430 @@
import type { ExperimentalEnvStatus, SecondaryModelConfig } from "../types";
/**
* Helpers for the `[experimental]` and `[secondary_model]` sections of the
* Kimi Code config.toml. Both live in `config.raw_other` (the pass-through
* bucket for unknown top-level TOML sections), so these helpers read/write
* that JSON object directly.
*/
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function isTruthyEnv(value: string | undefined): boolean {
if (!value) return false;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
// ---------------------------------------------------------------------------
// [experimental] — experimental feature flags
// ---------------------------------------------------------------------------
export interface ExperimentalFlagDef {
/** Flag id as stored in config.toml `[experimental]` (e.g. "secondary-model"). */
id: string;
/** Single-feature env var that can force the flag (locks the UI toggle). */
envVar: string;
}
/** Known experimental flags (Kimi Code v1 + v2 registries, merged). */
export const EXPERIMENTAL_FLAGS: ExperimentalFlagDef[] = [
{ id: "secondary-model", envVar: "KIMI_CODE_EXPERIMENTAL_SECONDARY_MODEL" },
{ id: "tool-select", envVar: "KIMI_CODE_EXPERIMENTAL_TOOL_SELECT" },
{ id: "acp-v2", envVar: "KIMI_CODE_EXPERIMENTAL_ACP_V2" },
{
id: "persistence_minidb_readmodel",
envVar: "KIMI_CODE_EXPERIMENTAL_PERSISTENCE_MINIDB_READMODEL",
},
];
export const EXPERIMENTAL_MASTER_ENV = "KIMI_CODE_EXPERIMENTAL_FLAG";
/** Whether the master env var is set to a truthy value (locks every flag on). */
export function isMasterEnvOn(env: ExperimentalEnvStatus | null): boolean {
return isTruthyEnv(env?.[EXPERIMENTAL_MASTER_ENV]);
}
/** Whether a flag's value is overridden by its env var (set & non-empty),
* locking the config toggle. Kimi Code lets the env var force the flag on
* *or* off, so a set env var locks regardless of its truthiness. */
export function isFlagLockedByEnv(
env: ExperimentalEnvStatus | null,
flag: ExperimentalFlagDef
): boolean {
return env !== null && flag.envVar in env;
}
/** The value a locked flag is forced to by its env var. */
export function forcedEnvValue(
env: ExperimentalEnvStatus | null,
flag: ExperimentalFlagDef
): boolean {
return isTruthyEnv(env?.[flag.envVar]);
}
/** Read `[experimental]` from raw_other: `{ flagId: boolean }`. */
export function getExperimentalFlags(rawOther: unknown): Record<string, boolean> {
const section = asRecord(rawOther)["experimental"];
const flags = asRecord(section);
const out: Record<string, boolean> = {};
for (const [k, v] of Object.entries(flags)) {
out[k] = v === true;
}
return out;
}
/** Set one flag in `[experimental]`. Removing all flags drops the section. */
export function setExperimentalFlag(
rawOther: unknown,
id: string,
enabled: boolean
): unknown {
const root = { ...asRecord(rawOther) };
const flags = { ...getExperimentalFlags(rawOther) };
if (enabled) {
flags[id] = true;
} else {
delete flags[id];
}
if (Object.keys(flags).length > 0) {
root.experimental = flags;
} else {
delete root.experimental;
}
return root;
}
// ---------------------------------------------------------------------------
// [secondary_model] — subagent model pool
// ---------------------------------------------------------------------------
/**
* Parsed subagent model pool (`[secondary_model]` v2 keys). The currently
* effective default is `defaultModel ?? model` (v2 pool key first, legacy v1
* recipe key as fallback).
*/
export interface SubagentModelPool {
/** v2 pool default (`default_model`). */
defaultModel?: string;
/** Legacy v1 recipe key (`model`), kept in sync with `defaultModel`. */
model?: string;
/** `[models]` table (alias → description); non-string values dropped. */
models: Record<string, string>;
/** Force subagents onto the default alias. */
force: boolean;
}
/** Known v1 patch fields, dropped when re-picking without a pool so stale
* patches are cleaned up. */
const PATCH_FIELDS: ReadonlySet<string> = new Set([
"default_effort",
"max_output_size",
"max_context_size",
]);
/** Read `[secondary_model]` from raw_other; `{}` when absent. */
export function getSecondaryModel(rawOther: unknown): SecondaryModelConfig {
const section = asRecord(rawOther)["secondary_model"];
const cfg = asRecord(section);
const out: SecondaryModelConfig = {};
if (typeof cfg.default_model === "string" && cfg.default_model !== "")
out.default_model = cfg.default_model;
if (typeof cfg.model === "string" && cfg.model !== "") out.model = cfg.model;
const models = asRecord(cfg.models);
const pool: Record<string, string> = {};
for (const [k, v] of Object.entries(models)) {
if (typeof v === "string") pool[k] = v;
}
if (Object.keys(pool).length > 0) out.models = pool;
if (cfg.force === true) out.force = true;
if (typeof cfg.default_effort === "string" && cfg.default_effort !== "")
out.default_effort = cfg.default_effort;
if (typeof cfg.max_output_size === "number" && cfg.max_output_size > 0)
out.max_output_size = cfg.max_output_size;
if (typeof cfg.max_context_size === "number" && cfg.max_context_size > 0)
out.max_context_size = cfg.max_context_size;
return out;
}
/** Read the v2 subagent model pool from raw_other; `undefined` when there is
* no `[secondary_model]` section or it is empty. The effective default is
* `defaultModel ?? model`. */
export function getSubagentModelPool(
rawOther: unknown
): SubagentModelPool | undefined {
const section = asRecord(asRecord(rawOther)["secondary_model"]);
if (Object.keys(section).length === 0) return undefined;
const models: Record<string, string> = {};
for (const [k, v] of Object.entries(asRecord(section["models"]))) {
if (typeof v === "string") models[k] = v;
}
const out: SubagentModelPool = { models, force: section["force"] === true };
if (typeof section["default_model"] === "string" && section["default_model"] !== "")
out.defaultModel = section["default_model"];
if (typeof section["model"] === "string" && section["model"] !== "")
out.model = section["model"];
return out;
}
/**
* Write `[secondary_model]` picking the given alias as the subagent model.
*
* Pool-aware: when a pool exists (`models` table or `default_model` present)
* the alias becomes the v2 default (added to the `models` table with an empty
* description when missing) and the legacy `model` key is synced; the rest of
* the section — `force`, patch fields, unknown fields — is preserved. This
* keeps usage records keyed on the real model alias instead of the
* synthesized `__secondary__` derived entry.
*
* Without a pool the legacy single-model form is written: only `model`, with
* the known patch fields (`default_effort`, `max_output_size`,
* `max_context_size`) dropped so stale patches are cleaned up when the model
* is re-picked; unknown fields are preserved.
*/
export function setSecondaryModelOnly(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
const hasPool =
section["models"] !== undefined || section["default_model"] !== undefined;
if (hasPool) {
for (const [k, v] of Object.entries(section)) next[k] = v;
next.default_model = alias;
next.model = alias;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
if (!(alias in models)) models[alias] = "";
next.models = models;
} else {
for (const [k, v] of Object.entries(section)) {
if (!PATCH_FIELDS.has(k)) next[k] = v;
}
next.model = alias;
}
root.secondary_model = next;
return root;
}
/**
* Rebuild the subagent model pool atomically. `default_model` and `model` are
* written with the same value — the effective default, `defaultModel ?? model`
* — plus the `models` table and `force`; unknown fields in the section are
* preserved. An empty `models` table is omitted: the engine requires
* `default_model` to be a key of the table, so an empty table can never be
* valid, and omitting it keeps the implicit single-entry form.
*/
export function setSubagentModelPool(
rawOther: unknown,
pool: SubagentModelPool
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const effective = pool.defaultModel ?? pool.model;
if (effective) {
next.default_model = effective;
next.model = effective;
} else {
delete next.default_model;
delete next.model;
}
if (Object.keys(pool.models).length > 0) {
next.models = { ...pool.models };
} else {
delete next.models;
}
next.force = pool.force === true;
root.secondary_model = next;
return root;
}
/** Add or update one alias in the pool `models` table. The rest of the
* section (default, force, unknown fields) is preserved untouched. */
export function upsertSubagentPoolEntry(
rawOther: unknown,
alias: string,
description: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
models[alias] = description;
next.models = models;
root.secondary_model = next;
return root;
}
/**
* Remove one alias from the pool `models` table. If it was the default, the
* default falls back to the first remaining key (`default_model` and `model`
* are both synced). Removing the last entry drops the `models` table and
* leaves `default_model`/`model` in place — the implicit single-entry pool.
*/
export function removeSubagentPoolEntry(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) {
if (k !== alias) models[k] = v;
}
const remaining = Object.keys(models);
if (remaining.length === 0) {
delete next.models;
} else {
next.models = models;
if (next.default_model === alias) {
next.default_model = remaining[0];
next.model = remaining[0];
}
}
root.secondary_model = next;
return root;
}
/** Set the pool default alias, syncing `default_model` and `model`; the alias
* is added to the `models` table with an empty description when missing. */
export function setSubagentDefault(
rawOther: unknown,
alias: string
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) next[k] = v;
const models: Record<string, unknown> = {};
for (const [k, v] of Object.entries(asRecord(next.models))) models[k] = v;
if (!(alias in models)) models[alias] = "";
next.models = models;
next.default_model = alias;
next.model = alias;
root.secondary_model = next;
return root;
}
/**
* Set the `force` flag. Turning force on drops the `models` table — `force`
* and the pool table are mutually exclusive per the engine (the implicit
* `default_model`/`model` form stays); turning it off leaves the table
* untouched. Everything else in the section is preserved.
*/
export function setSubagentForce(
rawOther: unknown,
force: boolean
): unknown {
const root = { ...asRecord(rawOther) };
const section = asRecord(asRecord(rawOther)["secondary_model"]);
const next: Record<string, unknown> = {};
for (const [k, v] of Object.entries(section)) {
if (force && k === "models") continue;
next[k] = v;
}
next.force = force;
root.secondary_model = next;
return root;
}
/** Keys of validation errors, mirroring the kimi-code engine checks. */
export type ValidationErrorKey =
| "primaryReserved"
| "defaultRequired"
| "defaultNotInPool"
| "aliasNotInModels"
| "forceRequiresDefault"
| "forceExcludesModels";
/** A pool validation error; `params` carries the offending alias. */
export interface PoolValidationError {
key: ValidationErrorKey;
params?: Record<string, string>;
}
/**
* Mirror the kimi-code engine validation for the subagent model pool
* (violations fail the kimi session with CONFIG_INVALID):
* 1. `"primary"` is reserved and cannot be a pool key;
* 2. a `models` table requires `default_model`;
* 3. `default_model` must be a key of the `models` table;
* 4. every pool key must resolve in the top-level `[models]` registry;
* 5. `force` requires a default (`default_model` or the `model` fallback);
* 6. `force` and a `models` table are mutually exclusive.
*
* `availableAliases` is the set of top-level `[models]` aliases. A pool
* without a `models` table is the implicit single-entry form: only the
* effective default is checked against the registry.
*/
export function validateSubagentPool(
pool: SubagentModelPool,
availableAliases: string[]
): PoolValidationError[] {
const errors: PoolValidationError[] = [];
const { defaultModel, model, models, force } = pool;
const effectiveDefault = defaultModel ?? model;
const poolKeys = Object.keys(models);
const hasPoolTable = poolKeys.length > 0;
const registry = new Set(availableAliases);
const aliasError = (alias: string) => {
if (alias !== "primary" && !registry.has(alias)) {
errors.push({ key: "aliasNotInModels", params: { alias } });
}
};
// Rule 1: "primary" is reserved as a pool key.
if (effectiveDefault === "primary") {
errors.push({ key: "primaryReserved", params: { alias: "primary" } });
}
for (const key of poolKeys) {
if (key === "primary") {
errors.push({ key: "primaryReserved", params: { alias: key } });
}
}
// Rule 2: a `models` table requires `default_model`.
if (hasPoolTable && !defaultModel) {
errors.push({ key: "defaultRequired" });
}
// Rule 3: `default_model` must be a key of the `models` table.
if (hasPoolTable && defaultModel && !(defaultModel in models)) {
errors.push({ key: "defaultNotInPool", params: { alias: defaultModel } });
}
// Rule 4: every pool key must resolve in the `[models]` registry.
for (const key of poolKeys) aliasError(key);
if (!hasPoolTable && effectiveDefault) aliasError(effectiveDefault);
// Rule 5: `force` requires a default (`default_model` or `model` fallback).
if (force && !effectiveDefault) {
errors.push({ key: "forceRequiresDefault" });
}
// Rule 6: `force` and a `models` table are mutually exclusive.
if (force && hasPoolTable) {
errors.push({ key: "forceExcludesModels" });
}
return errors;
}
/** Remove `[secondary_model]` entirely (the "not configured" option). */
export function clearSecondaryModel(rawOther: unknown): unknown {
const root = { ...asRecord(rawOther) };
delete root.secondary_model;
return root;
}
+6 -1
View File
@@ -13,7 +13,8 @@ export interface TotalsRow {
export interface DailyRow extends TotalsRow {
date: string;
byModel: Record<string, number>;
/** Per-model structured breakdown (tokens / requests / cost / cacheHitRate). */
byModel: Record<string, TotalsRow>;
byProvider: Record<string, number>;
byProviderModel: Record<string, Record<string, number>>;
}
@@ -24,6 +25,8 @@ export interface ModelRow extends TotalsRow {
modelResolved: string;
priceId: string;
costEstimated: boolean;
/** True when any record in this row came from a subagent (secondary-model) request. */
isSecondary: boolean;
}
export interface RecentRow {
@@ -40,6 +43,8 @@ export interface RecentRow {
costEstimated: boolean;
priceId: string;
fromEnv: boolean;
/** True when this request came from a subagent (secondary-model) call. */
isSecondary: boolean;
}
export interface RangeStats {
+36
View File
@@ -97,6 +97,11 @@ export interface ThinkingConfig {
}
export interface LoopControlConfig {
/** v2 engine key (kimi-code 0.33+): `max_retries_per_step` was renamed. */
max_attempts_per_step?: number;
/** v2 engine key (kimi-code 0.33+): `max_steps_per_run` was renamed. */
max_steps_per_turn?: number;
/** Legacy v1 key — written in sync so KIMI_CODE_LEGACY_FLAG=1 still works. */
max_retries_per_step?: number;
reserved_context_size?: number;
}
@@ -127,3 +132,34 @@ export interface AgentSettings {
permission?: { rules?: PermissionRule[] };
hooks?: Hook[];
}
/**
* Kimi Code `[secondary_model]` section of config.toml: the subagent model
* pool (experimental feature).
*
* v2 engine (default) reads the pool keys: `default_model` + `[models]` table
* (alias → description) + `force`. `model` is ignored by the v2 validator when
* pool keys are present, but is kept in sync with `default_model` so the v1
* engine (KIMI_CODE_LEGACY_FLAG=1) resolves the same alias.
*
* v1 engine reads only the recipe key `model` plus the patch fields; pool keys
* are ignored by it. Pool resolution order: `models` table → `default_model` →
* `model`.
*/
export interface SecondaryModelConfig {
/** v2: default subagent alias in the pool (a key of `models`). */
default_model?: string;
/** v2: alias → description table for the subagent model pool. */
models?: Record<string, string>;
/** v2: force subagents onto the default alias (excludes `models`). */
force?: boolean;
/** Legacy v1 recipe key — written in sync so KIMI_CODE_LEGACY_FLAG=1 works. */
model?: string;
/** v1 patch fields, applied on top of the referenced entry (v1 only). */
default_effort?: string;
max_output_size?: number;
max_context_size?: number;
}
/** Values of experimental env vars that are currently set (non-empty). */
export type ExperimentalEnvStatus = Record<string, string>;
+4
View File
@@ -1,3 +1,4 @@
/// <reference types="vitest" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
@@ -10,4 +11,7 @@ export default defineConfig(async () => ({
watch: { ignored: ["**/src-tauri/**"] },
},
envPrefix: ["VITE_"],
test: {
environment: "node",
},
}));
+10
View File
@@ -9,6 +9,7 @@
"version": "0.6.7",
"dependencies": {
"@fontsource/fira-code": "^5.3.0",
"@fontsource/geist": "^5.3.0",
"@fontsource/inter": "^5.3.0",
"@phosphor-icons/react": "^2.1.10",
"react": "^18.3.1",
@@ -722,6 +723,15 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/geist": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/geist/-/geist-5.3.0.tgz",
"integrity": "sha512-u03ftlfVwb05uijq2jGDJ03/HKGqMKaNFk7KOhkpBUex8+BhrAOfMs/XciJ2UUNUX9fEsZbZQld/RWMA2oFU7g==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.3.0.tgz",
+1
View File
@@ -10,6 +10,7 @@
},
"dependencies": {
"@fontsource/fira-code": "^5.3.0",
"@fontsource/geist": "^5.3.0",
"@fontsource/inter": "^5.3.0",
"@phosphor-icons/react": "^2.1.10",
"react": "^18.3.1",
+70 -5
View File
@@ -1,3 +1,4 @@
import { useEffect, useState } from "react";
import { recommendLinks } from "../data/recommendLinks";
import { useLang } from "../i18n";
import { asset } from "../lib/asset";
@@ -12,14 +13,68 @@ const logoFor: Record<string, string> = {
"基元律动": "logos/tokenrhythm.svg",
};
// 下载统计:只拉 GitHub(公开 API 带 CORS),镜像站 Gitea 未开 CORS 不计入。
const STATS_URL =
"https://api.github.com/repos/billowliu2/KimiSwitch/releases?per_page=100";
const STATS_CACHE_KEY = "kimi-switch-downloads";
const STATS_CACHE_TTL = 60 * 60 * 1000; // 1 hour
/** GitHub Release 全部资产 download_count 之和;拉取失败返回 null(不展示)。 */
function useDownloadCount(): number | null {
const [count, setCount] = useState<number | null>(null);
useEffect(() => {
let cancelled = false;
try {
const cached = localStorage.getItem(STATS_CACHE_KEY);
if (cached) {
const { ts, total } = JSON.parse(cached) as { ts: number; total: number };
if (Date.now() - ts < STATS_CACHE_TTL) {
setCount(total);
return;
}
}
} catch {
/* ignore corrupt cache */
}
fetch(STATS_URL)
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
.then((releases: Array<{ assets?: Array<{ download_count?: number }> }>) => {
if (cancelled) return;
const total = (releases ?? []).reduce(
(sum, rel) =>
sum +
(rel.assets ?? []).reduce((s, a) => s + (a.download_count ?? 0), 0),
0
);
setCount(total);
try {
localStorage.setItem(
STATS_CACHE_KEY,
JSON.stringify({ ts: Date.now(), total })
);
} catch {
/* ignore quota errors */
}
})
.catch(() => {
/* 拉取失败则不显示 */
});
return () => {
cancelled = true;
};
}, []);
return count;
}
export default function Footer() {
const { t } = useLang();
const downloadCount = useDownloadCount();
return (
<footer className="border-t border-border py-12">
<div className="container-page space-y-8">
{/* 推荐链接 */}
<div>
<h3 className="mb-4 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
<h3 className="mb-4 text-sm font-semibold text-muted-foreground">
{t.footer.recommend}
</h3>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
@@ -32,9 +87,10 @@ export default function Footer() {
href={link.url}
target="_blank"
rel="noreferrer"
className="group flex items-start gap-3 rounded-xl border border-border bg-card p-4 transition-all hover:-translate-y-0.5 hover:border-primary/50"
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"
style={{ boxShadow: "var(--shadow-soft)" }}
>
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border bg-white">
<div className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-border bg-white">
{logo ? (
<img
src={asset(logo)}
@@ -48,11 +104,11 @@ export default function Footer() {
)}
</div>
<div className="min-w-0 flex-1">
<div className="font-semibold group-hover:text-primary">
<div className="font-semibold tracking-tight group-hover:text-primary">
{link.name}
</div>
{text && (
<p className="mt-1 line-clamp-3 text-xs text-muted-foreground">
<p className="mt-1 line-clamp-3 text-xs leading-relaxed text-muted-foreground">
{text}
</p>
)}
@@ -85,6 +141,15 @@ export default function Footer() {
{t.footer.mirror}
</a>{" "}
· MIT License
{downloadCount !== null && (
<>
{" "}
·{" "}
<span className="opacity-60">
{t.footer.downloads.replace("{n}", downloadCount.toLocaleString())}
</span>
</>
)}
</div>
<div className="text-xs opacity-80">
{t.footer.creditBefore}
+1 -1
View File
@@ -11,7 +11,7 @@ export default function Nav() {
{ to: "/download", label: t.nav.download },
];
return (
<header className="sticky top-0 z-40 border-b border-border bg-background/80 backdrop-blur">
<header className="sticky top-0 z-40 border-b border-border bg-background/70 backdrop-blur-md">
<div className="container-page flex h-14 items-center justify-between gap-4">
<NavLink
to="/"
+2 -2
View File
@@ -25,12 +25,12 @@ export default function SectionShell({ id, title, subtitle, children }: SectionS
<div className="mb-12 max-w-3xl">
<h2
id={`${id}-title`}
className="text-3xl font-bold tracking-tight md:text-4xl"
className="text-3xl font-bold tracking-[-0.03em] md:text-4xl"
>
{title}
</h2>
{subtitle && (
<p className="mt-3 text-base text-muted-foreground">{subtitle}</p>
<p className="mt-3 text-base leading-relaxed text-muted-foreground">{subtitle}</p>
)}
</div>
{children}
+135 -10
View File
@@ -16,10 +16,10 @@ const zh = {
performance: "性能",
changelog: "更新日志",
download: "下载",
downloadBtn: "下载 v0.6.9",
downloadBtn: "下载 v0.7.4",
},
hero: {
badge: "v0.6.9 · 开源 MIT · Windows / macOS / Linux",
badge: "v0.7.4 · 开源 MIT · Windows / macOS / Linux",
titleBefore: "统一管理你的",
titleAccent: "AI 供应商",
titleAfter: "",
@@ -140,6 +140,63 @@ const zh = {
syncedNote: "数据已同步 GitHub Releases",
fallbackNote: "内置版本记录",
entries: [
{
version: "v0.7.4",
date: "2026-08-09",
items: [
"仪表盘热力图双击弹窗:双击方块查看当日模型用量分布,每种模型展示 Token / 请求次数 / 费用 / 命中率",
"后端 by_model 数据结构升级:从纯 token 数升级为结构化对象,柱状图双击弹窗也同步展示全量指标",
"范围外日期不可双击、无放大效果",
],
},
{
version: "v0.7.3",
date: "2026-08-07",
items: [
"高级设置新增 Kimi Code WebUI 应用内嵌窗口:新版 Web 界面以独立顶层窗口打开(单例、可缩放、居中),不再跳转外部浏览器",
"WebUI 两个入口并存:应用内独立窗口 / 系统浏览器(复用已运行的 kimi web 服务器,不重复拉起)",
"服务器进程自动管理:自己启动的服务器随窗口关闭/应用退出清理,不留残留;窗口创建失败不再泄漏进程",
"最小化窗口再次打开可恢复;发布说明文案同步更新",
],
},
{
version: "v0.7.2",
date: "2026-08-07",
items: [
"「子代理设置」升级为「高级设置」:聚合子代理模型指定、实验功能开关与 WebUI 快捷入口",
"新增 Kimi Code WebUI 快捷打开:高级设置页可将新版 Web 界面以独立窗口在应用内打开,也可在系统浏览器打开(kimi-code 0.33+)",
"子代理模型指定(实验功能):设置中为子代理选择次主力模型,子代理不再默认继承主模型",
"实验开关改为滑动开关,修复开启态因样式缺失而不可见的问题",
"兼容 kimi-code 0.33+(v2 引擎):循环控制改用新键 max_attempts_per_step,旧配置自动迁移",
"models.dev 模型列表与价格数据同步更新",
"官网企业版视觉升级;出品公司标识统一为 codingplan.site",
"macOS 安装优化:Release 附带 install-macos.sh 一键脚本,自动清除下载隔离,免去手动右键打开",
],
},
{
version: "v0.7.1",
date: "2026-08-05",
items: [
"实验功能设置新增「子代理模型(次主力模型)」配置:选择后子代理绑定该模型,不再继承主模型",
"仪表盘用量统计识别子代理请求(__secondary__)独立展示,并缓存次主力模型定价",
"自定义网关模型按官方同名模型跨 provider 匹配价格,不再落入兜底估算",
],
},
{
version: "v0.7.0",
date: "2026-08-02",
items: [
"订阅套餐模型计价修正:零价条目按官方付费模型计价(zhipuai-coding-plan/glm-5.2 按 zhipuai/glm-5.2 牌价)",
"-highspeed / -free 派生变体自动回退到基础模型价格",
"Kimi For Coding 套餐无牌价时按旗舰模型 kimi-k3 价格估算用量",
"设置页:识图(image_in)能力可手动编辑,原生多模态模型不再提示 kimi-eyes 插件",
"修复仅单个套餐档位(如 5 小时)时用量卡片不显示的问题",
"kimi usages 响应异常时透出原始返回,便于对照接口排查",
"models.dev 价格快照同步",
"关于页新增官方网站链接",
"设置-关于页新增 Kimi Eyes 识图插件站链接",
],
},
{
version: "v0.6.9",
date: "2026-08-01",
@@ -149,6 +206,15 @@ const zh = {
"仪表盘性能再优化:价格解析记忆化缓存,扫描从秒级降到百毫秒级;右上角新增加载耗时/数据量跟踪",
],
},
{
version: "v0.6.7",
date: "2026-08-01",
items: [
"应用内置 Kimi 授权登录(Device Code Flow,等同 kimi login):浏览器授权即用,无需命令行",
"授权后凭据自动写入,15 分钟过期自动续期,用量查询直接可用",
"修复外链打开问题:授权页 / 设置页超链接统一走 Rust 侧 opener 命令(更可靠)",
],
},
{
version: "v0.6.8",
date: "2026-08-01",
@@ -245,7 +311,7 @@ const zh = {
},
download: {
title: "下载 Kimi Switch",
subtitle: "当前版本 v0.6.9 · Windows / macOS / Linux 三平台已发布",
subtitle: "当前版本 v0.7.4 · Windows / macOS / Linux 三平台已发布",
autoUpdate: "应用内置自动检测更新,新版本发布后在设置页一键升级。",
ready: "已发布",
wip: "开发中",
@@ -253,7 +319,7 @@ const zh = {
mirrorBtn: "镜像下载",
items: [
{ id: "windows", name: "Windows", ready: true, note: ".msi 安装包,系统托盘常驻" },
{ id: "macos", name: "macOS", ready: true, note: ".dmg 安装包(Apple Silicon),未签名需右键打开" },
{ id: "macos", name: "macOS", ready: true, note: ".dmg 安装包(Apple Silicon),未签名:下载 install-macos.sh 后运行 bash install-macos.sh 一键安装" },
{ id: "linux", name: "Linux", ready: true, note: ".deb / .AppImage / .rpm 三格式" },
],
},
@@ -288,6 +354,7 @@ const zh = {
footer: {
recommend: "推荐供应商",
mirror: "国内镜像",
downloads: "GitHub 累计下载 {n} 次",
creditBefore: "仪表盘与会话管理功能基于 ",
creditAfter: " (MIT, © JochenYang) 移植",
recommendText: {
@@ -295,7 +362,7 @@ const zh = {
"智谱 GLM":
"通过我的邀请链接注册 BigModel.cn,即可获得 2000 万 Tokens 大礼包,畅享新一代旗舰模型 GLM-5.2",
DeepSeek: "",
OpenCodeGo: "",
OpenCodeGo: "好友订阅后,您可获得 $5,对方也可获得 $5。",
MiniMax:
"MiniMax Token Plan:订阅套餐解锁最新模型,好友订阅享 9 折 + Builder 权益,邀请人得 10% 返利",
基元律动: "",
@@ -313,10 +380,10 @@ const en: Dict = {
performance: "Performance",
changelog: "Changelog",
download: "Download",
downloadBtn: "Download v0.6.9",
downloadBtn: "Download v0.7.4",
},
hero: {
badge: "v0.6.9 · Open source MIT · Windows / macOS / Linux",
badge: "v0.7.4 · Open source MIT · Windows / macOS / Linux",
titleBefore: "One app for all your ",
titleAccent: "AI providers",
titleAfter: "",
@@ -437,6 +504,63 @@ const en: Dict = {
syncedNote: "Synced from GitHub Releases",
fallbackNote: "Built-in release notes",
entries: [
{
version: "v0.7.4",
date: "2026-08-09",
items: [
"Dashboard heatmap double-click: click any heatmap cell to see per-model breakdown with Token / requests / cost / cache hit rate",
"Backend by_model data structure upgraded from plain token counts to structured objects; bar chart double-click modal also shows full metrics",
"Out-of-range dates are not double-clickable and have no hover zoom",
],
},
{
version: "v0.7.3",
date: "2026-08-07",
items: [
"Advanced Settings gains an embedded Kimi Code WebUI window: the new Web UI opens in an independent top-level window (singleton, resizable, centered) instead of the external browser",
"Two WebUI entries coexist: in-app independent window / system browser (reuses an already-running kimi web server, no duplicate spawn)",
"Server process is managed automatically: servers we start are cleaned up when the window closes or the app exits; a failed window creation no longer leaks the process",
"Re-opening focuses and restores a minimized window; release notes wording synced",
],
},
{
version: "v0.7.2",
date: "2026-08-07",
items: [
"Subagent settings upgraded to an Advanced Settings page: subagent model assignment, experimental toggles and a WebUI quick launcher",
"New Kimi Code WebUI quick open: open the new Web UI in an independent in-app window from Advanced Settings, or in your system browser (kimi-code 0.33+)",
"Subagent model assignment (experimental): pick a secondary model for subagents so they no longer inherit the main model by default",
"Experiment toggle converted to a sliding switch, fixing the invisible enabled state",
"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",
],
},
{
version: "v0.7.1",
date: "2026-08-05",
items: [
"Experimental settings gain a secondary-model picker for subagents, decoupling them from the main model",
"Dashboard usage stats identify subagent requests (__secondary__) and show them separately with cached secondary-model pricing",
"Custom gateway models match prices against the same-named official model across providers",
],
},
{
version: "v0.7.0",
date: "2026-08-02",
items: [
"Plan-entry pricing fix: zero-price plan listings bill at the official priced model (zhipuai-coding-plan/glm-5.2 → zhipuai/glm-5.2)",
"-highspeed / -free derived variants fall back to the base model price",
"Kimi For Coding (no list price) estimates usage at the flagship kimi-k3 rate",
"Settings: image_in capability is now manually editable; native multimodal models no longer show the kimi-eyes plugin hint",
"Fix single-tier plans (e.g. 5-hour only) showing no usage card",
"kimi usages failure now exposes the raw response for easier debugging",
"models.dev price snapshot sync",
"About page gains an official website link",
"Settings-About page gains a Kimi Eyes plugin site link",
],
},
{
version: "v0.6.9",
date: "2026-08-01",
@@ -550,7 +674,7 @@ const en: Dict = {
},
download: {
title: "Download Kimi Switch",
subtitle: "Current version v0.6.9 · Windows, macOS and Linux now released",
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.",
ready: "Available",
wip: "In development",
@@ -558,7 +682,7 @@ const en: Dict = {
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 - right-click to open" },
{ 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: "linux", name: "Linux", ready: true, note: ".deb / .AppImage / .rpm" },
],
},
@@ -593,6 +717,7 @@ const en: Dict = {
footer: {
recommend: "Recommended Providers",
mirror: "China mirror",
downloads: "Total GitHub downloads: {n}",
creditBefore: "Dashboard & session management adapted from ",
creditAfter: " (MIT, © JochenYang)",
recommendText: {
@@ -600,7 +725,7 @@ const en: Dict = {
"智谱 GLM":
"Register on BigModel.cn via my invite link and get a 20M token gift pack for the new GLM-5.2 flagship",
DeepSeek: "",
OpenCodeGo: "",
OpenCodeGo: "When a friend subscribes, you get $5 and they get $5.",
MiniMax:
"MiniMax Token Plan: subscribe to unlock the latest models. Friends get 10% off, inviters get 10% rebate",
基元律动: "",
+53 -15
View File
@@ -1,8 +1,8 @@
@import "@fontsource/inter/400.css";
@import "@fontsource/inter/500.css";
@import "@fontsource/inter/600.css";
@import "@fontsource/inter/700.css";
@import "@fontsource/inter/800.css";
@import "@fontsource/geist/400.css";
@import "@fontsource/geist/500.css";
@import "@fontsource/geist/600.css";
@import "@fontsource/geist/700.css";
@import "@fontsource/geist/800.css";
@import "@fontsource/fira-code/400.css";
@import "@fontsource/fira-code/500.css";
@@ -26,6 +26,11 @@
--primary: 221 83% 53%;
--primary-foreground: 0 0% 100%;
--ring: 221 83% 53%;
/* 克制分层阴影(色相一致的 tinted shadow,非荧光发光) */
--shadow-soft: 0 1px 2px hsl(240 9% 11% / 0.05),
0 8px 24px hsl(240 9% 11% / 0.06);
--shadow-lift: 0 1px 2px hsl(240 9% 11% / 0.05),
0 12px 36px hsl(240 9% 11% / 0.1);
}
@media (prefers-color-scheme: dark) {
@@ -42,6 +47,10 @@
--primary: 217 91% 60%;
--primary-foreground: 0 0% 100%;
--ring: 217 91% 60%;
--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),
0 12px 36px hsl(222 47% 2% / 0.55);
}
}
@@ -59,8 +68,8 @@
z-index: 0;
pointer-events: none;
background-image:
linear-gradient(to right, hsl(var(--primary) / 0.05) 1px, transparent 1px),
linear-gradient(to bottom, hsl(var(--primary) / 0.05) 1px, transparent 1px);
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%);
}
@@ -68,6 +77,21 @@
position: relative;
z-index: 1;
}
/* 选中色与键盘焦点(无障碍) */
::selection {
background: hsl(var(--primary) / 0.16);
}
:focus-visible {
outline: 2px solid hsl(var(--ring));
outline-offset: 2px;
}
/* 展示标题:更紧字距 + 防孤词 */
h1,
h2 {
text-wrap: balance;
letter-spacing: -0.02em;
}
}
@layer components {
@@ -75,27 +99,41 @@
@apply mx-auto w-full max-w-6xl px-6;
}
.btn {
@apply inline-flex items-center justify-center gap-2 rounded-xl px-5 py-2.5 text-sm font-medium transition-colors;
@apply inline-flex items-center justify-center gap-2 rounded-xl px-5 py-2.5 text-sm font-medium transition-all duration-200;
}
.btn-primary {
@apply btn bg-primary text-primary-foreground hover:opacity-90;
box-shadow: 0 0 20px hsl(var(--primary) / 0.35);
@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);
}
.btn-ghost {
@apply btn border border-border text-foreground hover:bg-accent;
@apply btn border border-border bg-card/60 text-foreground hover:border-foreground/25 hover:bg-accent active:scale-[0.98];
}
.card {
@apply rounded-xl border border-border bg-card p-6 transition-shadow;
@apply rounded-2xl border border-border bg-card p-6;
box-shadow: var(--shadow-soft);
transition:
box-shadow 0.3s ease,
transform 0.3s ease,
border-color 0.3s ease;
}
.card:hover {
box-shadow: 0 0 28px hsl(var(--primary) / 0.12);
box-shadow: var(--shadow-lift);
}
/* 截图容器:限定最大宽高,避免撑满页面 */
.screenshot {
@apply overflow-hidden rounded-xl border border-border bg-muted;
box-shadow: 0 0 36px hsl(var(--primary) / 0.1);
@apply overflow-hidden rounded-2xl border border-border bg-muted;
box-shadow: var(--shadow-lift);
}
.screenshot > img {
@apply block h-auto w-full;
}
/* 图标容器:统一的蓝色徽标容器 */
.icon-chip {
@apply flex h-10 w-10 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary;
}
}
+9 -5
View File
@@ -10,20 +10,24 @@ export default function CTA() {
className="py-24"
>
<div className="container-page">
<div className="relative overflow-hidden rounded-xl border border-primary/25 bg-gradient-to-r from-primary/10 via-primary/5 to-violet-500/10 p-12 text-center md:p-16">
{/* 科技风光晕 */}
<div className="card relative overflow-hidden p-12 text-center md:p-16">
{/* 克制同色系光晕 + 顶部强调线(去紫,保持页面调性) */}
<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/15 blur-3xl"
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"
/>
<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-tight md:text-5xl"
className="text-3xl font-bold tracking-[-0.03em] md:text-5xl"
>
{t.cta.title}
</h2>
<p className="mt-4 text-base text-muted-foreground md:text-lg">
<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">
+37 -10
View File
@@ -18,12 +18,38 @@ function cacheKey(embedded: ChangelogEntry[]) {
return `kimi-switch-changelog-${embedded[0]?.version ?? "v1"}`;
}
/** Parse a GitHub release body into bullet items. */
/** Compare semantic versions like "v0.7.1" for descending order. */
function compareVersionsDesc(a: string, b: string): number {
const parse = (v: string) =>
v.replace(/^v/, "").split(".").map((n) => Number(n) || 0);
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
const da = pa[i] ?? 0;
const db = pb[i] ?? 0;
if (da !== db) return db - da;
}
return 0;
}
/** Parse a GitHub release body into bullet items, stripping markdown syntax
* and the release-template "Downloads by platform" section (changelog entries
* are about changes, not installers). */
function parseBody(body: string): string[] {
return body
.split("\n")
.map((l) => l.replace(/^\s*[-*]\s+/, "").trim())
.filter((l) => l.length > 0 && l !== "---");
const items: string[] = [];
for (const raw of body.split("\n")) {
const line = raw.replace(/^\s*[-*]\s+/, "").trim();
if (line.length === 0 || line === "---") continue;
// Drop the release template's download section and everything after it.
if (/downloads?\s+by\s+platform/i.test(line)) break;
const cleaned = line
.replace(/^#{1,6}\s+/, "") // markdown heading markers
.replace(/\*\*(.+?)\*\*/g, "$1") // bold
.replace(/`([^`]+)`/g, "$1") // inline code
.trim();
if (cleaned.length > 0) items.push(cleaned);
}
return items;
}
async function fetchReleases(): Promise<ChangelogEntry[]> {
@@ -94,12 +120,13 @@ export default function Changelog() {
}, []);
// 远端拉到的版本优先显示(含未翻译的新版本),内置列表补齐缺失版本。
// 合并后按版本倒序排序,避免未翻译版本被无脑塞到最前导致时间轴顺序错乱。
const entries: ChangelogEntry[] = [
...(remote ?? []).filter(
(r) => !embedded.some((e) => e.version === r.version),
),
...embedded,
];
].sort((a, b) => compareVersionsDesc(a.version, b.version));
return (
<SectionShell
@@ -107,16 +134,16 @@ export default function Changelog() {
title={t.changelog.title}
subtitle={t.changelog.subtitle}
>
<ol className="relative space-y-8 border-l border-border pl-8">
<ol className="relative space-y-10 border-l border-border pl-7">
{entries.map((e) => (
<li key={e.version} className="relative">
<span className="absolute -left-[37px] top-1.5 h-2.5 w-2.5 rounded-full bg-primary" />
<span className="absolute -left-[34px] top-[5px] h-3 w-3 rounded-full border-2 border-background bg-primary ring-4 ring-primary/10" />
<div className="flex flex-wrap items-baseline gap-3">
<h3 className="font-mono text-lg font-semibold">{e.version}</h3>
<h3 className="font-mono text-lg font-semibold tracking-tight">{e.version}</h3>
<time className="text-xs text-muted-foreground">{e.date}</time>
</div>
{e.items.length > 0 && (
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-muted-foreground">
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm leading-relaxed text-muted-foreground">
{e.items.map((item) => (
<li key={item}>{item}</li>
))}
+12 -10
View File
@@ -8,25 +8,27 @@ const icons: Record<string, Icon> = {
linux: LinuxLogo,
};
const VERSION = "0.6.9";
const VERSION = "0.7.4";
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, e.g. Kimi.Switch_0.6.9_x64_en-US.msi). */
* release workflow exactly — verified against the published v0.7.4 assets:
* tauri-bundler on CI produces `Kimi.Switch_…` (dots) on every platform). */
const assets: Record<string, { label: string; href: string }[]> = {
windows: [
{ label: "MSI", href: dl("Kimi.Switch_0.6.9_x64_en-US.msi") },
{ label: "MSI", href: dl("Kimi.Switch_0.7.4_x64_en-US.msi") },
{ label: "镜像", href: MIRROR_RELEASES },
],
macos: [
{ label: "Apple Silicon (.dmg)", href: dl("Kimi.Switch_0.6.9_aarch64.dmg") },
{ label: "Apple Silicon (.dmg)", href: dl("Kimi.Switch_0.7.4_aarch64.dmg") },
{ label: "安装脚本", href: dl("install-macos.sh") },
],
linux: [
{ label: ".deb", href: dl("Kimi.Switch_0.6.9_amd64.deb") },
{ label: ".AppImage", href: dl("Kimi.Switch_0.6.9_amd64.AppImage") },
{ label: ".rpm", href: dl("Kimi.Switch-0.6.9-1.x86_64.rpm") },
{ 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") },
],
};
@@ -45,14 +47,14 @@ export default function Download() {
return (
<div key={p.id} className="card flex flex-col">
<div className="mb-3 flex items-center justify-between">
<div className="flex h-10 w-10 items-center justify-center rounded-xl border border-primary/25 bg-primary/10 text-primary">
<div className="icon-chip">
<Icon className="h-5 w-5" weight="duotone" />
</div>
<span className="rounded-full border border-primary/25 bg-primary/10 px-2.5 py-0.5 text-xs font-medium text-primary">
<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>
</div>
<h3 className="mb-2 text-lg font-semibold">{p.name}</h3>
<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">
{links.map((l) => (
+2 -2
View File
@@ -59,10 +59,10 @@ export default function Features() {
/>
</div>
<div className="p-6">
<div className="mb-3 flex h-10 w-10 items-center justify-center rounded-xl border border-primary/25 bg-primary/10 text-primary">
<div className="icon-chip mb-3">
<Icon className="h-5 w-5" weight="duotone" />
</div>
<h3 className="mb-2 text-lg font-semibold">{f.title}</h3>
<h3 className="mb-2 text-lg font-semibold tracking-tight">{f.title}</h3>
<p className="text-sm leading-relaxed text-muted-foreground">
{f.desc}
</p>
+6 -6
View File
@@ -23,29 +23,29 @@ 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/15 blur-3xl"
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-violet-500/10 blur-3xl"
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)}>
<span className="inline-block rounded-full border border-primary/25 bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
<span className="inline-block rounded-full border border-primary/25 bg-primary/10 px-3 py-1 text-xs font-medium tracking-wide text-primary">
{t.hero.badge}
</span>
</div>
<h1
id="hero-title"
{...reveal(100, "mt-4 text-4xl font-bold tracking-tight md:text-5xl lg:text-6xl")}
{...reveal(100, "mt-5 text-4xl font-bold leading-[1.05] tracking-[-0.03em] md:text-5xl lg:text-6xl")}
>
{t.hero.titleBefore}
<br />
<span className="whitespace-nowrap bg-gradient-to-r from-blue-500 to-violet-500 bg-clip-text text-transparent">
<span className="whitespace-nowrap text-primary">
{t.hero.titleAccent}
</span>
{t.hero.titleAfter}
+1 -1
View File
@@ -65,7 +65,7 @@ function Counter({
const v = useCountUp(target, inView);
return (
<div ref={ref} className="card text-center">
<div className="font-mono text-4xl font-bold tracking-tight tabular-nums">
<div className="font-mono text-4xl font-bold tracking-[-0.03em] tabular-nums">
{v.toFixed(decimals)}
{suffix}
</div>
+2 -2
View File
@@ -21,10 +21,10 @@ export default function Privacy() {
const Icon = icons[it.id] ?? Database;
return (
<div key={it.id} className="card">
<div className="mb-3 flex h-10 w-10 items-center justify-center rounded-xl border border-primary/25 bg-primary/10 text-primary">
<div className="icon-chip mb-3">
<Icon className="h-5 w-5" weight="duotone" />
</div>
<h3 className="mb-2 text-lg font-semibold">{it.title}</h3>
<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>
+1 -1
View File
@@ -27,7 +27,7 @@ export default {
},
fontFamily: {
sans: [
"Inter",
"Geist",
"-apple-system",
"BlinkMacSystemFont",
'"Segoe UI"',