A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
fix(agy): recover usage for steps missing from transcripts (#10144)
ZeeyeC62c1fce7f4ca
diff --git a/src-tauri/src/services/session_usage_agy.rs b/src-tauri/src/services/session_usage_agy.rsindex 564ef8ee5..6e53efd49 100644--- a/src-tauri/src/services/session_usage_agy.rs+++ b/src-tauri/src/services/session_usage_agy.rs@@ -39,7 +39,15 @@ pub(crate) fn sync_agy_usage_with_cursors(db: &Database,cursors: &crate::services::session_usage::SyncCursors,) -> Result<SessionSyncResult, AppError> {- sync_agy_usage_from_files_with_cursors(db, agy::transcript_files(), cursors)+ let mut files = agy::transcript_files();+ // Prefer the transcript and its companion database when both exist.+ let mut seen: HashSet<_> = files.iter().map(|(session, _)| session.clone()).collect();+ files.extend(+ agy::native_usage_files()+ .into_iter()+ .filter(|(session, _)| seen.insert(session.clone())),+ );+ sync_agy_usage_from_files_with_cursors(db, files, cursors)}#[cfg(test)]@@ -78,39 +86,66 @@ fn sync_agy_usage_from_files_with_cursors(};let modified = metadata_modified_nanos(&metadata);let size = metadata.len() as i64;- // Invalidate pre-Orchestrator / pre-worker-alias / pre-Neon-Orchestrator cursors once,- // including unchanged, already timed history.- let native_state = format!("v4:{}", native_models::native_state_fingerprint(&path));+ // Revisit unchanged transcripts once to recover steps missing from their export.+ let native_state = native_models::native_state_fingerprint(&path);+ let parser_state = format!("v5:{native_state}");if cursor.is_some_and(|c| {c.last_modified == modified&& c.last_byte_offset == Some(size)- && c.parser_state.as_deref() == Some(native_state.as_str())+ && c.parser_state.as_deref() == Some(parser_state.as_str())}) {continue;}- match agy::records(&path) {- Ok(rows) => {- let sync_cursor = AgySyncCursorUpdate {- key: &cursor_key,- modified,- size,- native_state: &native_state,- };- match import_records_with_cursor(- db,- &session_id,- &rows,- Some(&path),- Some(sync_cursor),- ) {- Ok((imported, skipped)) => {- result.imported += imported;- result.skipped += skipped;- }- Err(e) => result.errors.push(format!("Antigravity {session_id}: {e}")),- }+ let transcript = (path.extension().is_none_or(|ext| ext != "db")).then_some(path.as_path());+ let rows = match transcript.map(agy::records).transpose() {+ Ok(rows) => rows.unwrap_or_default(),+ Err(error) => {+ result.errors.push(error);+ continue;+ }+ };+ let exported = rows+ .iter()+ .filter_map(|row| row["step_index"].as_u64())+ .collect();+ let native = native_models::native_database_path(&path).and_then(|database| {+ database+ .map(|database| native_models::missing_usage(&database, &session_id, &exported))+ .transpose()+ });+ let (recovered, stable) = match native {+ Ok(recovered) if native_state == native_models::native_state_fingerprint(&path) => {+ (recovered.unwrap_or_default(), true)+ }+ Ok(_) => {+ result.deferred_files += 1;+ (Vec::new(), false)+ }+ Err(error) => {+ log::debug!("Antigravity {session_id}: cannot recover native usage: {error}");+ result.deferred_files += 1;+ (Vec::new(), false)}- Err(e) => result.errors.push(e),+ };+ let sync_cursor = stable.then_some(AgySyncCursorUpdate {+ key: &cursor_key,+ modified,+ size,+ native_state: &parser_state,+ });+ match import_records_with_cursor(+ db,+ &session_id,+ &rows,+ transcript,+ &recovered,+ sync_cursor,+ ) {+ Ok((imported, skipped)) => {+ result.imported += imported;+ result.skipped += skipped;+ }+ Err(e) => result.errors.push(format!("Antigravity {session_id}: {e}")),}}Ok(result)@@ -215,7 +250,7 @@ fn import_records(rows: &[Value],transcript: Option<&Path>,) -> Result<(u32, u32), AppError> {- import_records_with_cursor(db, session, rows, transcript, None)+ import_records_with_cursor(db, session, rows, transcript, &[], None)}fn import_records_with_cursor(@@ -223,6 +258,7 @@ fn import_records_with_cursor(session: &str,rows: &[Value],transcript: Option<&Path>,+ recovered: &[native_models::RecoveredStep],sync_cursor: Option<AgySyncCursorUpdate<'_>>,) -> Result<(u32, u32), AppError> {// step_index 顺序决定模型归属:先按顺序扫一遍切换事件,再给每个响应打上当时的模型。@@ -286,6 +322,46 @@ fn import_records_with_cursor(}}+ timing_by_step.extend(+ recovered+ .iter()+ .filter_map(|step| Some((step.index, step.generation.timing?))),+ );+ let exported = rows.iter().filter_map(|row| {+ if row["type"] != "PLANNER_RESPONSE" || row["status"] != "DONE" {+ return None;+ }+ let step = row["step_index"].as_u64()?;+ let tokens = [+ "input_tokens",+ "output_tokens",+ "cache_read_tokens",+ "cache_write_tokens",+ ]+ .map(|name| {+ row[name]+ .as_u64()+ .and_then(|v| i64::try_from(v).ok())+ .unwrap_or(0)+ });+ Some((+ step,+ tokens,+ known_model(row),+ agy::timestamp(row).unwrap_or(0) / 1000,+ false,+ ))+ });+ let native_only = recovered.iter().map(|step| {+ (+ step.index,+ step.tokens.map(|tokens| tokens as i64),+ step.generation.model.as_deref(),+ step.timestamp_ms / 1000,+ true,+ )+ });+// 聚合模式的 key 登记簿:key 永不改指向,按它认出 `ccs-<key>--<模型>` 是哪家的。let stack_keys = crate::mode::state::stack(&DeviceStore::for_device(), AppType::Agy.as_str()).map(|stack| stack.keys)@@ -294,23 +370,9 @@ fn import_records_with_cursor(let tx = conn.transaction()?;let mut pricing_cache = HashMap::new();let (mut imported, mut skipped) = (0, 0);- for row in rows {- if row["type"] != "PLANNER_RESPONSE" || row["status"] != "DONE" {- continue;- }- let Some(step) = row["step_index"].as_u64() else {- continue;- };- let token = |name: &str| {- row[name]- .as_u64()- .and_then(|v| i64::try_from(v).ok())- .unwrap_or(0)- };- let input = token("input_tokens");- let output = token("output_tokens");- let cache = token("cache_read_tokens");- let write = token("cache_write_tokens");+ for (step, [input, output, cache, write], recorded_model, created_at, recovered_only) in+ exported.chain(native_only)+ {if input == 0 && output == 0 && cache == 0 && write == 0 {continue;}@@ -319,8 +381,13 @@ fn import_records_with_cursor(let fresh = tx.prepare_cached("INSERT OR IGNORE INTO session_usage_dedup(data_source,request_id,semantic_id,has_entry_id) VALUES ('agy_session',?1,?1,1)")?.execute([&id])?;+ if fresh == 0 && recovered_only {+ // An exported record or an archived request may already own this ID.+ skipped += 1;+ continue;+ }// `model` 存 ID(对得上定价和其它应用的统计),`request_model` 留显示名。- let display = known_model(row)+ let display = recorded_model.map(str::to_string).or_else(|| model_by_step.get(&step).cloned()).or_else(|| native_model_by_step.get(&step).cloned())@@ -430,7 +497,7 @@ fn import_records_with_cursor(cache_read_cost_usd,cache_creation_cost_usd,total_cost_usd,latency_ms,first_token_ms,status_code,session_id,provider_type,is_streaming,cost_multiplier,created_at,data_source,input_token_semantics) VALUES (?1,?18,'agy',?2,?10,?3,?4,?5,?6,?11,?12,?13,?14,?15,?16,?17,200,?7,'agy_session',1,'1',?8,'agy_session',?9)")?- .execute(params![id, model, input, output, cache, write, session, agy::timestamp(row).unwrap_or(0)/1000, INPUT_TOKEN_SEMANTICS_FRESH, display, input_cost, output_cost, cache_cost, write_cost, total_cost, latency_ms, first_token_ms, provider_id])?;+ .execute(params![id, model, input, output, cache, write, session, created_at, INPUT_TOKEN_SEMANTICS_FRESH, display, input_cost, output_cost, cache_cost, write_cost, total_cost, latency_ms, first_token_ms, provider_id])?;imported += inserted as u32;skipped += u32::from(inserted == 0);}@@ -504,6 +571,102 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ #[serial_test::serial]+ fn sync_agy_usage_recovers_completed_steps_missing_from_the_export() {+ if crate::config::sqlite_unsupported_in_temp_dir() {+ return;+ }+ let home = crate::test_support::TestHome::new();+ let root = home.path().join(".gemini/antigravity-cli");+ let conversations = root.join("conversations");+ let logs = root.join("brain/partial/.system_generated/logs");+ std::fs::create_dir_all(&logs).unwrap();+ std::fs::create_dir_all(&conversations).unwrap();+ let transcript = logs.join("transcript_full.jsonl");+ let exported = json!({+ "step_index": 1, "type": "PLANNER_RESPONSE", "status": "DONE",+ "input_tokens": 21, "output_tokens": 3+ });+ std::fs::write(&transcript, format!("{exported}\n")).unwrap();++ let native = native_models::write_test_database(+ &conversations.join("partial.db"),+ &[+ (1, 0, "gemini-4-argon"),+ (2, 1, "gemini-4-argon"),+ (3, 2, "gemini-4-argon"),+ (4, 3, "gemini-4-argon"),+ (5, 4, "gemini-4-argon"),+ ],+ );+ for (step, generation, status, origin) in [+ (1, 0, 3, ""),+ (2, 1, 3, ""),+ (3, 2, 2, ""),+ (4, 3, 3, "21b06a6b-4e97-41ba-8b29-84dbc4ee6880"),+ (5, 4, 3, ""),+ ] {+ native_models::set_test_step_usage(&native, step, generation, status, origin);+ }+ drop(native);+ let native_only = native_models::write_test_database(+ &conversations.join("native-only.db"),+ &[(1, 0, "gemini-4-argon")],+ );+ native_models::set_test_step_usage(&native_only, 1, 0, 3, "");+ drop(native_only);++ let db = Database::memory().unwrap();+ db.conn+ .lock()+ .unwrap()+ .execute(+ "INSERT INTO session_usage_dedup (data_source,request_id,semantic_id,has_entry_id)+ VALUES ('agy_session','agy:partial:5','agy:partial:5',1)",+ [],+ )+ .unwrap();+ let first = sync_agy_usage(&db).unwrap();+ assert_eq!(+ (first.files_scanned, first.imported, first.skipped),+ (2, 3, 1)+ );+ assert!(first.errors.is_empty());+ assert_eq!(first.deferred_files, 0);+ let counts = |id: &str| -> (String, i64, i64, i64, i64) {+ db.conn.lock().unwrap().query_row(+ "SELECT model,input_tokens,output_tokens,cache_read_tokens,cache_creation_tokens+ FROM proxy_request_logs WHERE request_id=?1",+ [id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),+ ).unwrap()+ };+ assert_eq!(counts("agy:partial:1").1, 21);+ let expected = ("gemini-4-argon".into(), 60, 7, 20, 8);+ assert_eq!(counts("agy:partial:2"), expected);+ assert_eq!(counts("agy:native-only:1"), expected);+ assert_eq!(sync_agy_usage(&db).unwrap().imported, 0);++ let late = json!({+ "step_index": 2, "type": "PLANNER_RESPONSE", "status": "DONE",+ "input_tokens": 63, "output_tokens": 7+ });+ std::fs::write(&transcript, format!("{exported}\n{late}\n")).unwrap();+ assert_eq!(sync_agy_usage(&db).unwrap().imported, 1);+ assert_eq!(counts("agy:partial:2").1, 63);+ assert_eq!(sync_agy_usage(&db).unwrap().imported, 0);+ let total: i64 = db+ .conn+ .lock()+ .unwrap()+ .query_row("SELECT COUNT(*) FROM proxy_request_logs", [], |row| {+ row.get(0)+ })+ .unwrap();+ assert_eq!(total, 3);+ }+#[test]fn native_models_backfill_unknown_rows_without_changing_tokens_or_deduplication() {if crate::config::sqlite_unsupported_in_temp_dir() {diff --git a/src-tauri/src/services/session_usage_agy/native_models.rs b/src-tauri/src/services/session_usage_agy/native_models.rsindex c551fb3e3..006d56f9f 100644--- a/src-tauri/src/services/session_usage_agy/native_models.rs+++ b/src-tauri/src/services/session_usage_agy/native_models.rs@@ -1,7 +1,11 @@//! Read per-generation model names from Antigravity's native conversation database.use prost::Message;use rusqlite::{Connection, OpenFlags, OptionalExtension};-use std::{collections::HashMap, path::Path, time::Duration};+use std::{+ collections::{HashMap, HashSet},+ path::Path,+ time::Duration,+};// Only the fields needed for the step -> generation -> model association are decoded.#[derive(Clone, PartialEq, Message)]@@ -103,9 +107,14 @@ fn timing_of(bytes: &[u8]) -> Option<Timing> {})}-fn native_database_path(transcript: &Path) -> Result<Option<std::path::PathBuf>, String> {+pub(super) fn native_database_path(+ transcript: &Path,+) -> Result<Option<std::path::PathBuf>, String> {// brain/<id>/.system_generated/logs/transcript_full.jsonl and conversations/<id>.db// share the same CLI/IDE/private-profile root.+ if transcript.extension().is_some_and(|ext| ext == "db") {+ return Ok(Some(transcript.to_path_buf()));+ }let session = transcript.parent().and_then(Path::parent)@@ -136,6 +145,10 @@ pub(super) fn native_state_fingerprint(transcript: &Path) -> String {let Ok(Some(path)) = native_database_path(transcript) else {return "none".to_string();};+ database_fingerprint(&path)+}++fn database_fingerprint(path: &Path) -> String {let file_sig = |target: &Path| -> (i64, u64) {std::fs::metadata(target).map(|meta| {@@ -146,7 +159,7 @@ pub(super) fn native_state_fingerprint(transcript: &Path) -> String {}).unwrap_or((0, 0))};- let (db_mtime, db_len) = file_sig(&path);+ let (db_mtime, db_len) = file_sig(path);let mut wal_os = path.as_os_str().to_os_string();wal_os.push("-wal");let (wal_mtime, wal_len) = file_sig(Path::new(&wal_os));@@ -198,40 +211,7 @@ fn read_generations(path: &Path, steps: &[u64]) -> rusqlite::Result<HashMap<u64,let Some(bytes) = data else {continue;};- let tiered = GenerationModelId::decode(bytes.as_slice())- .ok()- .and_then(|metadata| metadata.response)- .map(|response| response.model_id);- let base = GenerationMetadata::decode(bytes.as_slice())- .ok()- .and_then(|metadata| metadata.response)- .map(|response| response.model);- // Orchestrator's display field names the mode (or just "Gemini Flash"),- // while field 19 identifies the planner/worker that produced this step.- // Only these exact AGY aliases are mapped; unknown IDs keep their configured pricing.- // https://antigravity.google/docs/models#orchestrator- let orchestrator_model = match base.as_deref() {- Some("gemini-pro-orchestrator") => Some("gemini-4-carbon"),- Some("gemini-pro-orchestrator-argon" | "gemini-pro-orchestrator-g1-pro") => {- Some("gemini-4-argon")- }- Some("gemini-pro-orchestrator-neon") => Some("gemini-4-neon"),- Some("gemini-flash-worker-agy") => Some("gemini-4-hydrogen"),- _ => None,- };- let tiered = tiered.filter(|model| {- let id = super::model_id_of(model);- // Keep a concrete field-21 model/tier if a newer AGY build supplies one.- !(orchestrator_model.is_some()- && (super::is_orchestrator(&id)- || matches!(id.as_str(), "gemini-flash" | "gemini-flash-worker-agy")))- });- let model = [tiered, orchestrator_model.map(str::to_string), base]- .into_iter()- .flatten()- .map(|model| model.trim().to_string())- .find(|model| !model.is_empty() && !model.eq_ignore_ascii_case("unknown"));- let timing = timing_of(&bytes);+ let Generation { model, timing } = generation_of(&bytes);if model.is_some() || timing.is_some() {generations.insert(step, Generation { model, timing });}@@ -239,6 +219,184 @@ fn read_generations(path: &Path, steps: &[u64]) -> rusqlite::Result<HashMap<u64,Ok(generations)}+fn generation_of(bytes: &[u8]) -> Generation {+ let tiered = GenerationModelId::decode(bytes)+ .ok()+ .and_then(|metadata| metadata.response)+ .map(|response| response.model_id);+ let base = GenerationMetadata::decode(bytes)+ .ok()+ .and_then(|metadata| metadata.response)+ .map(|response| response.model);+ // Orchestrator's display field names the mode (or just "Gemini Flash"),+ // while field 19 identifies the planner/worker that produced this step.+ // Only these exact AGY aliases are mapped; unknown IDs keep their configured pricing.+ // https://antigravity.google/docs/models#orchestrator+ let orchestrator_model = match base.as_deref() {+ Some("gemini-pro-orchestrator") => Some("gemini-4-carbon"),+ Some("gemini-pro-orchestrator-argon" | "gemini-pro-orchestrator-g1-pro") => {+ Some("gemini-4-argon")+ }+ Some("gemini-pro-orchestrator-neon") => Some("gemini-4-neon"),+ Some("gemini-flash-worker-agy") => Some("gemini-4-hydrogen"),+ _ => None,+ };+ let tiered = tiered.filter(|model| {+ let id = super::model_id_of(model);+ // Keep a concrete field-21 model/tier if a newer AGY build supplies one.+ !(orchestrator_model.is_some()+ && (super::is_orchestrator(&id)+ || matches!(id.as_str(), "gemini-flash" | "gemini-flash-worker-agy")))+ });+ let model = [tiered, orchestrator_model.map(str::to_string), base]+ .into_iter()+ .flatten()+ .map(|model| model.trim().to_string())+ .find(|model| !model.is_empty() && !model.eq_ignore_ascii_case("unknown"));+ let timing = timing_of(bytes);+ Generation { model, timing }+}++#[derive(Clone, PartialEq, Message)]+struct UsageStepMetadata {+ #[prost(message, optional, tag = "1")]+ created: Option<DurationValue>,+ #[prost(message, optional, tag = "9")]+ usage: Option<StepUsage>,+ #[prost(message, optional, tag = "20")]+ generation: Option<UsageGenerationReference>,+}++#[derive(Clone, PartialEq, Message)]+struct UsageGenerationReference {+ #[prost(uint64, tag = "3")]+ index: u64,+ #[prost(string, tag = "4")]+ source_session: String,+}++#[derive(Clone, PartialEq, Message)]+struct StepUsage {+ #[prost(uint32, tag = "2")]+ input: u32,+ #[prost(uint32, tag = "3")]+ billed_output: u32,+ #[prost(uint32, tag = "4")]+ cache_write: u32,+ #[prost(uint32, tag = "5")]+ cache_read: u32,+ #[prost(uint32, tag = "9")]+ thinking: u32,+ #[prost(uint32, optional, tag = "10")]+ response_output: Option<u32>,+}++pub(super) struct RecoveredStep {+ pub index: u64,+ pub timestamp_ms: i64,+ pub tokens: [u64; 4],+ pub generation: Generation,+}++/// Read only completed steps that were never exported. Preserve the step's own+/// counters; generation-level counters can aggregate multiple planner steps.+pub(super) fn missing_usage(+ path: &Path,+ session: &str,+ exported: &HashSet<u64>,+) -> Result<Vec<RecoveredStep>, String> {+ let mut conn = crate::session_manager::providers::agy::open_db(path)+ .ok_or("cannot open native conversation database")?;+ read_missing_usage(&mut conn, session, exported).map_err(|error| error.to_string())+}++fn read_missing_usage(+ conn: &mut Connection,+ session: &str,+ exported: &HashSet<u64>,+) -> rusqlite::Result<Vec<RecoveredStep>> {+ let tx = conn.transaction()?;+ // A build without these tables/columns has nothing to recover; deferring would+ // re-read the whole transcript on every sync.+ let mut query =+ match tx.prepare("SELECT idx, metadata FROM steps WHERE step_type=15 AND status=3") {+ Err(error) if is_schema_gap(&error) => return Ok(Vec::new()),+ query => query?,+ };+ let mut rows = query.query([])?;+ let mut recovered = Vec::new();+ while let Some(row) = rows.next()? {+ let index: u64 = row.get(0)?;+ if exported.contains(&index) {+ continue;+ }+ let metadata: Option<Vec<u8>> = row.get(1)?;+ let Some(metadata) = metadata+ .as_deref()+ .and_then(|bytes| UsageStepMetadata::decode(bytes).ok())+ else {+ continue;+ };+ let Some(timestamp_ms) = metadata+ .created+ .and_then(|created| created.millis())+ .filter(|ms| *ms > 0)+ else {+ continue;+ };+ let Some(usage) = metadata.usage else {+ continue;+ };+ let output = usage+ .response_output+ .map_or(u64::from(usage.billed_output), |visible| {+ u64::from(visible) + u64::from(usage.thinking)+ });+ let tokens = [+ u64::from(usage.input),+ output,+ u64::from(usage.cache_read),+ u64::from(usage.cache_write),+ ];+ if tokens == [0; 4] {+ continue;+ }+ // A fork can replay a step whose usage belongs to the original session.+ let generation = if let Some(reference) = metadata.generation {+ if let Ok(origin) = uuid::Uuid::parse_str(&reference.source_session) {+ if uuid::Uuid::parse_str(session).ok() != Some(origin) {+ continue;+ }+ }+ match tx.prepare_cached("SELECT data FROM gen_metadata WHERE idx=?1") {+ Err(error) if is_schema_gap(&error) => Generation::default(),+ statement => statement?+ .query_row([reference.index], |row| {+ let data: Vec<u8> = row.get(0)?;+ Ok(generation_of(&data))+ })+ .optional()?+ .unwrap_or_default(),+ }+ } else {+ Generation::default()+ };+ recovered.push(RecoveredStep {+ index,+ timestamp_ms,+ tokens,+ generation,+ });+ }+ Ok(recovered)+}++/// Prepare errors arrive as `SqliteFailure` or `SqlInputError` depending on the SQLite build.+fn is_schema_gap(error: &rusqlite::Error) -> bool {+ let message = error.to_string();+ message.contains("no such table") || message.contains("no such column")+}+#[cfg(test)]fn read_models(path: &Path, steps: &[u64]) -> rusqlite::Result<HashMap<u64, String>> {Ok(read_generations(path, steps)?@@ -247,11 +405,44 @@ fn read_models(path: &Path, steps: &[u64]) -> rusqlite::Result<HashMap<u64, Stri.collect())}+#[cfg(test)]+pub(super) fn set_test_step_usage(+ conn: &Connection,+ index: i64,+ generation: u64,+ status: i64,+ source_session: &str,+) {+ let metadata = UsageStepMetadata {+ created: Some(DurationValue {+ seconds: 1_700_000_000,+ nanos: 0,+ }),+ usage: Some(StepUsage {+ input: 60,+ billed_output: 7,+ cache_read: 20,+ cache_write: 8,+ thinking: 2,+ response_output: Some(5),+ }),+ generation: Some(UsageGenerationReference {+ index: generation,+ source_session: source_session.to_owned(),+ }),+ };+ conn.execute(+ "UPDATE steps SET metadata=?1,status=?2 WHERE idx=?3",+ rusqlite::params![metadata.encode_to_vec(), status, index],+ )+ .unwrap();+}+#[cfg(test)]pub(super) fn write_test_database(path: &Path, entries: &[(i64, u64, &str)]) -> Connection {let conn = Connection::open(path).unwrap();conn.execute_batch(- "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, metadata BLOB);+ "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, metadata BLOB, status INTEGER DEFAULT 3);CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);",).unwrap();@@ -265,7 +456,7 @@ pub(super) fn write_test_database(path: &Path, entries: &[(i64, u64, &str)]) ->}),};conn.execute(- "INSERT INTO steps VALUES (?1,15,?2)",+ "INSERT INTO steps (idx, step_type, metadata) VALUES (?1,15,?2)",rusqlite::params![step, metadata.encode_to_vec()],).unwrap();@@ -317,6 +508,26 @@ pub(super) fn test_timing(first_token_ms: i64, streaming_ms: i64) -> Vec<u8> {mod tests {use super::*;+ #[test]+ fn missing_usage_treats_an_older_schema_as_nothing_to_recover() {+ if crate::config::sqlite_unsupported_in_temp_dir() {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("old.db");+ let conn = Connection::open(&path).unwrap();+ conn.execute_batch(+ "CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, metadata BLOB);",+ )+ .unwrap();+ drop(conn);+ assert!(missing_usage(&path, "old", &HashSet::new())+ .unwrap()+ .is_empty());+ // Unreadable databases still fail, so the sync defers instead of settling.+ assert!(missing_usage(&dir.path().join("absent.db"), "absent", &HashSet::new()).is_err());+ }+#[test]fn orchestrator_native_aliases_use_generation_role_instead_of_generic_display() {if crate::config::sqlite_unsupported_in_temp_dir() {@@ -422,10 +633,10 @@ mod tests {let path = dir.path().join("session.db");let conn = write_test_database(&path, &[(1, 0, "gemini-4-argon")]);conn.execute_batch(- "INSERT INTO steps VALUES (2,15,X'');- INSERT INTO steps VALUES (3,15,X'80');- INSERT INTO steps VALUES (4,15,X'A201021809');- INSERT INTO steps VALUES (5,15,NULL);",+ "INSERT INTO steps (idx, step_type, metadata) VALUES (2,15,X'');+ INSERT INTO steps (idx, step_type, metadata) VALUES (3,15,X'80');+ INSERT INTO steps (idx, step_type, metadata) VALUES (4,15,X'A201021809');+ INSERT INTO steps (idx, step_type, metadata) VALUES (5,15,NULL);",).unwrap();let models = read_models(&path, &[1, 2, 3, 4, 5]).unwrap();diff --git a/src-tauri/src/session_manager/providers/agy.rs b/src-tauri/src/session_manager/providers/agy.rsindex 330219ce8..59628bd1d 100644--- a/src-tauri/src/session_manager/providers/agy.rs+++ b/src-tauri/src/session_manager/providers/agy.rs@@ -211,6 +211,34 @@ pub(crate) fn transcript_files() -> Vec<(String, PathBuf)> {transcript_files_in_roots(&session_roots())}+/// Session usage can survive in a conversation database after the transcript is absent.+pub(crate) fn native_usage_files() -> Vec<(String, PathBuf)> {+ let mut files = Vec::new();+ for root in session_roots() {+ let Some(base) = root.parent().and_then(|base| base.canonicalize().ok()) else {+ continue;+ };+ let conversations = base.join("conversations");+ for entry in fs::read_dir(&conversations).into_iter().flatten().flatten() {+ let path = entry.path();+ if path.extension().is_none_or(|ext| ext != "db") {+ continue;+ }+ let Some(id) = path+ .file_stem()+ .and_then(|id| id.to_str())+ .filter(|id| valid_session_id(id))+ else {+ continue;+ };+ if let Some(path) = db_file(&conversations, Some(&base), id) {+ files.push((id.to_owned(), path));+ }+ }+ }+ files+}+pub(crate) fn transcript_files_in_roots(roots: &[PathBuf]) -> Vec<(String, PathBuf)> {let mut seen = HashSet::new();let mut files = Vec::new();@@ -419,7 +447,7 @@ fn has_nonempty_wal(path: &Path) -> bool {.is_some_and(|canonical| wal_nonempty(&canonical))}-fn open_db(path: &Path) -> Option<rusqlite::Connection> {+pub(crate) fn open_db(path: &Path) -> Option<rusqlite::Connection> {let flags =rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;match rusqlite::Connection::open_with_flags(path, flags) {