diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 181b68a9..d46de7f4 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2220,6 +2220,10 @@ pub struct SessionView { /// 没有拿到用量、所以算不出钱的轮数 #[serde(default)] pub no_usage_turns: u64, + /// 由订阅制上游服务的轮数:计入订阅额度,**没有金额,也不是「无法计价」**。 + /// 和上面三个数互不相交,和概览的 `subscription_requests` 数的是同一类请求。 + /// 少了它,全走订阅的会话和一轮都算不出钱的会话在这里长得一模一样 + pub subscription_turns: u64, pub input_tokens: i64, pub output_tokens: i64, pub cache_read_tokens: i64, @@ -2253,6 +2257,10 @@ pub struct TurnView { /// 估算的金额在瀑布图上和实测的长得一模一样 #[serde(default)] pub cost_estimated: bool, + /// 服务它的那家怎么收钱,和 `HistoryRow::billing` 同一套词:`per-token` / + /// `subscription` / `free` / `unknown`。**订阅制那一轮的 `cost_micros` 也是 + /// None**,只看金额分不出它和「无法计价」 + pub billing: String, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 2d9d939b..8f302541 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -1279,6 +1279,7 @@ fn session_view(s: &tw_store::db::SessionRow) -> tw_api::SessionView { priced_turns: s.priced_turns as u64, unpriced_turns: s.unpriced_turns as u64, no_usage_turns: s.no_usage_turns as u64, + subscription_turns: s.subscription_turns as u64, input_tokens: s.input_tokens, output_tokens: s.output_tokens, cache_read_tokens: s.cache_read_tokens, @@ -1309,6 +1310,7 @@ fn turn_view(t: &tw_store::db::TurnRow) -> tw_api::TurnView { error: t.error.clone(), cancelled: t.cancelled, cost_estimated: t.cost_estimated, + billing: t.billing.clone(), } } diff --git a/crates/tw-control/tests/sessions.rs b/crates/tw-control/tests/sessions.rs new file mode 100644 index 00000000..4bb51141 --- /dev/null +++ b/crates/tw-control/tests/sessions.rs @@ -0,0 +1,131 @@ +//! 会话端点的形状。 +//! +//! 各种轮次怎么数在 tw-store 里测;这里盯的是**界面拿到的那份 JSON**。 +//! 订阅那几轮要作为一个数、每一轮的计费方式要作为一个字段送到界面 —— +//! 否则界面手里只有「没有金额」,只能把订阅说成「无法计价」。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +const BASE: &str = "version: 1\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n"; + +/// 一轮 Codex 的请求。按 token 计费的那一轮带着金额,订阅制的没有。 +fn turn(id: i64, billing: &str) -> tw_store::db::RequestRow { + let per_token = billing == "per-token"; + tw_store::db::RequestRow { + id, + at_ms: 1000 + id, + client: "codex".into(), + client_hint: None, + session: Some("s1".into()), + tool_calls: None, + flagged: None, + redacted: None, + provider: if per_token { "官方" } else { "ChatGPT" }.into(), + model: "gpt-5-codex".into(), + path: "/v1/responses".into(), + status: Some(200), + ttfb_ms: Some(100), + duration_ms: Some(200), + bytes: Some(10), + input_tokens: Some(50), + output_tokens: Some(20), + cache_read_tokens: None, + cache_write_tokens: None, + cost_micros: per_token.then_some(1_000), + cost_estimated: false, + error: None, + local: false, + cancelled: false, + routing: None, + billing: billing.into(), + cache_saved_micros: None, + price_source: None, + translated: None, + } +} + +fn app(rows: &[tw_store::db::RequestRow]) -> (tempfile::TempDir, axum::Router) { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, BASE).unwrap(); + let db = tw_store::Db::open(&d.path().join("data.db")).unwrap(); + for r in rows { + db.insert(r).unwrap(); + } + let rec = tw_store::Recorder::new( + db, + tw_store::Blobs::new(d.path().join("blobs")), + tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()), + ); + let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + gateway_addr: None, + store: Some(Arc::new(tokio::sync::Mutex::new(rec))), + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + home: d.path().join("home"), + }; + (d, tw_control::router(state)) +} + +async fn get(app: &axum::Router, path: &str) -> serde_json::Value { + let r = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::OK, "{path}"); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + serde_json::from_slice(&b).unwrap() +} + +/// 报这个问题的那种会话:Codex 走 ChatGPT 账号,一轮按量计费的都没有。 +/// **界面要能说「订阅额度 2 轮」,而不是「无法计价」。** +#[tokio::test] +async fn a_session_served_by_a_subscription_says_so_rather_than_looking_unpriced() { + let (_d, app) = app(&[turn(1, "subscription"), turn(2, "subscription")]); + + let list = get(&app, "/sessions").await; + let s = &list[0]; + assert_eq!(s["priced_turns"], 0); + assert_eq!(s["unpriced_turns"], 0); + assert_eq!(s["no_usage_turns"], 0); + assert_eq!(s["subscription_turns"], 2, "{s}"); + + let detail = get(&app, "/sessions/s1").await; + assert_eq!(detail["session"]["subscription_turns"], 2); + for t in detail["turns"].as_array().unwrap() { + assert_eq!(t["cost_micros"], serde_json::Value::Null); + assert_eq!(t["billing"], "subscription", "{t}"); + } +} + +/// 混着走的会话:金额只合计按量计费的那一轮,订阅那一轮单独数。 +#[tokio::test] +async fn a_mixed_session_keeps_the_money_and_the_subscription_apart() { + let (_d, app) = app(&[turn(1, "per-token"), turn(2, "subscription")]); + + let s = &get(&app, "/sessions").await[0]; + assert_eq!(s["cost_micros"], 1_000); + assert_eq!(s["priced_turns"], 1); + assert_eq!(s["subscription_turns"], 1); + + let detail = get(&app, "/sessions/s1").await; + let billing: Vec<_> = detail["turns"] + .as_array() + .unwrap() + .iter() + .map(|t| t["billing"].as_str().unwrap()) + .collect(); + assert_eq!(billing, ["per-token", "subscription"]); +} diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index b50cd2f2..ebd8812b 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -39,6 +39,13 @@ const NO_PRICE: &str = "(cost_micros IS NULL AND input_tokens IS NOT NULL \ const NO_USAGE: &str = "(cost_micros IS NULL AND input_tokens IS NULL AND error IS NULL \ AND billing IN ('', 'per-token') AND (cancelled = 1 OR status < 300))"; +/// 这一行由订阅制上游服务:**没有金额,但不是缺了什么** —— 这笔账按订阅额度 +/// 算,不按用量算。和上面两种都不相交(那两种只数按 token 计费的)。 +/// +/// **概览和会话都用它。**概览上的「订阅额度 N 次」和会话里的订阅轮数数的是 +/// 同一批行,两处各写一遍迟早会数得不一样 —— 上面那两个常量就是这么来的。 +const SUBSCRIPTION: &str = "(billing = 'subscription')"; + #[derive(Debug, thiserror::Error)] pub enum DbError { #[error("无法打开 {path}:{source}")] @@ -412,6 +419,10 @@ pub struct SessionRow { pub unpriced_turns: i64, /// 没有拿到用量、所以算不出钱的轮数(见 `NO_USAGE`) pub no_usage_turns: i64, + /// 由订阅制上游服务的轮数(见 `SUBSCRIPTION`)。**少了它,一个全走订阅的 + /// 会话和一个一轮都算不出钱的会话长得一模一样**:有价格、没有价格、没有 + /// 用量都是 0 轮 + pub subscription_turns: i64, pub input_tokens: i64, pub output_tokens: i64, pub cache_read_tokens: i64, @@ -439,6 +450,9 @@ pub struct TurnRow { pub cancelled: bool, /// 这一轮的金额是估算。**瀑布图上要带记号** pub cost_estimated: bool, + /// 服务它的那家怎么收钱(见 `RequestRow::billing`)。**订阅制那一轮没有 + /// 金额,但不是「无法计价」** —— 只看 `cost_micros` 分不出这两种 + pub billing: String, } impl Db { @@ -463,7 +477,8 @@ impl Db { SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END), COALESCE(SUM(CASE WHEN cost_estimated = 1 THEN cost_micros ELSE 0 END), 0), COUNT(cost_micros), - COALESCE(SUM({NO_USAGE}), 0) + COALESCE(SUM({NO_USAGE}), 0), + COALESCE(SUM({SUBSCRIPTION}), 0) FROM requests WHERE session IS NOT NULL AND local = 0 GROUP BY session @@ -490,6 +505,7 @@ impl Db { cost_micros_estimated: r.get(15)?, priced_turns: r.get(16)?, no_usage_turns: r.get(17)?, + subscription_turns: r.get(18)?, }) })?; Ok(rows.collect::, _>>()?) @@ -500,7 +516,7 @@ impl Db { let mut st = self.conn.prepare( "SELECT id, at_ms, model, provider, input_tokens, output_tokens, cache_read_tokens, cost_micros, duration_ms, error, cancelled, - cost_estimated + cost_estimated, billing FROM requests WHERE session = ?1 AND local = 0 ORDER BY at_ms, id", )?; let rows = st.query_map([session], |r| { @@ -517,6 +533,7 @@ impl Db { error: r.get(9)?, cancelled: r.get::<_, i64>(10)? != 0, cost_estimated: r.get::<_, i64>(11)? != 0, + billing: r.get(12)?, }) })?; Ok(rows.collect::, _>>()?) @@ -743,8 +760,8 @@ impl Db { COALESCE(SUM(CASE WHEN cost_estimated = 0 THEN cost_micros ELSE 0 END), 0), COALESCE(SUM(CASE WHEN cost_estimated = 1 THEN cost_micros ELSE 0 END), 0), COALESCE(SUM({NO_PRICE}), 0), - COALESCE(SUM(billing = 'subscription'), 0), - COALESCE(SUM(CASE WHEN billing = 'subscription' + COALESCE(SUM({SUBSCRIPTION}), 0), + COALESCE(SUM(CASE WHEN {SUBSCRIPTION} THEN COALESCE(input_tokens,0) + COALESCE(output_tokens,0) ELSE 0 END), 0), COALESCE(SUM(cache_saved_micros), 0), @@ -1951,6 +1968,45 @@ mod cost_state_tests { assert_eq!(s.priced_turns, 0, "订阅制那一轮没有价格可言"); } + /// **全走订阅的会话和一轮都算不出钱的会话是两个结论。**以前两者在会话 + /// 这一层长得一模一样 —— 有价格、没有价格、没有用量都是 0 轮 —— 界面只能 + /// 都说成「无法计价」,而概览上同一批请求写着「订阅额度 N 次」。 + #[test] + fn a_session_counts_its_subscription_turns_as_what_they_are() { + let db = Db::in_memory().unwrap(); + let mut served = row(1, 100); + served.billing = "subscription".into(); + served.cost_micros = None; + // 断在中间的那一轮也是订阅上游服务的,不因为失败就变成「没有价格」 + let mut broken = served.clone(); + broken.id = 2; + broken.at_ms = 200; + broken.error = Some("流中断:上游断开了".into()); + for mut r in [served, broken, row(3, 300), unknown_model(4, 400)] { + r.session = Some("s1".into()); + db.insert(&r).unwrap(); + } + + let s = &db.sessions(10).unwrap()[0]; + assert_eq!(s.subscription_turns, 2); + assert_eq!( + (s.priced_turns, s.unpriced_turns, s.no_usage_turns), + (1, 1, 0), + "订阅那几轮混进了别的状态" + ); + assert_eq!( + db.summary(0, 1000).unwrap().subscription_requests, + s.subscription_turns, + "概览和会话数的不是同一批行" + ); + // 每一轮带着自己的计费方式:瀑布图上订阅那一轮不能写成「无法计价」 + let turns = db.turns("s1").unwrap(); + assert_eq!( + turns.iter().map(|t| t.billing.as_str()).collect::>(), + ["subscription", "subscription", "per-token", "per-token"] + ); + } + /// 价格页只列**配一个价格就能解决**的模型。列出一个失败了的、或者 /// 上游没报用量的模型,用户照做了,那几行也还是算不出钱。 #[test]