Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8aed04898c | ||
|
|
8b0daabd95 | ||
|
|
6e38bed092 | ||
|
|
6df9095ee8 | ||
|
|
d06fb41f48 | ||
|
|
69f9b8d603 | ||
|
|
2f75929fda | ||
|
|
a1c3f06bdf | ||
|
|
acde6d97c2 | ||
|
|
6cbaea7159 | ||
|
|
f0d5e27bb4 | ||
|
|
38a11666ac | ||
|
|
de132ffb3a | ||
|
|
a285d192eb | ||
|
|
127818a7c3 | ||
|
|
6bc9e4644e | ||
|
|
dfd41d12c0 | ||
|
|
615dfb54e0 | ||
|
|
8914b40bec | ||
|
|
4071930aff | ||
|
|
1b5cd0f416 |
No files matched your search
@@ -86,6 +86,6 @@ jobs:
|
|||||||
- **Linux**: `.deb` / `.AppImage` / `.rpm`
|
- **Linux**: `.deb` / `.AppImage` / `.rpm`
|
||||||
|
|
||||||
Full changelog: see commit history.
|
Full changelog: see commit history.
|
||||||
releaseDraft: true
|
|
||||||
prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
|
prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
|
||||||
|
overwrite: true
|
||||||
args: ${{ matrix.args }}
|
args: ${{ matrix.args }}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "kimiswitch",
|
"name": "kimiswitch",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.6.8",
|
"version": "0.7.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
Generated
+1
-1
@@ -1958,7 +1958,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kimiswitch"
|
name = "kimiswitch"
|
||||||
version = "0.6.7"
|
version = "0.7.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "kimiswitch"
|
name = "kimiswitch"
|
||||||
version = "0.6.8"
|
version = "0.7.1"
|
||||||
description = "Kimi Switch - model config manager"
|
description = "Kimi Switch - model config manager"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|||||||
@@ -1078,3 +1078,34 @@ pub async fn kimi_oauth_poll(
|
|||||||
) -> Result<crate::oauth::DevicePollStatus, String> {
|
) -> Result<crate::oauth::DevicePollStatus, String> {
|
||||||
crate::oauth::poll_device_token(&device_code, interval).await
|
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
|
||||||
|
}
|
||||||
+233
-9
@@ -149,6 +149,9 @@ pub struct ModelRow {
|
|||||||
pub model_resolved: String,
|
pub model_resolved: String,
|
||||||
pub price_id: String,
|
pub price_id: String,
|
||||||
pub cost_estimated: bool,
|
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 requests: usize,
|
||||||
pub input_other: u64,
|
pub input_other: u64,
|
||||||
pub output: u64,
|
pub output: u64,
|
||||||
@@ -175,6 +178,9 @@ pub struct RecentRow {
|
|||||||
pub cost_estimated: bool,
|
pub cost_estimated: bool,
|
||||||
pub price_id: String,
|
pub price_id: String,
|
||||||
pub from_env: bool,
|
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)]
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
@@ -330,6 +336,9 @@ pub struct UsageRecord {
|
|||||||
pub model_display: String,
|
pub model_display: String,
|
||||||
pub provider: Option<String>,
|
pub provider: Option<String>,
|
||||||
pub from_env: bool,
|
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
|
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/`
|
/// 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).
|
/// prefix, then fall back to the legacy alias→provider map (config + backups).
|
||||||
fn resolve_provider(model_raw: &str, map: &HashMap<String, String>) -> Option<String> {
|
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))
|
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
|
/// 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.
|
/// 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
|
/// Returns the stripped id (provider prefix preserved), or None when there is
|
||||||
@@ -610,7 +653,62 @@ fn strip_context_suffix(model_name: &str) -> Option<String> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Memoized price resolution. `match_price` is called once per usage record
|
||||||
|
/// during the scan, and the models.dev suffix scan is O(5910) per miss — with
|
||||||
|
/// thousands of records sharing a handful of model names, memoizing the result
|
||||||
|
/// turns the whole scan from O(records × 5910) into O(unique_models × 5910).
|
||||||
|
static MATCH_PRICE_MEMO: OnceLock<Mutex<HashMap<String, (String, f64, f64, f64, bool)>>> =
|
||||||
|
OnceLock::new();
|
||||||
|
|
||||||
|
/// Resolve a model's price, caching per-model results (hits and misses).
|
||||||
fn match_price(model_name: &str) -> (String, f64, f64, f64, bool) {
|
fn match_price(model_name: &str) -> (String, f64, f64, f64, bool) {
|
||||||
|
let key = model_name.to_ascii_lowercase();
|
||||||
|
let memo = MATCH_PRICE_MEMO.get_or_init(|| Mutex::new(HashMap::new()));
|
||||||
|
if let Some(hit) = memo.lock().unwrap().get(&key) {
|
||||||
|
return hit.clone();
|
||||||
|
}
|
||||||
|
let result = match_price_inner(model_name);
|
||||||
|
memo.lock().unwrap().insert(key, result.clone());
|
||||||
|
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('/') {
|
let bare = match model_name.rsplit_once('/') {
|
||||||
Some((_, b)) => b,
|
Some((_, b)) => b,
|
||||||
None => model_name,
|
None => model_name,
|
||||||
@@ -621,11 +719,30 @@ fn match_price(model_name: &str) -> (String, f64, f64, f64, bool) {
|
|||||||
return (id, c.cache_read, c.input, c.output, false);
|
return (id, c.cache_read, c.input, c.output, false);
|
||||||
}
|
}
|
||||||
// Zero-priced listing (subscription-plan entries such as
|
// Zero-priced listing (subscription-plan entries such as
|
||||||
// kimi-for-coding/k3-256k): bill at the base model's list price.
|
// zhipuai-coding-plan/glm-5.2 or kimi-for-coding/kimi-for-coding):
|
||||||
if let Some(base) = strip_context_suffix(model_name) {
|
// bill at a priced equivalent — the full id first, then derived
|
||||||
if let Some((base_id, base_c)) = models_dev_lookup(&base) {
|
// variants (-highspeed / -free), then the context-size base, then the
|
||||||
if base_c.input > 0.0 || base_c.output > 0.0 {
|
// curated flagship fallback.
|
||||||
return (base_id, base_c.cache_read, base_c.input, base_c.output, false);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -638,6 +755,15 @@ fn match_price(model_name: &str) -> (String, f64, f64, f64, bool) {
|
|||||||
return (id, c.cache_read, c.input, c.output, false);
|
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).
|
// 2) legacy Kimi table (kept as a fallback for names not in models.dev).
|
||||||
let bare_l = bare.to_ascii_lowercase();
|
let bare_l = bare.to_ascii_lowercase();
|
||||||
for p in &list_prices() {
|
for p in &list_prices() {
|
||||||
@@ -670,9 +796,30 @@ fn cost_for_usage(input_other: u64, output: u64, cache_read: u64, cache_create:
|
|||||||
// Scanner
|
// 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) {
|
fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
|
||||||
let root = sessions_root(home);
|
let root = sessions_root(home);
|
||||||
let alias2prov = build_alias_provider_map(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) = ¤t_secondary {
|
||||||
|
let _ = crate::db::set_setting_pub(SECONDARY_MODEL_CACHE_KEY, alias);
|
||||||
|
}
|
||||||
let mut records = Vec::new();
|
let mut records = Vec::new();
|
||||||
let mut files_scanned = 0;
|
let mut files_scanned = 0;
|
||||||
let mut lines_seen = 0;
|
let mut lines_seen = 0;
|
||||||
@@ -712,6 +859,21 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
|
|||||||
if scope != "turn" { continue; }
|
if scope != "turn" { continue; }
|
||||||
|
|
||||||
let model_raw = obj.get("model").and_then(|v| v.as_str()).unwrap_or("unknown").to_string();
|
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 time = obj.get("time").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||||
let usage = &obj["usage"];
|
let usage = &obj["usage"];
|
||||||
let input_other = usage.get("inputOther").and_then(|v| v.as_u64()).unwrap_or(0);
|
let input_other = usage.get("inputOther").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||||
@@ -721,16 +883,22 @@ fn scan_usage(home: &Path) -> (Vec<UsageRecord>, ScanMeta) {
|
|||||||
|
|
||||||
// Resolve model display
|
// Resolve model display
|
||||||
let bare = model_raw.rsplit_once('/').map(|x| x.1).unwrap_or(&model_raw);
|
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 (cost, est) = cost_for_usage(input_other, output, cache_read, cache_create, &price_model);
|
||||||
let (pid, _ch, _ip, _op, _) = match_price(&model_raw);
|
// 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 {
|
records.push(UsageRecord {
|
||||||
time,
|
time,
|
||||||
model: model_raw.clone(),
|
model: model_raw.clone(),
|
||||||
model_resolved: bare.to_string(),
|
model_resolved: bare.to_string(),
|
||||||
model_display: model_raw.clone(),
|
model_display: model_raw.clone(),
|
||||||
provider: resolve_provider(&model_raw, &alias2prov),
|
provider: resolve_provider(&price_model, &alias2prov),
|
||||||
from_env: model_raw == "__kimi_env_model__",
|
from_env,
|
||||||
|
is_secondary,
|
||||||
input_other,
|
input_other,
|
||||||
output,
|
output,
|
||||||
input_cache_read: cache_read,
|
input_cache_read: cache_read,
|
||||||
@@ -837,6 +1005,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
|||||||
model_resolved: r.model_resolved.clone(),
|
model_resolved: r.model_resolved.clone(),
|
||||||
price_id: r.price_id.clone(),
|
price_id: r.price_id.clone(),
|
||||||
cost_estimated: r.cost_estimated,
|
cost_estimated: r.cost_estimated,
|
||||||
|
is_secondary: r.is_secondary,
|
||||||
requests: 0, input_other: 0, output: 0,
|
requests: 0, input_other: 0, output: 0,
|
||||||
input_cache_read: 0, input_cache_creation: 0,
|
input_cache_read: 0, input_cache_creation: 0,
|
||||||
cost_usd: 0.0, total_tokens: 0, cache_hit_rate: 0.0,
|
cost_usd: 0.0, total_tokens: 0, cache_hit_rate: 0.0,
|
||||||
@@ -845,6 +1014,7 @@ fn aggregate(records: &[UsageRecord], range: &str, now_ms: u64) -> RangeStats {
|
|||||||
});
|
});
|
||||||
entry.1.add(r);
|
entry.1.add(r);
|
||||||
entry.0.cost_estimated = entry.0.cost_estimated || r.cost_estimated;
|
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;
|
let total_input = totals.input_other + totals.input_cache_read + totals.input_cache_creation;
|
||||||
@@ -891,6 +1061,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,
|
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,
|
cost_usd: r.cost_usd, cost_estimated: r.cost_estimated,
|
||||||
price_id: r.price_id.clone(), from_env: r.from_env,
|
price_id: r.price_id.clone(), from_env: r.from_env,
|
||||||
|
is_secondary: r.is_secondary,
|
||||||
}).collect();
|
}).collect();
|
||||||
|
|
||||||
RangeStats {
|
RangeStats {
|
||||||
@@ -1537,6 +1708,7 @@ pub fn get_prices() -> PricesResult {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh: Option<bool>) -> SummaryResult {
|
pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh: Option<bool>) -> SummaryResult {
|
||||||
|
let t0 = std::time::Instant::now();
|
||||||
let refresh = refresh.unwrap_or(false);
|
let refresh = refresh.unwrap_or(false);
|
||||||
let home = resolve_kimi_home(home_override);
|
let home = resolve_kimi_home(home_override);
|
||||||
let now_ms = std::time::SystemTime::now()
|
let now_ms = std::time::SystemTime::now()
|
||||||
@@ -1544,6 +1716,7 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
|
|||||||
let r = range.unwrap_or_else(|| "30d".into());
|
let r = range.unwrap_or_else(|| "30d".into());
|
||||||
|
|
||||||
let (records, meta) = scan_usage_cached(&home, refresh);
|
let (records, meta) = scan_usage_cached(&home, refresh);
|
||||||
|
let t1 = std::time::Instant::now();
|
||||||
let stats = aggregate(&records, &r, now_ms);
|
let stats = aggregate(&records, &r, now_ms);
|
||||||
let all_stats = aggregate(&records, "all", now_ms);
|
let all_stats = aggregate(&records, "all", now_ms);
|
||||||
let heatmap = build_heatmap(&records, now_ms);
|
let heatmap = build_heatmap(&records, now_ms);
|
||||||
@@ -1568,6 +1741,15 @@ pub fn get_summary(home_override: Option<String>, range: Option<String>, refresh
|
|||||||
name, provider: std::env::var("KIMI_MODEL_PROVIDER").ok(), model: std::env::var("KIMI_MODEL_ID").ok(),
|
name, provider: std::env::var("KIMI_MODEL_PROVIDER").ok(), model: std::env::var("KIMI_MODEL_ID").ok(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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
|
||||||
|
);
|
||||||
|
|
||||||
SummaryResult {
|
SummaryResult {
|
||||||
home: home.to_string_lossy().to_string(),
|
home: home.to_string_lossy().to_string(),
|
||||||
valid: is_kimi_home(&home),
|
valid: is_kimi_home(&home),
|
||||||
@@ -1661,6 +1843,19 @@ mod pricing_tests {
|
|||||||
assert!(est, "unknown models must be flagged as estimated");
|
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]
|
#[test]
|
||||||
fn ambiguous_ids_prefer_official_provider() {
|
fn ambiguous_ids_prefer_official_provider() {
|
||||||
// glm-4.6 ships under resellers too (e.g. 302ai); the official zhipuai
|
// glm-4.6 ships under resellers too (e.g. 302ai); the official zhipuai
|
||||||
@@ -1687,6 +1882,35 @@ mod pricing_tests {
|
|||||||
assert_eq!(strip_context_suffix("kimi-k2-thinking"), None);
|
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]
|
#[test]
|
||||||
fn cache_write_price_preferred_when_present() {
|
fn cache_write_price_preferred_when_present() {
|
||||||
// glm-4.6 has cache_write: 0 → cache creation billed at 0, not input.
|
// glm-4.6 has cache_write: 0 → cache creation billed at 0, not input.
|
||||||
|
|||||||
@@ -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));
|
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)
|
TomlValue::Table(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -552,6 +585,76 @@ api_key = ""
|
|||||||
assert!(caps.iter().any(|v| v.as_str() == Some("thinking")));
|
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]
|
#[test]
|
||||||
fn kimi_code_export_does_not_inject_thinking_from_supports_1m() {
|
fn kimi_code_export_does_not_inject_thinking_from_supports_1m() {
|
||||||
let mut providers = IndexMap::new();
|
let mut providers = IndexMap::new();
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ pub fn run() {
|
|||||||
let icon = app.default_window_icon().unwrap().clone();
|
let icon = app.default_window_icon().unwrap().clone();
|
||||||
TrayIconBuilder::new()
|
TrayIconBuilder::new()
|
||||||
.icon(icon)
|
.icon(icon)
|
||||||
|
.tooltip("Kimi Switch")
|
||||||
.menu(&menu)
|
.menu(&menu)
|
||||||
.show_menu_on_left_click(false)
|
.show_menu_on_left_click(false)
|
||||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||||
@@ -110,6 +111,7 @@ pub fn run() {
|
|||||||
commands::open_external_url,
|
commands::open_external_url,
|
||||||
commands::kimi_oauth_start,
|
commands::kimi_oauth_start,
|
||||||
commands::kimi_oauth_poll,
|
commands::kimi_oauth_poll,
|
||||||
|
commands::get_experimental_env_status,
|
||||||
dashboard::get_paths,
|
dashboard::get_paths,
|
||||||
dashboard::get_prices,
|
dashboard::get_prices,
|
||||||
dashboard::get_summary,
|
dashboard::get_summary,
|
||||||
|
|||||||
@@ -79,7 +79,20 @@ pub async fn query_kimi_coding(api_key: &str, timeout: Duration) -> Result<Usage
|
|||||||
)
|
)
|
||||||
.await?
|
.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),
|
Fetched::Failed(err) => Ok(err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"productName": "Kimi Switch",
|
"productName": "Kimi Switch",
|
||||||
"version": "0.6.8",
|
"version": "0.7.1",
|
||||||
"identifier": "com.kimiswitch.app",
|
"identifier": "com.kimiswitch.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|||||||
+21
-2
@@ -5,6 +5,7 @@ import { useConfig } from "./hooks/useConfig";
|
|||||||
import { useUpdateCheck } from "./hooks/useUpdateCheck";
|
import { useUpdateCheck } from "./hooks/useUpdateCheck";
|
||||||
import { ProviderList } from "./components/ProviderList";
|
import { ProviderList } from "./components/ProviderList";
|
||||||
import { ProviderEdit } from "./components/ProviderEdit";
|
import { ProviderEdit } from "./components/ProviderEdit";
|
||||||
|
import { SubagentSettingsPage } from "./components/SubagentSettingsPage";
|
||||||
import { DashboardPage } from "./components/dashboard/DashboardPage";
|
import { DashboardPage } from "./components/dashboard/DashboardPage";
|
||||||
import { SessionsPage } from "./components/sessions/SessionsPage";
|
import { SessionsPage } from "./components/sessions/SessionsPage";
|
||||||
import { SettingsModal } from "./components/SettingsModal";
|
import { SettingsModal } from "./components/SettingsModal";
|
||||||
@@ -70,7 +71,7 @@ export default function App() {
|
|||||||
updateConfig,
|
updateConfig,
|
||||||
} = useConfig(agent);
|
} = 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 [editingProvider, setEditingProvider] = useState<string>("");
|
||||||
const [loadTimeout, setLoadTimeout] = useState(false);
|
const [loadTimeout, setLoadTimeout] = useState(false);
|
||||||
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
|
const [switchMessage, setSwitchMessage] = useState<string | null>(null);
|
||||||
@@ -573,7 +574,7 @@ export default function App() {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => setView("list")}
|
onClick={() => setView("list")}
|
||||||
className={`px-3 py-1 text-sm rounded transition-colors ${
|
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"
|
? "bg-blue-600 text-white"
|
||||||
: "text-content-muted hover:text-content-primary"
|
: "text-content-muted hover:text-content-primary"
|
||||||
}`}
|
}`}
|
||||||
@@ -649,6 +650,15 @@ export default function App() {
|
|||||||
<DashboardPage />
|
<DashboardPage />
|
||||||
) : view === "sessions" ? (
|
) : view === "sessions" ? (
|
||||||
<SessionsPage />
|
<SessionsPage />
|
||||||
|
) : view === "subagent" ? (
|
||||||
|
<SubagentSettingsPage
|
||||||
|
rawOther={config.raw_other}
|
||||||
|
models={config.models}
|
||||||
|
onChange={(nextRawOther) =>
|
||||||
|
updateConfig((cfg) => ({ ...cfg, raw_other: nextRawOther }))
|
||||||
|
}
|
||||||
|
onBack={() => setView("list")}
|
||||||
|
/>
|
||||||
) : view === "list" ? (
|
) : view === "list" ? (
|
||||||
<ProviderList
|
<ProviderList
|
||||||
providers={providers}
|
providers={providers}
|
||||||
@@ -813,6 +823,15 @@ export default function App() {
|
|||||||
>
|
>
|
||||||
{t("openConfigDir")}
|
{t("openConfigDir")}
|
||||||
</button>
|
</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>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import type { ReactNode } from "react";
|
|
||||||
import { useTranslation } from "../i18n";
|
import { useTranslation } from "../i18n";
|
||||||
import type { TranslationKey } from "../i18n/zh";
|
import type { TranslationKey } from "../i18n/zh";
|
||||||
import { getAgentSettings, setAgentSettings } from "../lib/agent-settings";
|
import { getAgentSettings, setAgentSettings } from "../lib/agent-settings";
|
||||||
import type { AgentSettings, Hook, PermissionRule } from "../types";
|
import type { AgentSettings, Hook, PermissionRule } from "../types";
|
||||||
|
import { Card, Checkbox, NumberField, Segmented } from "./ui/controls";
|
||||||
|
|
||||||
interface AgentSettingsPanelProps {
|
interface AgentSettingsPanelProps {
|
||||||
rawOther: unknown;
|
rawOther: unknown;
|
||||||
@@ -275,102 +275,3 @@ export function AgentSettingsPanel({ rawOther, onChange }: AgentSettingsPanelPro
|
|||||||
</div>
|
</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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -699,6 +699,7 @@ function ModelMapping({
|
|||||||
<td className="px-4 py-2">
|
<td className="px-4 py-2">
|
||||||
<CapabilitiesCell
|
<CapabilitiesCell
|
||||||
capabilities={m.capabilities || []}
|
capabilities={m.capabilities || []}
|
||||||
|
nativeImage={getModelRef(m.model)?.image === true}
|
||||||
onChange={(next) =>
|
onChange={(next) =>
|
||||||
onModelChange({ ...m, capabilities: next })
|
onModelChange({ ...m, capabilities: next })
|
||||||
}
|
}
|
||||||
@@ -822,9 +823,13 @@ function JsonPreview({
|
|||||||
function CapabilitiesCell({
|
function CapabilitiesCell({
|
||||||
capabilities,
|
capabilities,
|
||||||
onChange,
|
onChange,
|
||||||
|
nativeImage,
|
||||||
}: {
|
}: {
|
||||||
capabilities: string[];
|
capabilities: string[];
|
||||||
onChange: (next: string[]) => void;
|
onChange: (next: string[]) => void;
|
||||||
|
/** 模型本身是否原生支持图像输入(models.dev `image` 能力)。原生多模态
|
||||||
|
* 模型无需 kimi-eyes 插件,提示不展示。 */
|
||||||
|
nativeImage?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
@@ -838,13 +843,12 @@ function CapabilitiesCell({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
|
||||||
{/* Only `thinking` is user-editable. The other capabilities
|
{/* `thinking` 与 `image_in`(识图)可手动编辑;其余能力
|
||||||
(always_thinking / image_in / video_in / tool_use) are still
|
(always_thinking / video_in / tool_use) 仍由 models.dev 自动派生,
|
||||||
auto-derived from models.dev via `capabilitiesFromRef` and saved
|
保存时照常写入 config.toml。 */}
|
||||||
to config.toml — they just aren't exposed for manual editing.
|
{KNOWN_CAPABILITIES.filter(
|
||||||
To restore the full editor, drop the `.filter(...)` below and
|
(cap) => cap === "thinking" || cap === "image_in",
|
||||||
re-add the custom-capabilities input (see git history). */}
|
).map((cap) => (
|
||||||
{KNOWN_CAPABILITIES.filter((cap) => cap === "thinking").map((cap) => (
|
|
||||||
<label
|
<label
|
||||||
key={cap}
|
key={cap}
|
||||||
className="flex items-center gap-1 text-xs text-content-muted cursor-pointer"
|
className="flex items-center gap-1 text-xs text-content-muted cursor-pointer"
|
||||||
@@ -858,6 +862,11 @@ function CapabilitiesCell({
|
|||||||
{t(CAPABILITY_LABELS[cap])}
|
{t(CAPABILITY_LABELS[cap])}
|
||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
|
{capabilities.includes("image_in") && !nativeImage && (
|
||||||
|
<span className="w-full text-[11px] text-content-muted">
|
||||||
|
{t("capImageInHint")}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -372,6 +372,30 @@ export function SettingsModal({
|
|||||||
<div>{t("appDescription")}</div>
|
<div>{t("appDescription")}</div>
|
||||||
<div className="text-xs text-content-muted">v{appVersion} · MIT License</div>
|
<div className="text-xs text-content-muted">v{appVersion} · MIT License</div>
|
||||||
<div className="pt-2 space-y-1">
|
<div className="pt-2 space-y-1">
|
||||||
|
<div>
|
||||||
|
{t("settingsWebsite")}:{" "}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
openExternal("https://billowliu2.github.io/KimiSwitch")
|
||||||
|
}
|
||||||
|
className="text-blue-500 hover:text-blue-400 underline bg-transparent p-0 border-0 cursor-pointer"
|
||||||
|
>
|
||||||
|
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>
|
<div>
|
||||||
{t("attributionPorted")}{" "}
|
{t("attributionPorted")}{" "}
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
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,
|
||||||
|
getSecondaryModel,
|
||||||
|
isFlagLockedByEnv,
|
||||||
|
isMasterEnvOn,
|
||||||
|
setExperimentalFlag,
|
||||||
|
setSecondaryModelOnly,
|
||||||
|
type ExperimentalFlagDef,
|
||||||
|
} from "../lib/subagent-settings";
|
||||||
|
import { Card, Checkbox } 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",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export function SubagentSettingsPage({
|
||||||
|
rawOther,
|
||||||
|
models,
|
||||||
|
onChange,
|
||||||
|
onBack,
|
||||||
|
}: SubagentSettingsPageProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [env, setEnv] = useState<ExperimentalEnvStatus | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
invoke<ExperimentalEnvStatus>("get_experimental_env_status")
|
||||||
|
.then(setEnv)
|
||||||
|
.catch(() => setEnv({}));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const flags = getExperimentalFlags(rawOther);
|
||||||
|
const secondary = getSecondaryModel(rawOther);
|
||||||
|
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 aliasList = Object.keys(models).sort();
|
||||||
|
|
||||||
|
// 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 = secondary.model ? models[secondary.model] : 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
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>
|
||||||
|
)}
|
||||||
|
<Checkbox
|
||||||
|
label=""
|
||||||
|
checked={on}
|
||||||
|
disabled={locked}
|
||||||
|
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>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Subagent: experimental flag + secondary model in one card */}
|
||||||
|
<Card title={t("secondaryModelSection")}>
|
||||||
|
{renderFlagRow(secondaryFlag)}
|
||||||
|
<div className="border-t border-border" />
|
||||||
|
|
||||||
|
{!secondaryEnabled && (
|
||||||
|
<div className="bg-amber-100 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-500/30 rounded-lg px-3 py-2 text-sm text-amber-800 dark:text-amber-400">
|
||||||
|
{t("secondaryModelDisabledHint")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<label className="flex items-center gap-3 text-sm text-content-primary">
|
||||||
|
<span className="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={secondary.model ?? ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
const alias = e.target.value;
|
||||||
|
if (alias === "") {
|
||||||
|
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 Kimi Code's synthesized `__secondary__` entry.
|
||||||
|
onChange(setSecondaryModelOnly(rawOther, alias));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">{t("secondaryModelUnset")}</option>
|
||||||
|
{aliasList.map((alias) => (
|
||||||
|
<option key={alias} value={alias}>
|
||||||
|
{models[alias]?.display_name
|
||||||
|
? `${alias}(${models[alias].display_name})`
|
||||||
|
: alias}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{secondary.model !== undefined && (
|
||||||
|
<div className="rounded-lg border border-border bg-input/40 px-3 py-2 space-y-1.5">
|
||||||
|
<div className="flex items-center gap-3 text-sm">
|
||||||
|
<span className="text-content-muted w-24 shrink-0">
|
||||||
|
{t("secondaryModelInheritedContext")}
|
||||||
|
</span>
|
||||||
|
<span className="text-content-primary">
|
||||||
|
{inheritedContext ? fmtContext(inheritedContext) : "—"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 text-sm">
|
||||||
|
<span className="text-content-muted w-24 shrink-0">
|
||||||
|
{t("secondaryModelInheritedEffort")}
|
||||||
|
</span>
|
||||||
|
<span className="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("secondaryModelHint")}</p>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -357,7 +357,9 @@ export function UsageFooter({
|
|||||||
// success, or error/loading with last-good data (ghost).
|
// success, or error/loading with last-good data (ghost).
|
||||||
// Compact header already shows the primary entry; detail only adds value
|
// Compact header already shows the primary entry; detail only adds value
|
||||||
// when there are multiple tiers (e.g. 5h + weekly) or on error ghost.
|
// 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";
|
const ghost = status !== "success";
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { useTranslation } from "../../i18n";
|
import { useTranslation } from "../../i18n";
|
||||||
import { fmtPct, fmtTokens, fmtUsd } from "../../lib/dashboard-format";
|
import { useCurrency } from "../../hooks/useCurrency";
|
||||||
|
import { fmtPct, fmtTokens } from "../../lib/dashboard-format";
|
||||||
import type { DailyRow } from "../../types/dashboard";
|
import type { DailyRow } from "../../types/dashboard";
|
||||||
import { DailyDetailModal } from "./DailyDetailModal";
|
import { DailyDetailModal } from "./DailyDetailModal";
|
||||||
|
|
||||||
@@ -43,6 +44,7 @@ function shortModel(model: string): string {
|
|||||||
|
|
||||||
export function DailyBars({ daily, dimension, names, unknownProviderLabel }: DailyBarsProps) {
|
export function DailyBars({ daily, dimension, names, unknownProviderLabel }: DailyBarsProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { money } = useCurrency();
|
||||||
const [selected, setSelected] = useState<DailyRow | null>(null);
|
const [selected, setSelected] = useState<DailyRow | null>(null);
|
||||||
|
|
||||||
const colorMap = useMemo(() => {
|
const colorMap = useMemo(() => {
|
||||||
@@ -57,6 +59,10 @@ export function DailyBars({ daily, dimension, names, unknownProviderLabel }: Dai
|
|||||||
if (dimension === "provider") {
|
if (dimension === "provider") {
|
||||||
return key === "unknown" ? unknownProviderLabel : key;
|
return key === "unknown" ? unknownProviderLabel : key;
|
||||||
}
|
}
|
||||||
|
// Subagent records (Kimi Code `__secondary__` marker) show their own label.
|
||||||
|
if (key === "__secondary__") {
|
||||||
|
return t("subagentModel");
|
||||||
|
}
|
||||||
return shortModel(key);
|
return shortModel(key);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -103,7 +109,7 @@ export function DailyBars({ daily, dimension, names, unknownProviderLabel }: Dai
|
|||||||
|
|
||||||
const tooltipLines = [
|
const tooltipLines = [
|
||||||
d.date,
|
d.date,
|
||||||
`${t("totalTokens")}: ${fmtTokens(d.totalTokens)} · ${fmtUsd(d.costUsd)} · ${t("colCacheHit")} ${fmtPct(d.cacheHitRate)}`,
|
`${t("totalTokens")}: ${fmtTokens(d.totalTokens)} · ${money(d.costUsd)} · ${t("colCacheHit")} ${fmtPct(d.cacheHitRate)}`,
|
||||||
...segments.map((s) => `${displayName(s.key)}: ${fmtTokens(s.tokens)}`),
|
...segments.map((s) => `${displayName(s.key)}: ${fmtTokens(s.tokens)}`),
|
||||||
"",
|
"",
|
||||||
t("doubleClickHint"),
|
t("doubleClickHint"),
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useTranslation } from "../../i18n";
|
import { useTranslation } from "../../i18n";
|
||||||
import { fmtPct, fmtTokens, fmtUsd } from "../../lib/dashboard-format";
|
import { useCurrency } from "../../hooks/useCurrency";
|
||||||
|
import { fmtPct, fmtTokens } from "../../lib/dashboard-format";
|
||||||
import type { DailyRow } from "../../types/dashboard";
|
import type { DailyRow } from "../../types/dashboard";
|
||||||
import { modelColor } from "./DailyBars";
|
import { modelColor } from "./DailyBars";
|
||||||
|
|
||||||
@@ -22,6 +23,11 @@ function shortModel(model: string): string {
|
|||||||
|
|
||||||
export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabel, onClose }: DailyDetailModalProps) {
|
export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabel, onClose }: DailyDetailModalProps) {
|
||||||
const { t } = useTranslation();
|
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(() => {
|
useEffect(() => {
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
@@ -106,7 +112,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
|
|||||||
{/* Day summary chips */}
|
{/* Day summary chips */}
|
||||||
<div className="grid grid-cols-2 gap-2 px-5 py-3 sm:grid-cols-4">
|
<div className="grid grid-cols-2 gap-2 px-5 py-3 sm:grid-cols-4">
|
||||||
<SummaryChip label={t("totalTokens")} value={fmtTokens(day.totalTokens)} tone="default" />
|
<SummaryChip label={t("totalTokens")} value={fmtTokens(day.totalTokens)} tone="default" />
|
||||||
<SummaryChip label={t("cost")} value={fmtUsd(day.costUsd)} tone="orange" />
|
<SummaryChip label={t("cost")} value={money(day.costUsd)} tone="orange" />
|
||||||
<SummaryChip label={t("requests")} value={Math.round(day.requests).toLocaleString()} tone="blue" />
|
<SummaryChip label={t("requests")} value={Math.round(day.requests).toLocaleString()} tone="blue" />
|
||||||
<SummaryChip label={t("cacheHitRate")} value={fmtPct(day.cacheHitRate)} tone="green" />
|
<SummaryChip label={t("cacheHitRate")} value={fmtPct(day.cacheHitRate)} tone="green" />
|
||||||
</div>
|
</div>
|
||||||
@@ -141,7 +147,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
|
|||||||
<div className="mt-1 ml-5 space-y-0.5">
|
<div className="mt-1 ml-5 space-y-0.5">
|
||||||
{p.models.map((m) => (
|
{p.models.map((m) => (
|
||||||
<div key={m.model} className="flex items-baseline justify-between gap-2 text-xs">
|
<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>
|
<span className="shrink-0 text-content-muted tabular-nums">{fmtTokens(m.tokens)}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -165,7 +171,7 @@ export function DailyDetailModal({ day, dimension, colorMap, unknownProviderLabe
|
|||||||
<span className="inline-block h-2.5 w-2.5 rounded-sm shrink-0" style={{ backgroundColor: modelColor(i) }} />
|
<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="min-w-0 flex-1">
|
||||||
<div className="flex items-baseline justify-between gap-2">
|
<div className="flex items-baseline justify-between gap-2">
|
||||||
<span className="truncate text-content-primary" title={s.model}>{shortModel(s.model)}</span>
|
<span className="truncate text-content-primary" title={s.model}>{modelName(s.model)}</span>
|
||||||
<span className="shrink-0 text-xs text-content-muted tabular-nums">
|
<span className="shrink-0 text-xs text-content-muted tabular-nums">
|
||||||
{fmtTokens(s.tokens)} <span className="text-content-muted">· {s.pct.toFixed(1)}%</span>
|
{fmtTokens(s.tokens)} <span className="text-content-muted">· {s.pct.toFixed(1)}%</span>
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
import { useState, type ReactNode } from "react";
|
import { useState, type ReactNode } from "react";
|
||||||
import { useDashboard, type DashboardRange } from "../../hooks/useDashboard";
|
import { useDashboard, type DashboardRange } from "../../hooks/useDashboard";
|
||||||
|
import { useCurrency } from "../../hooks/useCurrency";
|
||||||
import { useTranslation } from "../../i18n";
|
import { useTranslation } from "../../i18n";
|
||||||
import { fmtInt, fmtPct, fmtTime, fmtTokens, fmtUsd } from "../../lib/dashboard-format";
|
import { fmtInt, fmtPct, fmtTime, fmtTokens } from "../../lib/dashboard-format";
|
||||||
import { DailyBars } from "./DailyBars";
|
import { DailyBars } from "./DailyBars";
|
||||||
import { Heatmap } from "./Heatmap";
|
import { Heatmap } from "./Heatmap";
|
||||||
import { TrendLineChart } from "./TrendLineChart";
|
import { TrendLineChart } from "./TrendLineChart";
|
||||||
|
|
||||||
const RANGES: DashboardRange[] = ["today", "7d", "30d", "all"];
|
const RANGES: DashboardRange[] = ["today", "7d", "30d", "all"];
|
||||||
|
|
||||||
|
/** Per-request cache hit rate: cached tokens / total input tokens. */
|
||||||
|
function cacheHitOf(r: { inputOther: number; inputCacheRead: number }): number {
|
||||||
|
const denom = r.inputOther + r.inputCacheRead;
|
||||||
|
return denom > 0 ? r.inputCacheRead / denom : 0;
|
||||||
|
}
|
||||||
|
|
||||||
function Card({
|
function Card({
|
||||||
title,
|
title,
|
||||||
subtitle,
|
subtitle,
|
||||||
@@ -44,7 +51,8 @@ function KpiCard({ label, value, sub }: { label: string; value: string; sub?: st
|
|||||||
|
|
||||||
export function DashboardPage() {
|
export function DashboardPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { range, changeRange, data, loading, error, refresh } = useDashboard();
|
const { money } = useCurrency();
|
||||||
|
const { range, changeRange, data, loading, error, refresh, loadStats } = useDashboard();
|
||||||
const [showAllModels, setShowAllModels] = useState(false);
|
const [showAllModels, setShowAllModels] = useState(false);
|
||||||
const [recentPage, setRecentPage] = useState(1);
|
const [recentPage, setRecentPage] = useState(1);
|
||||||
const [trendTab, setTrendTab] = useState<"daily" | "model" | "provider">("daily");
|
const [trendTab, setTrendTab] = useState<"daily" | "model" | "provider">("daily");
|
||||||
@@ -120,28 +128,35 @@ export function DashboardPage() {
|
|||||||
{ label: t("kpiCacheCreation"), value: fmtTokens(totals.inputCacheCreation), sub: fmtInt(totals.inputCacheCreation) },
|
{ label: t("kpiCacheCreation"), value: fmtTokens(totals.inputCacheCreation), sub: fmtInt(totals.inputCacheCreation) },
|
||||||
{ label: t("kpiCacheHit"), value: fmtPct(totals.cacheHitRate) },
|
{ label: t("kpiCacheHit"), value: fmtPct(totals.cacheHitRate) },
|
||||||
{ label: t("totalTokens"), value: fmtTokens(totals.totalTokens), sub: fmtInt(totals.totalTokens) },
|
{ label: t("totalTokens"), value: fmtTokens(totals.totalTokens), sub: fmtInt(totals.totalTokens) },
|
||||||
{ label: t("kpiCost"), value: fmtUsd(totals.costUsd) },
|
{ label: t("kpiCost"), value: money(totals.costUsd) },
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-full overflow-auto p-4 space-y-4">
|
<div className="h-full overflow-auto p-4 space-y-4">
|
||||||
{/* Range tabs + refresh */}
|
{/* Range tabs + refresh */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center bg-input border border-border rounded p-0.5">
|
<div className="flex items-center gap-3">
|
||||||
{RANGES.map((r) => (
|
<div className="flex items-center bg-input border border-border rounded p-0.5">
|
||||||
<button
|
{RANGES.map((r) => (
|
||||||
key={r}
|
<button
|
||||||
type="button"
|
key={r}
|
||||||
onClick={() => changeRange(r)}
|
type="button"
|
||||||
className={`px-3 py-1 text-sm rounded transition-colors ${
|
onClick={() => changeRange(r)}
|
||||||
range === r
|
className={`px-3 py-1 text-sm rounded transition-colors ${
|
||||||
? "bg-blue-600 text-white"
|
range === r
|
||||||
: "text-content-muted hover:text-content-primary"
|
? "bg-blue-600 text-white"
|
||||||
}`}
|
: "text-content-muted hover:text-content-primary"
|
||||||
>
|
}`}
|
||||||
{RANGE_LABELS[r]}
|
>
|
||||||
</button>
|
{RANGE_LABELS[r]}
|
||||||
))}
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{loadStats && !loading && (
|
||||||
|
<span className="hidden text-[10px] text-content-muted sm:inline">
|
||||||
|
{t("loadStats", { ms: loadStats.ms, kb: loadStats.kb })}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -175,7 +190,7 @@ export function DashboardPage() {
|
|||||||
{fmtTokens(tot.totalTokens)}
|
{fmtTokens(tot.totalTokens)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1 text-[11px] text-content-muted">
|
<div className="mt-1 text-[11px] text-content-muted">
|
||||||
{fmtInt(tot.requests)} {t("unitTimes")} · {fmtUsd(tot.costUsd)} · {fmtPct(tot.cacheHitRate)}
|
{fmtInt(tot.requests)} {t("unitTimes")} · {money(tot.costUsd)} · {fmtPct(tot.cacheHitRate)}
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@@ -295,7 +310,9 @@ export function DashboardPage() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div className="flex items-center gap-1.5 min-w-0">
|
<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 && (
|
{m.costEstimated && (
|
||||||
<span className="text-[10px] text-yellow-600 shrink-0">({t("estimate")})</span>
|
<span className="text-[10px] text-yellow-600 shrink-0">({t("estimate")})</span>
|
||||||
)}
|
)}
|
||||||
@@ -305,7 +322,7 @@ export function DashboardPage() {
|
|||||||
<td className="py-2 pr-3 text-right text-content-muted">{fmtInt(m.requests)}</td>
|
<td className="py-2 pr-3 text-right text-content-muted">{fmtInt(m.requests)}</td>
|
||||||
<td className="py-2 pr-3 text-right text-content-muted">{fmtTokens(m.totalTokens)}</td>
|
<td className="py-2 pr-3 text-right text-content-muted">{fmtTokens(m.totalTokens)}</td>
|
||||||
<td className="py-2 pr-3 text-right text-content-muted">{fmtPct(m.cacheHitRate)}</td>
|
<td className="py-2 pr-3 text-right text-content-muted">{fmtPct(m.cacheHitRate)}</td>
|
||||||
<td className="py-2 text-right text-orange-600 dark:text-orange-400">{fmtUsd(m.costUsd)}</td>
|
<td className="py-2 text-right text-orange-600 dark:text-orange-400">{money(m.costUsd)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -346,6 +363,7 @@ export function DashboardPage() {
|
|||||||
<th className="pb-2 pr-4 font-normal text-right">{t("colInput")}</th>
|
<th className="pb-2 pr-4 font-normal text-right">{t("colInput")}</th>
|
||||||
<th className="pb-2 pr-4 font-normal text-right">{t("colOutput")}</th>
|
<th className="pb-2 pr-4 font-normal text-right">{t("colOutput")}</th>
|
||||||
<th className="pb-2 pr-4 font-normal text-right">{t("colCacheRead")}</th>
|
<th className="pb-2 pr-4 font-normal text-right">{t("colCacheRead")}</th>
|
||||||
|
<th className="pb-2 pr-4 font-normal text-right">{t("colCacheHit")}</th>
|
||||||
<th className="pb-2 font-normal text-right">{t("cost")}</th>
|
<th className="pb-2 font-normal text-right">{t("cost")}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -355,11 +373,18 @@ export function DashboardPage() {
|
|||||||
<td className="py-1.5 pr-4 text-content-muted whitespace-nowrap">
|
<td className="py-1.5 pr-4 text-content-muted whitespace-nowrap">
|
||||||
{fmtTime(r.time)}
|
{fmtTime(r.time)}
|
||||||
</td>
|
</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.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.output)}</td>
|
||||||
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputCacheRead)}</td>
|
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtTokens(r.inputCacheRead)}</td>
|
||||||
<td className="py-1.5 text-right text-orange-600 dark:text-orange-400">{fmtUsd(r.costUsd)}</td>
|
<td className="py-1.5 pr-4 text-right text-content-muted">{fmtPct(cacheHitOf(r))}</td>
|
||||||
|
<td className="py-1.5 text-right text-orange-600 dark:text-orange-400">{money(r.costUsd)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||||
import { createPortal } from "react-dom";
|
import { createPortal } from "react-dom";
|
||||||
import { useTranslation } from "../../i18n";
|
import { useTranslation } from "../../i18n";
|
||||||
import { fmtPct, fmtTokens, fmtUsd } from "../../lib/dashboard-format";
|
import { useCurrency } from "../../hooks/useCurrency";
|
||||||
|
import { fmtPct, fmtTokens } from "../../lib/dashboard-format";
|
||||||
import type { HeatmapCell, HeatmapData } from "../../types/dashboard";
|
import type { HeatmapCell, HeatmapData } from "../../types/dashboard";
|
||||||
|
|
||||||
interface HeatmapProps {
|
interface HeatmapProps {
|
||||||
@@ -220,6 +221,7 @@ export function Heatmap({ heatmap }: HeatmapProps) {
|
|||||||
|
|
||||||
function HeatmapTooltip({ state }: { state: HoverState }) {
|
function HeatmapTooltip({ state }: { state: HoverState }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { money } = useCurrency();
|
||||||
const { cell, x, y } = state;
|
const { cell, x, y } = state;
|
||||||
// Position above the cursor with a small offset; flip below if too close to top.
|
// Position above the cursor with a small offset; flip below if too close to top.
|
||||||
const offset = 14;
|
const offset = 14;
|
||||||
@@ -239,7 +241,7 @@ function HeatmapTooltip({ state }: { state: HoverState }) {
|
|||||||
>
|
>
|
||||||
<div className="font-medium text-content-primary">{cell.date}</div>
|
<div className="font-medium text-content-primary">{cell.date}</div>
|
||||||
<div className="text-content-muted">
|
<div className="text-content-muted">
|
||||||
{fmtTokens(cell.totalTokens)} · {fmtUsd(cell.costUsd)} ·{" "}
|
{fmtTokens(cell.totalTokens)} · {money(cell.costUsd)} ·{" "}
|
||||||
{fmtInt(cell.requests)} {t("requests")}
|
{fmtInt(cell.requests)} {t("requests")}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-content-muted">
|
<div className="text-content-muted">
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { useTranslation } from "../i18n";
|
||||||
|
import { fmtUsd } from "../lib/dashboard-format";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* USD → CNY exchange rate for the dashboard.
|
||||||
|
* Chinese mode shows prices in CNY (latest available rate), English stays in
|
||||||
|
* USD. The rate is fetched once and cached in localStorage for 12h; any
|
||||||
|
* failure falls back to a conservative fixed rate so the UI never blocks.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const FALLBACK_RATE = 7.2;
|
||||||
|
const CACHE_KEY = "kimi-switch-cny-rate";
|
||||||
|
const CACHE_TTL = 12 * 60 * 60 * 1000; // 12 hours
|
||||||
|
|
||||||
|
function readCachedRate(): number | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(CACHE_KEY);
|
||||||
|
if (!raw) return null;
|
||||||
|
const { ts, rate } = JSON.parse(raw) as { ts: number; rate: number };
|
||||||
|
if (Date.now() - ts > CACHE_TTL || !(rate > 1)) return null;
|
||||||
|
return rate;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeCachedRate(rate: number) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), rate }));
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCurrency() {
|
||||||
|
const { lang } = useTranslation();
|
||||||
|
const [rate, setRate] = useState<number | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
const cached = readCachedRate();
|
||||||
|
if (cached) {
|
||||||
|
setRate(cached);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await fetch("https://open.er-api.com/v6/latest/USD");
|
||||||
|
if (res.ok) {
|
||||||
|
const data = (await res.json()) as { rates?: { CNY?: number } };
|
||||||
|
const cny = Number(data.rates?.CNY);
|
||||||
|
if (cny > 1) {
|
||||||
|
if (!cancelled) setRate(cny);
|
||||||
|
writeCachedRate(cny);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* network blocked → fallback */
|
||||||
|
}
|
||||||
|
if (!cancelled) setRate(FALLBACK_RATE);
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/** Format a USD cost for display: CNY in Chinese mode, USD otherwise. */
|
||||||
|
const money = useCallback(
|
||||||
|
(usd: number): string => {
|
||||||
|
if (lang !== "zh") return fmtUsd(usd);
|
||||||
|
const v = (Number(usd) || 0) * (rate ?? FALLBACK_RATE);
|
||||||
|
if (v === 0) return "¥0.00";
|
||||||
|
if (v < 0.1) return "¥" + v.toFixed(3);
|
||||||
|
if (v < 1) return "¥" + v.toFixed(2);
|
||||||
|
return "¥" + v.toFixed(2);
|
||||||
|
},
|
||||||
|
[lang, rate],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { money, cnyRate: rate ?? FALLBACK_RATE };
|
||||||
|
}
|
||||||
@@ -22,16 +22,23 @@ export function useDashboard() {
|
|||||||
const [data, setData] = useState<SummaryResult | null>(null);
|
const [data, setData] = useState<SummaryResult | null>(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
/** Round-trip timing for the last get_summary call (user-perceived lag). */
|
||||||
|
const [loadStats, setLoadStats] = useState<{ ms: number; kb: number } | null>(null);
|
||||||
|
|
||||||
const refresh = useCallback(async (force = false) => {
|
const refresh = useCallback(async (force = false) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
const start = performance.now();
|
||||||
try {
|
try {
|
||||||
const result = await invoke<SummaryResult>("get_summary", {
|
const result = await invoke<SummaryResult>("get_summary", {
|
||||||
range,
|
range,
|
||||||
refresh: force,
|
refresh: force,
|
||||||
});
|
});
|
||||||
setData(result);
|
setData(result);
|
||||||
|
setLoadStats({
|
||||||
|
ms: Math.round(performance.now() - start),
|
||||||
|
kb: Math.round(JSON.stringify(result).length / 1024),
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
setError(msg);
|
setError(msg);
|
||||||
@@ -53,5 +60,5 @@ export function useDashboard() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return { range, changeRange, data, loading, error, refresh };
|
return { range, changeRange, data, loading, error, refresh, loadStats };
|
||||||
}
|
}
|
||||||
@@ -163,6 +163,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
|||||||
capThinking: "Thinking",
|
capThinking: "Thinking",
|
||||||
capAlwaysThinking: "Always Thinking",
|
capAlwaysThinking: "Always Thinking",
|
||||||
capImageIn: "Image Input",
|
capImageIn: "Image Input",
|
||||||
|
capImageInHint: "Text models actually need the plugin-kimi-eyes:kimi-eyes plugin for image recognition",
|
||||||
capVideoIn: "Video Input",
|
capVideoIn: "Video Input",
|
||||||
capToolUse: "Tool Use",
|
capToolUse: "Tool Use",
|
||||||
customCapabilities: "Other capabilities (comma-separated)",
|
customCapabilities: "Other capabilities (comma-separated)",
|
||||||
@@ -197,6 +198,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
|||||||
scanning: "Scanning…",
|
scanning: "Scanning…",
|
||||||
refresh: "Refresh",
|
refresh: "Refresh",
|
||||||
refreshing: "Refreshing…",
|
refreshing: "Refreshing…",
|
||||||
|
loadStats: "Loaded in {ms} ms · {kb} KB payload",
|
||||||
refreshed: "Refreshed",
|
refreshed: "Refreshed",
|
||||||
cancel: "Cancel",
|
cancel: "Cancel",
|
||||||
confirmDeleteTitle: "Delete session forever?",
|
confirmDeleteTitle: "Delete session forever?",
|
||||||
@@ -260,6 +262,8 @@ export const enTranslations: Record<TranslationKey, string> = {
|
|||||||
updateCheckFailed: "Update check failed",
|
updateCheckFailed: "Update check failed",
|
||||||
lastChecked: "Last checked",
|
lastChecked: "Last checked",
|
||||||
appDescription: "Windows desktop LLM provider config manager",
|
appDescription: "Windows desktop LLM provider config manager",
|
||||||
|
settingsWebsite: "Official website",
|
||||||
|
kimiEyesSite: "Kimi Eyes plugin site",
|
||||||
referenceProject: "Reference project",
|
referenceProject: "Reference project",
|
||||||
|
|
||||||
// Validation errors
|
// Validation errors
|
||||||
@@ -316,6 +320,7 @@ export const enTranslations: Record<TranslationKey, string> = {
|
|||||||
colCacheRead: "Cache read",
|
colCacheRead: "Cache read",
|
||||||
unitTimes: "requests",
|
unitTimes: "requests",
|
||||||
estimate: "est.",
|
estimate: "est.",
|
||||||
|
subagentModel: "Subagent model",
|
||||||
collapse: "Collapse",
|
collapse: "Collapse",
|
||||||
expandAll: "Expand all ({n})",
|
expandAll: "Expand all ({n})",
|
||||||
|
|
||||||
@@ -443,4 +448,34 @@ export const enTranslations: Record<TranslationKey, string> = {
|
|||||||
trendLineShowRequests: "Show requests",
|
trendLineShowRequests: "Show requests",
|
||||||
trendLineTooltip: "{date}\nTokens: {tokens}\nCache hit: {cache}\nRequests: {req}",
|
trendLineTooltip: "{date}\nTokens: {tokens}\nCache hit: {cache}\nRequests: {req}",
|
||||||
trendLineNoData: "No data",
|
trendLineNoData: "No data",
|
||||||
|
|
||||||
|
// Subagent settings page (experimental flags + secondary model)
|
||||||
|
subagentSettings: "Subagent 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: explicit tool model param > profile model_preference > this config > inherit primary model",
|
||||||
};
|
};
|
||||||
@@ -161,6 +161,7 @@ export const zhTranslations = {
|
|||||||
capThinking: "思考",
|
capThinking: "思考",
|
||||||
capAlwaysThinking: "始终思考",
|
capAlwaysThinking: "始终思考",
|
||||||
capImageIn: "图像输入",
|
capImageIn: "图像输入",
|
||||||
|
capImageInHint: "文本推理模型实际需要搭配 plugin-kimi-eyes:kimi-eyes 插件才能识图",
|
||||||
capVideoIn: "视频输入",
|
capVideoIn: "视频输入",
|
||||||
capToolUse: "工具调用",
|
capToolUse: "工具调用",
|
||||||
customCapabilities: "其他能力(逗号分隔)",
|
customCapabilities: "其他能力(逗号分隔)",
|
||||||
@@ -194,6 +195,7 @@ export const zhTranslations = {
|
|||||||
scanning: "扫描中…",
|
scanning: "扫描中…",
|
||||||
refresh: "刷新",
|
refresh: "刷新",
|
||||||
refreshing: "刷新中…",
|
refreshing: "刷新中…",
|
||||||
|
loadStats: "加载 {ms} ms · 数据 {kb} KB",
|
||||||
refreshed: "已刷新",
|
refreshed: "已刷新",
|
||||||
cancel: "取消",
|
cancel: "取消",
|
||||||
confirmDeleteTitle: "永久删除会话?",
|
confirmDeleteTitle: "永久删除会话?",
|
||||||
@@ -255,6 +257,8 @@ export const zhTranslations = {
|
|||||||
updateCheckFailed: "检查更新失败",
|
updateCheckFailed: "检查更新失败",
|
||||||
lastChecked: "上次检查",
|
lastChecked: "上次检查",
|
||||||
appDescription: "Windows 桌面端 LLM 供应商配置管理器",
|
appDescription: "Windows 桌面端 LLM 供应商配置管理器",
|
||||||
|
settingsWebsite: "官方网站",
|
||||||
|
kimiEyesSite: "Kimi Eyes 插件站",
|
||||||
referenceProject: "引用项目",
|
referenceProject: "引用项目",
|
||||||
|
|
||||||
// Validation errors
|
// Validation errors
|
||||||
@@ -311,6 +315,7 @@ export const zhTranslations = {
|
|||||||
colCacheRead: "缓存读",
|
colCacheRead: "缓存读",
|
||||||
unitTimes: "次",
|
unitTimes: "次",
|
||||||
estimate: "估算",
|
estimate: "估算",
|
||||||
|
subagentModel: "子代理模型",
|
||||||
collapse: "收起",
|
collapse: "收起",
|
||||||
expandAll: "展开全部 ({n})",
|
expandAll: "展开全部 ({n})",
|
||||||
|
|
||||||
@@ -438,6 +443,36 @@ export const zhTranslations = {
|
|||||||
trendLineShowRequests: "显示请求数",
|
trendLineShowRequests: "显示请求数",
|
||||||
trendLineTooltip: "{date}\nToken: {tokens}\n命中率: {cache}\n请求: {req}",
|
trendLineTooltip: "{date}\nToken: {tokens}\n命中率: {cache}\n请求: {req}",
|
||||||
trendLineNoData: "暂无数据",
|
trendLineNoData: "暂无数据",
|
||||||
|
|
||||||
|
// Subagent settings page (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:
|
||||||
|
"优先级:工具显式 model 参数 > 子代理 profile 的 model_preference > 本配置 > 继承主模型",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type TranslationKey = keyof typeof zhTranslations;
|
export type TranslationKey = keyof typeof zhTranslations;
|
||||||
+9321
-5001
File diff suppressed because it is too large.
Load diff
+7715
-3883
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
|||||||
|
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 secondary model
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 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.model === "string" && cfg.model !== "") out.model = cfg.model;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write `[secondary_model]` with only the `model` field — no patch fields.
|
||||||
|
* Subagents then bind the pointed model entry directly and inherit its
|
||||||
|
* settings (context size, capabilities, effort fallback), which also keeps
|
||||||
|
* usage records keyed on the real model alias instead of the synthesized
|
||||||
|
* `__secondary__` derived entry. Unknown fields already present in the
|
||||||
|
* section are preserved; the known patch fields (`default_effort`,
|
||||||
|
* `max_output_size`, `max_context_size`) are dropped so stale patches are
|
||||||
|
* cleaned up when the model is re-picked.
|
||||||
|
*/
|
||||||
|
export function setSecondaryModelOnly(
|
||||||
|
rawOther: unknown,
|
||||||
|
alias: string
|
||||||
|
): unknown {
|
||||||
|
const root = { ...asRecord(rawOther) };
|
||||||
|
const section = asRecord(asRecord(rawOther)["secondary_model"]);
|
||||||
|
const next: Record<string, unknown> = { model: alias };
|
||||||
|
const knownFields: ReadonlySet<string> = new Set([
|
||||||
|
"model",
|
||||||
|
"default_effort",
|
||||||
|
"max_output_size",
|
||||||
|
"max_context_size",
|
||||||
|
]);
|
||||||
|
for (const [k, v] of Object.entries(section)) {
|
||||||
|
if (!knownFields.has(k)) next[k] = v;
|
||||||
|
}
|
||||||
|
root.secondary_model = next;
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove `[secondary_model]` entirely (the "not configured" option). */
|
||||||
|
export function clearSecondaryModel(rawOther: unknown): unknown {
|
||||||
|
const root = { ...asRecord(rawOther) };
|
||||||
|
delete root.secondary_model;
|
||||||
|
return root;
|
||||||
|
}
|
||||||
@@ -24,6 +24,8 @@ export interface ModelRow extends TotalsRow {
|
|||||||
modelResolved: string;
|
modelResolved: string;
|
||||||
priceId: string;
|
priceId: string;
|
||||||
costEstimated: boolean;
|
costEstimated: boolean;
|
||||||
|
/** True when any record in this row came from a subagent (secondary-model) request. */
|
||||||
|
isSecondary: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RecentRow {
|
export interface RecentRow {
|
||||||
@@ -40,6 +42,8 @@ export interface RecentRow {
|
|||||||
costEstimated: boolean;
|
costEstimated: boolean;
|
||||||
priceId: string;
|
priceId: string;
|
||||||
fromEnv: boolean;
|
fromEnv: boolean;
|
||||||
|
/** True when this request came from a subagent (secondary-model) call. */
|
||||||
|
isSecondary: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RangeStats {
|
export interface RangeStats {
|
||||||
|
|||||||
@@ -127,3 +127,19 @@ export interface AgentSettings {
|
|||||||
permission?: { rules?: PermissionRule[] };
|
permission?: { rules?: PermissionRule[] };
|
||||||
hooks?: Hook[];
|
hooks?: Hook[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kimi Code `[secondary_model]` section of config.toml: the secondary model
|
||||||
|
* bound to newly spawned subagents (experimental feature).
|
||||||
|
* `model` points at an alias defined in `[models]`; the remaining fields are
|
||||||
|
* a patch applied on top of the referenced entry (subagents only).
|
||||||
|
*/
|
||||||
|
export interface SecondaryModelConfig {
|
||||||
|
model?: string;
|
||||||
|
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
-4
@@ -13,7 +13,7 @@
|
|||||||
/>
|
/>
|
||||||
<meta
|
<meta
|
||||||
name="keywords"
|
name="keywords"
|
||||||
content="KimiSwitch, KimiCodeSwitch, SwitchKimi, Kimi Code Switch, Kimi 切换, LLM 供应商管理, AI 供应商切换, 多 LLM 管理, Kimi 用量监控, 智谱 GLM, MiniMax, DeepSeek, OpenRouter, 基元律动, 用量查询, 账单监控, Token 套餐, Claude, GPT, Windows LLM 桌面工具"
|
content="Kimi Switch, KimiSwitch, KimiCode Switch, KimiCodeSwitch, SwitchKimi, Kimi Code Switch, Kimi 切换, LLM 供应商管理, AI 供应商切换, 多 LLM 管理, Kimi 用量监控, 智谱 GLM, MiniMax, DeepSeek, OpenRouter, 基元律动, 用量查询, 账单监控, Token 套餐, Claude, GPT, Windows LLM 桌面工具"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- Open Graph -->
|
<!-- Open Graph -->
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
||||||
/>
|
/>
|
||||||
<meta property="og:url" content="https://billowliu2.github.io/KimiSwitch/" />
|
<meta property="og:url" content="https://billowliu2.github.io/KimiSwitch/" />
|
||||||
<meta property="og:image" content="%BASE_URL%og.png" />
|
<meta property="og:image" content="https://billowliu2.github.io/KimiSwitch/og.png" />
|
||||||
|
|
||||||
<!-- Twitter -->
|
<!-- Twitter -->
|
||||||
<meta name="twitter:card" content="summary_large_image" />
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
name="twitter:description"
|
name="twitter:description"
|
||||||
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
content="一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek 等供应商,用量与账单一目了然,开源 MIT。"
|
||||||
/>
|
/>
|
||||||
<meta name="twitter:image" content="%BASE_URL%og.png" />
|
<meta name="twitter:image" content="https://billowliu2.github.io/KimiSwitch/og.png" />
|
||||||
|
|
||||||
<!-- Canonical -->
|
<!-- Canonical -->
|
||||||
<link rel="canonical" href="https://billowliu2.github.io/KimiSwitch/" />
|
<link rel="canonical" href="https://billowliu2.github.io/KimiSwitch/" />
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
{
|
{
|
||||||
"@type": "SoftwareApplication",
|
"@type": "SoftwareApplication",
|
||||||
"name": "Kimi Switch",
|
"name": "Kimi Switch",
|
||||||
"alternateName": ["KimiSwitch", "KimiCodeSwitch"],
|
"alternateName": ["KimiSwitch", "KimiCodeSwitch", "Kimi Switch", "KimiCode Switch"],
|
||||||
"url": "https://billowliu2.github.io/KimiSwitch/",
|
"url": "https://billowliu2.github.io/KimiSwitch/",
|
||||||
"applicationCategory": "DeveloperApplication",
|
"applicationCategory": "DeveloperApplication",
|
||||||
"operatingSystem": "Windows 10, Windows 11",
|
"operatingSystem": "Windows 10, Windows 11",
|
||||||
|
|||||||
Generated
+18
@@ -16,6 +16,7 @@
|
|||||||
"react-router-dom": "^7.18.2"
|
"react-router-dom": "^7.18.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^26.1.2",
|
||||||
"@types/react": "^18.3.3",
|
"@types/react": "^18.3.3",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
"@vitejs/plugin-react": "^4.3.1",
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
@@ -1299,6 +1300,16 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "26.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz",
|
||||||
|
"integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~8.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/prop-types": {
|
"node_modules/@types/prop-types": {
|
||||||
"version": "15.7.15",
|
"version": "15.7.15",
|
||||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||||
@@ -2723,6 +2734,13 @@
|
|||||||
"node": ">=14.17"
|
"node": ">=14.17"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "8.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
||||||
|
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/update-browserslist-db": {
|
"node_modules/update-browserslist-db": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
"react-router-dom": "^7.18.2"
|
"react-router-dom": "^7.18.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^26.1.2",
|
||||||
"@types/react": "^18.3.3",
|
"@types/react": "^18.3.3",
|
||||||
"@types/react-dom": "^18.3.0",
|
"@types/react-dom": "^18.3.0",
|
||||||
"@vitejs/plugin-react": "^4.3.1",
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#0F62FE"><path d="M12 2L4 6v6c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V6l-8-4zm0 4l4 2v4c0 3-1.5 5-4 6-2.5-1-4-3-4-6V8l4-2z"/></svg>
|
|
||||||
|
Before Width: | Height: | Size: 192 B |
@@ -6,27 +6,17 @@
|
|||||||
<priority>1.0</priority>
|
<priority>1.0</priority>
|
||||||
</url>
|
</url>
|
||||||
<url>
|
<url>
|
||||||
<loc>https://billowliu2.github.io/KimiSwitch/#/features</loc>
|
<loc>https://billowliu2.github.io/KimiSwitch/features</loc>
|
||||||
<changefreq>monthly</changefreq>
|
<changefreq>monthly</changefreq>
|
||||||
<priority>0.8</priority>
|
<priority>0.8</priority>
|
||||||
</url>
|
</url>
|
||||||
<url>
|
<url>
|
||||||
<loc>https://billowliu2.github.io/KimiSwitch/#/showcase</loc>
|
<loc>https://billowliu2.github.io/KimiSwitch/changelog</loc>
|
||||||
<changefreq>monthly</changefreq>
|
|
||||||
<priority>0.8</priority>
|
|
||||||
</url>
|
|
||||||
<url>
|
|
||||||
<loc>https://billowliu2.github.io/KimiSwitch/#/performance</loc>
|
|
||||||
<changefreq>monthly</changefreq>
|
|
||||||
<priority>0.7</priority>
|
|
||||||
</url>
|
|
||||||
<url>
|
|
||||||
<loc>https://billowliu2.github.io/KimiSwitch/#/changelog</loc>
|
|
||||||
<changefreq>weekly</changefreq>
|
<changefreq>weekly</changefreq>
|
||||||
<priority>0.7</priority>
|
<priority>0.7</priority>
|
||||||
</url>
|
</url>
|
||||||
<url>
|
<url>
|
||||||
<loc>https://billowliu2.github.io/KimiSwitch/#/download</loc>
|
<loc>https://billowliu2.github.io/KimiSwitch/download</loc>
|
||||||
<changefreq>weekly</changefreq>
|
<changefreq>weekly</changefreq>
|
||||||
<priority>0.9</priority>
|
<priority>0.9</priority>
|
||||||
</url>
|
</url>
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ import Download from "./sections/Download";
|
|||||||
import Privacy from "./sections/Privacy";
|
import Privacy from "./sections/Privacy";
|
||||||
import CTA from "./sections/CTA";
|
import CTA from "./sections/CTA";
|
||||||
import Footer from "./components/Footer";
|
import Footer from "./components/Footer";
|
||||||
|
import { useLang, type Dict } from "./i18n";
|
||||||
|
|
||||||
|
const SITE_URL = "https://billowliu2.github.io/KimiSwitch";
|
||||||
|
type SeoKey = keyof Dict["seo"];
|
||||||
|
|
||||||
function ScrollToTop() {
|
function ScrollToTop() {
|
||||||
const { pathname } = useLocation();
|
const { pathname } = useLocation();
|
||||||
@@ -17,6 +21,47 @@ function ScrollToTop() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Update per-page title / description / OG / canonical for SEO. */
|
||||||
|
function RouteMeta() {
|
||||||
|
const { pathname } = useLocation();
|
||||||
|
const { t } = useLang();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const page = pathname.replace(/\/+$/, "");
|
||||||
|
const seoKey: SeoKey =
|
||||||
|
page === "/features" || page === "/changelog" || page === "/download"
|
||||||
|
? (page.slice(1) as SeoKey)
|
||||||
|
: "home";
|
||||||
|
const m = t.seo[seoKey];
|
||||||
|
const url = `${SITE_URL}${page === "" ? "/" : page}`;
|
||||||
|
|
||||||
|
document.title = m.title;
|
||||||
|
setMeta("name", "description", m.description);
|
||||||
|
setMeta("property", "og:title", m.title);
|
||||||
|
setMeta("property", "og:description", m.description);
|
||||||
|
setMeta("property", "og:url", url);
|
||||||
|
setMeta("name", "twitter:title", m.title);
|
||||||
|
setMeta("name", "twitter:description", m.description);
|
||||||
|
|
||||||
|
const canon = document.querySelector('link[rel="canonical"]');
|
||||||
|
if (canon) canon.setAttribute("href", url);
|
||||||
|
}, [pathname, t]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMeta(attr: "name" | "property", key: string, content: string) {
|
||||||
|
let el = document.head.querySelector<HTMLMetaElement>(
|
||||||
|
`meta[${attr}="${key}"]`,
|
||||||
|
);
|
||||||
|
if (!el) {
|
||||||
|
el = document.createElement("meta");
|
||||||
|
el.setAttribute(attr, key);
|
||||||
|
document.head.appendChild(el);
|
||||||
|
}
|
||||||
|
el.setAttribute("content", content);
|
||||||
|
}
|
||||||
|
|
||||||
const homePage = (
|
const homePage = (
|
||||||
<>
|
<>
|
||||||
<Hero />
|
<Hero />
|
||||||
@@ -30,6 +75,7 @@ export default function App() {
|
|||||||
<Nav />
|
<Nav />
|
||||||
<main className="flex-1">
|
<main className="flex-1">
|
||||||
<ScrollToTop />
|
<ScrollToTop />
|
||||||
|
<RouteMeta />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={homePage} />
|
<Route path="/" element={homePage} />
|
||||||
<Route
|
<Route
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { asset } from "../lib/asset";
|
|||||||
/** Map recommendLink.name → logo file in public/logos (only when we have one). */
|
/** Map recommendLink.name → logo file in public/logos (only when we have one). */
|
||||||
const logoFor: Record<string, string> = {
|
const logoFor: Record<string, string> = {
|
||||||
"Kimi": "logos/kimi.svg",
|
"Kimi": "logos/kimi.svg",
|
||||||
"智谱 GLM": "logos/glm.svg",
|
"智谱 GLM": "logos/zhipu.svg",
|
||||||
"DeepSeek": "logos/deepseek.svg",
|
"DeepSeek": "logos/deepseek.svg",
|
||||||
"OpenCodeGo": "logos/opencode.svg",
|
"OpenCodeGo": "logos/opencode.svg",
|
||||||
"MiniMax": "logos/minimax.svg",
|
"MiniMax": "logos/minimax.svg",
|
||||||
|
|||||||
+113
-9
@@ -16,10 +16,10 @@ const zh = {
|
|||||||
performance: "性能",
|
performance: "性能",
|
||||||
changelog: "更新日志",
|
changelog: "更新日志",
|
||||||
download: "下载",
|
download: "下载",
|
||||||
downloadBtn: "下载 v0.6.7",
|
downloadBtn: "下载 v0.7.0",
|
||||||
},
|
},
|
||||||
hero: {
|
hero: {
|
||||||
badge: "开源 MIT · Windows 10 / 11",
|
badge: "v0.7.0 · 开源 MIT · Windows / macOS / Linux",
|
||||||
titleBefore: "统一管理你的",
|
titleBefore: "统一管理你的",
|
||||||
titleAccent: "AI 供应商",
|
titleAccent: "AI 供应商",
|
||||||
titleAfter: "",
|
titleAfter: "",
|
||||||
@@ -141,11 +141,37 @@ const zh = {
|
|||||||
fallbackNote: "内置版本记录",
|
fallbackNote: "内置版本记录",
|
||||||
entries: [
|
entries: [
|
||||||
{
|
{
|
||||||
version: "v0.6.7",
|
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",
|
date: "2026-08-01",
|
||||||
items: [
|
items: [
|
||||||
"应用内置 Kimi 设备授权登录(等同 kimi login),浏览器授权即用,过期自动续期",
|
"最近请求新增缓存命中率列,每次请求命中一目了然",
|
||||||
"外链打开统一走 Rust 命令,修复部分链接无法跳转",
|
"中文模式费用按最新汇率换算人民币(¥)显示,英文模式保持美元",
|
||||||
|
"仪表盘性能再优化:价格解析记忆化缓存,扫描从秒级降到百毫秒级;右上角新增加载耗时/数据量跟踪",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
version: "v0.6.8",
|
||||||
|
date: "2026-08-01",
|
||||||
|
items: [
|
||||||
|
"仪表盘加载提速:models.dev 快照移出主 bundle,异步加载不阻塞首帧",
|
||||||
|
"Rust 价格索引启动时后台预热;get_summary 扫描结果 8 秒缓存",
|
||||||
|
"k3-256k 按 k3 牌价计费",
|
||||||
|
"官网更新:Kimi 风格重设计、中英文切换、更新日志同步 GitHub Releases、三平台下载",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -234,7 +260,7 @@ const zh = {
|
|||||||
},
|
},
|
||||||
download: {
|
download: {
|
||||||
title: "下载 Kimi Switch",
|
title: "下载 Kimi Switch",
|
||||||
subtitle: "当前版本 v0.6.7 · Windows 10 / 11 主推,macOS 与 Linux 路线图上。",
|
subtitle: "当前版本 v0.7.0 · Windows / macOS / Linux 三平台已发布",
|
||||||
autoUpdate: "应用内置自动检测更新,新版本发布后在设置页一键升级。",
|
autoUpdate: "应用内置自动检测更新,新版本发布后在设置页一键升级。",
|
||||||
ready: "已发布",
|
ready: "已发布",
|
||||||
wip: "开发中",
|
wip: "开发中",
|
||||||
@@ -252,6 +278,28 @@ const zh = {
|
|||||||
download: "免费下载",
|
download: "免费下载",
|
||||||
source: "GitHub 源码",
|
source: "GitHub 源码",
|
||||||
},
|
},
|
||||||
|
seo: {
|
||||||
|
home: {
|
||||||
|
title: "Kimi Switch — 多 LLM 供应商统一管理 · 用量监控 · 账单一目了然",
|
||||||
|
description:
|
||||||
|
"Kimi Switch / KimiCodeSwitch — Windows 桌面端多 LLM 供应商统一管理器,一键切换 Kimi / 智谱 GLM / MiniMax / DeepSeek / OpenRouter / 基元律动,用量账单实时监控,开源 MIT。",
|
||||||
|
},
|
||||||
|
features: {
|
||||||
|
title: "核心功能 - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"Kimi Switch 核心功能:多供应商管理、用量与账单监控、Kimi 一键授权登录、智能模型发现与自动更新,22 个预设开箱即用。",
|
||||||
|
},
|
||||||
|
changelog: {
|
||||||
|
title: "更新日志 - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"Kimi Switch 更新日志:每个版本的重要变更记录,同步自 GitHub Releases。",
|
||||||
|
},
|
||||||
|
download: {
|
||||||
|
title: "下载 - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"下载 Kimi Switch:Windows .msi、macOS .dmg、Linux .deb / .AppImage / .rpm,免费开源 MIT。",
|
||||||
|
},
|
||||||
|
},
|
||||||
footer: {
|
footer: {
|
||||||
recommend: "推荐供应商",
|
recommend: "推荐供应商",
|
||||||
mirror: "国内镜像",
|
mirror: "国内镜像",
|
||||||
@@ -280,10 +328,10 @@ const en: Dict = {
|
|||||||
performance: "Performance",
|
performance: "Performance",
|
||||||
changelog: "Changelog",
|
changelog: "Changelog",
|
||||||
download: "Download",
|
download: "Download",
|
||||||
downloadBtn: "Download v0.6.7",
|
downloadBtn: "Download v0.7.0",
|
||||||
},
|
},
|
||||||
hero: {
|
hero: {
|
||||||
badge: "Open source MIT · Windows 10 / 11",
|
badge: "v0.7.0 · Open source MIT · Windows / macOS / Linux",
|
||||||
titleBefore: "One app for all your ",
|
titleBefore: "One app for all your ",
|
||||||
titleAccent: "AI providers",
|
titleAccent: "AI providers",
|
||||||
titleAfter: "",
|
titleAfter: "",
|
||||||
@@ -404,6 +452,40 @@ const en: Dict = {
|
|||||||
syncedNote: "Synced from GitHub Releases",
|
syncedNote: "Synced from GitHub Releases",
|
||||||
fallbackNote: "Built-in release notes",
|
fallbackNote: "Built-in release notes",
|
||||||
entries: [
|
entries: [
|
||||||
|
{
|
||||||
|
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",
|
||||||
|
items: [
|
||||||
|
"Recent requests gain a cache-hit-rate column, per request at a glance",
|
||||||
|
"Chinese UI now shows costs in CNY (latest exchange rate); English keeps USD",
|
||||||
|
"Dashboard speedup: memoized price resolution drops the scan from seconds to milliseconds; load time / payload tracking in the top-right corner",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
version: "v0.6.8",
|
||||||
|
date: "2026-08-01",
|
||||||
|
items: [
|
||||||
|
"Dashboard speedup: models.dev snapshot moved out of the main bundle, async load without blocking first paint",
|
||||||
|
"Rust price index warmed in the background at startup; get_summary scan cached for 8s",
|
||||||
|
"k3-256k billed at the k3 list price",
|
||||||
|
"Website refresh: Kimi-style redesign, zh/en switch, changelog synced from GitHub Releases, downloads for all three platforms",
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
version: "v0.6.7",
|
version: "v0.6.7",
|
||||||
date: "2026-08-01",
|
date: "2026-08-01",
|
||||||
@@ -498,7 +580,7 @@ const en: Dict = {
|
|||||||
},
|
},
|
||||||
download: {
|
download: {
|
||||||
title: "Download Kimi Switch",
|
title: "Download Kimi Switch",
|
||||||
subtitle: "Current version v0.6.7 · Windows 10 / 11 first, macOS and Linux on the roadmap.",
|
subtitle: "Current version v0.7.0 · Windows, macOS and Linux now released",
|
||||||
autoUpdate: "Built-in update detection: upgrade in one click from Settings when a new version ships.",
|
autoUpdate: "Built-in update detection: upgrade in one click from Settings when a new version ships.",
|
||||||
ready: "Available",
|
ready: "Available",
|
||||||
wip: "In development",
|
wip: "In development",
|
||||||
@@ -516,6 +598,28 @@ const en: Dict = {
|
|||||||
download: "Free Download",
|
download: "Free Download",
|
||||||
source: "GitHub Source",
|
source: "GitHub Source",
|
||||||
},
|
},
|
||||||
|
seo: {
|
||||||
|
home: {
|
||||||
|
title: "Kimi Switch — Unified Management for AI Providers · Usage & Billing",
|
||||||
|
description:
|
||||||
|
"Kimi Switch / KimiCodeSwitch — a Windows desktop manager for multiple LLM providers. Switch between Kimi, Zhipu GLM, MiniMax, DeepSeek, OpenRouter and TokenRhythm in one click, with usage and billing at a glance. Open source MIT.",
|
||||||
|
},
|
||||||
|
features: {
|
||||||
|
title: "Core Features - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"Kimi Switch core features: multi-provider management, usage & billing, one-click Kimi login, smart model discovery and auto updates. 22 presets out of the box.",
|
||||||
|
},
|
||||||
|
changelog: {
|
||||||
|
title: "Changelog - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"Kimi Switch changelog: notable changes in every release, synced from GitHub Releases.",
|
||||||
|
},
|
||||||
|
download: {
|
||||||
|
title: "Download - Kimi Switch",
|
||||||
|
description:
|
||||||
|
"Download Kimi Switch: Windows .msi, macOS .dmg, Linux .deb / .AppImage / .rpm. Free and open source under MIT.",
|
||||||
|
},
|
||||||
|
},
|
||||||
footer: {
|
footer: {
|
||||||
recommend: "Recommended Providers",
|
recommend: "Recommended Providers",
|
||||||
mirror: "China mirror",
|
mirror: "China mirror",
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
import { StrictMode } from "react";
|
import { StrictMode } from "react";
|
||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
import { HashRouter } from "react-router-dom";
|
import { BrowserRouter } from "react-router-dom";
|
||||||
import { LangProvider } from "./i18n";
|
import { LangProvider } from "./i18n";
|
||||||
import App from "./App";
|
import App from "./App";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
createRoot(document.getElementById("root")!).render(
|
createRoot(document.getElementById("root")!).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<HashRouter>
|
<BrowserRouter basename="/KimiSwitch">
|
||||||
<LangProvider>
|
<LangProvider>
|
||||||
<App />
|
<App />
|
||||||
</LangProvider>
|
</LangProvider>
|
||||||
</HashRouter>
|
</BrowserRouter>
|
||||||
</StrictMode>,
|
</StrictMode>,
|
||||||
);
|
);
|
||||||
@@ -10,9 +10,14 @@ interface ChangelogEntry {
|
|||||||
|
|
||||||
const API_URL =
|
const API_URL =
|
||||||
"https://api.github.com/repos/billowliu2/KimiSwitch/releases?per_page=20";
|
"https://api.github.com/repos/billowliu2/KimiSwitch/releases?per_page=20";
|
||||||
const CACHE_KEY = "kimi-switch-changelog";
|
|
||||||
const CACHE_TTL = 60 * 60 * 1000; // 1 hour
|
const CACHE_TTL = 60 * 60 * 1000; // 1 hour
|
||||||
|
|
||||||
|
/** Cache key is versioned by the newest embedded release so redeploys
|
||||||
|
* invalidate stale caches in the browser immediately. */
|
||||||
|
function cacheKey(embedded: ChangelogEntry[]) {
|
||||||
|
return `kimi-switch-changelog-${embedded[0]?.version ?? "v1"}`;
|
||||||
|
}
|
||||||
|
|
||||||
/** Parse a GitHub release body into bullet items. */
|
/** Parse a GitHub release body into bullet items. */
|
||||||
function parseBody(body: string): string[] {
|
function parseBody(body: string): string[] {
|
||||||
return body
|
return body
|
||||||
@@ -36,9 +41,9 @@ async function fetchReleases(): Promise<ChangelogEntry[]> {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
function readCache(): ChangelogEntry[] | null {
|
function readCache(embedded: ChangelogEntry[]): ChangelogEntry[] | null {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(CACHE_KEY);
|
const raw = localStorage.getItem(cacheKey(embedded));
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
const { ts, data } = JSON.parse(raw) as { ts: number; data: ChangelogEntry[] };
|
const { ts, data } = JSON.parse(raw) as { ts: number; data: ChangelogEntry[] };
|
||||||
if (Date.now() - ts > CACHE_TTL) return null;
|
if (Date.now() - ts > CACHE_TTL) return null;
|
||||||
@@ -48,10 +53,10 @@ function readCache(): ChangelogEntry[] | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeCache(data: ChangelogEntry[]) {
|
function writeCache(data: ChangelogEntry[], embedded: ChangelogEntry[]) {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
CACHE_KEY,
|
cacheKey(embedded),
|
||||||
JSON.stringify({ ts: Date.now(), data }),
|
JSON.stringify({ ts: Date.now(), data }),
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -67,7 +72,7 @@ export default function Changelog() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const cached = readCache();
|
const cached = readCache(embedded);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
setRemote(cached);
|
setRemote(cached);
|
||||||
setSynced(true);
|
setSynced(true);
|
||||||
@@ -78,7 +83,7 @@ export default function Changelog() {
|
|||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
setRemote(data);
|
setRemote(data);
|
||||||
setSynced(true);
|
setSynced(true);
|
||||||
writeCache(data);
|
writeCache(data, embedded);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
/* 网络不通时使用内置列表兜底 */
|
/* 网络不通时使用内置列表兜底 */
|
||||||
|
|||||||
@@ -8,25 +8,25 @@ const icons: Record<string, Icon> = {
|
|||||||
linux: LinuxLogo,
|
linux: LinuxLogo,
|
||||||
};
|
};
|
||||||
|
|
||||||
const VERSION = "0.6.8";
|
const VERSION = "0.7.0";
|
||||||
const GITHUB = "https://github.com/billowliu2/KimiSwitch";
|
const GITHUB = "https://github.com/billowliu2/KimiSwitch";
|
||||||
const MIRROR_RELEASES = "https://git.codingplan.site/admin/KimiCodeSwitch/releases";
|
const MIRROR_RELEASES = "https://git.codingplan.site/admin/KimiCodeSwitch/releases";
|
||||||
const dl = (file: string) => `${GITHUB}/releases/download/v${VERSION}/${file}`;
|
const dl = (file: string) => `${GITHUB}/releases/download/v${VERSION}/${file}`;
|
||||||
|
|
||||||
/** Per-platform download assets for the current release (names match the CI
|
/** Per-platform download assets for the current release (names match the CI
|
||||||
* release workflow, e.g. Kimi.Switch_0.6.8_x64_en-US.msi). */
|
* release workflow, e.g. Kimi.Switch_0.7.0_x64_en-US.msi). */
|
||||||
const assets: Record<string, { label: string; href: string }[]> = {
|
const assets: Record<string, { label: string; href: string }[]> = {
|
||||||
windows: [
|
windows: [
|
||||||
{ label: "MSI", href: dl("Kimi.Switch_0.6.8_x64_en-US.msi") },
|
{ label: "MSI", href: dl("Kimi.Switch_0.7.0_x64_en-US.msi") },
|
||||||
{ label: "镜像", href: MIRROR_RELEASES },
|
{ label: "镜像", href: MIRROR_RELEASES },
|
||||||
],
|
],
|
||||||
macos: [
|
macos: [
|
||||||
{ label: "Apple Silicon (.dmg)", href: dl("Kimi.Switch_0.6.8_aarch64.dmg") },
|
{ label: "Apple Silicon (.dmg)", href: dl("Kimi.Switch_0.7.0_aarch64.dmg") },
|
||||||
],
|
],
|
||||||
linux: [
|
linux: [
|
||||||
{ label: ".deb", href: dl("Kimi.Switch_0.6.8_amd64.deb") },
|
{ label: ".deb", href: dl("Kimi.Switch_0.7.0_amd64.deb") },
|
||||||
{ label: ".AppImage", href: dl("Kimi.Switch_0.6.8_amd64.AppImage") },
|
{ label: ".AppImage", href: dl("Kimi.Switch_0.7.0_amd64.AppImage") },
|
||||||
{ label: ".rpm", href: dl("Kimi.Switch-0.6.8-1.x86_64.rpm") },
|
{ label: ".rpm", href: dl("Kimi.Switch-0.7.0-1.x86_64.rpm") },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+22
-3
@@ -1,11 +1,30 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig, type Plugin } from "vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
|
import { copyFileSync } from "node:fs";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHub Pages SPA fallback: any deep path (e.g. /KimiSwitch/features) is
|
||||||
|
* served by 404.html; duplicating the built index.html there lets the
|
||||||
|
* BrowserRouter boot and render the right route. This keeps every page
|
||||||
|
* indexable as a real URL instead of a `#/` fragment.
|
||||||
|
*/
|
||||||
|
function generate404(): Plugin {
|
||||||
|
return {
|
||||||
|
name: "generate-404",
|
||||||
|
apply: "build",
|
||||||
|
closeBundle() {
|
||||||
|
const dist = fileURLToPath(new URL("./dist", import.meta.url));
|
||||||
|
copyFileSync(`${dist}/index.html`, `${dist}/404.html`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// GitHub Pages subpath: billowliu2.github.io/KimiSwitch/
|
// GitHub Pages subpath: billowliu2.github.io/KimiSwitch/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
base: "/KimiSwitch/",
|
base: "/KimiSwitch/",
|
||||||
plugins: [react()],
|
plugins: [react(), generate404()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: { "@": "/src" },
|
alias: { "@": "/src" },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user