Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

18.7 KB
Raw Blame
//! Import usage from the CodeBuddy IDE plugins (JetBrains, VS Code) and the CodeBuddy
//! IDE itself. They share one engine and one store, separate from the CodeBuddy Code
//! CLI transcripts that `session_usage_codebuddy` reads:
//!
//! `<data root>/Data/<account>/<IDE type>/<account>/history/<workspace>/<conversation>/index.json`
//!
//! The data root is `CodeBuddyExtension` under `~/Library/Application Support` (macOS),
//! `~/AppData/Local` (Windows) or `~/.local/share` (elsewhere); the plugin derives it
//! from the home directory, not from environment variables. Signed out, `<account>` is
//! `default` and the third level is an encoded workspace path; the depth is the same.
//!
//! A conversation's `index.json` is `{messages: [id], requests: [{id, type, state,
//! startedAt (ms), messages: [id], usage}]}`, rewritten whole on every change. One
//! request is one user turn, possibly several model calls: `usage` sums them and is
//! written together with `state: "complete"` when the turn ends, so only finished
//! requests are imported (an unfinished one would be locked in half-counted by its
//! receipt). `inputTokens` includes the cache hits (`cacheTokens`) and writes
//! (`cachedWriteTokens`); rows store fresh input like the CLI importer. `credit` is a
//! CodeBuddy point count, not dollars, and is not used as cost.
//!
//! The model id is on the request's messages (`extra.modelId`, `custom-local:` prefix
//! dropped); the workspace `index.json` names the conversation's selected model as a
//! fallback. Message files are read only for requests not imported yet.
use crate::database::{lock_conn, Database};
use crate::error::AppError;
use crate::proxy::usage::parser::TokenUsage;
use crate::services::{
    session_usage::{metadata_modified_nanos, update_sync_state_on_conn, SessionSyncResult},
    session_usage_codebuddy::{costs, strip_custom_prefix},
    sql_helpers::INPUT_TOKEN_SEMANTICS_FRESH,
};
use serde_json::Value;
use std::{
    collections::HashSet,
    fs,
    path::{Path, PathBuf},
};

const DATA_SOURCE: &str = "codebuddy_ide_session";
/// Cursor key prefix; bump it to make every conversation file be read again.
const CURSOR_PREFIX: &str = "codebuddy-ide:v1:";
/// How many of a request's messages, newest first, are opened to find its model.
const MODEL_LOOKUP_MESSAGES: usize = 3;

/// `CodeBuddyExtension/Data` for the given OS, mirroring the plugin's own choice.
fn data_root_for(home: &Path, os: &str) -> PathBuf {
    let base = match os {
        "macos" => home.join("Library").join("Application Support"),
        "windows" => home.join("AppData").join("Local"),
        _ => home.join(".local").join("share"),
    };
    base.join("CodeBuddyExtension").join("Data")
}

pub(crate) fn sync_codebuddy_ide_usage(
    db: &Database,
    cursors: &crate::services::session_usage::SyncCursors,
) -> Result<SessionSyncResult, AppError> {
    let root = data_root_for(&crate::config::get_home_dir(), std::env::consts::OS);
    sync_root_with_cursors(db, &root, cursors)
}

fn subdirs(dir: &Path) -> Vec<PathBuf> {
    fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
        .map(|entry| entry.path())
        .collect()
}

/// Every `history/<workspace>` directory under the data root.
fn workspace_dirs(root: &Path) -> Vec<PathBuf> {
    let mut workspaces = Vec::new();
    for account in subdirs(root) {
        for ide in subdirs(&account) {
            for scope in subdirs(&ide) {
                workspaces.extend(subdirs(&scope.join("history")));
            }
        }
    }
    workspaces
}

#[cfg(test)]
fn sync_root(db: &Database, root: &Path) -> Result<SessionSyncResult, AppError> {
    sync_root_with_cursors(
        db,
        root,
        &crate::services::session_usage::load_sync_cursors(db)?,
    )
}

fn sync_root_with_cursors(
    db: &Database,
    root: &Path,
    cursors: &crate::services::session_usage::SyncCursors,
) -> Result<SessionSyncResult, AppError> {
    let mut result = SessionSyncResult::default();
    for workspace in workspace_dirs(root) {
        // Read lazily: only needed when a conversation changed.
        let mut selected_models: Option<Value> = None;
        for conversation in subdirs(&workspace) {
            let path = conversation.join("index.json");
            let Ok(meta) = fs::metadata(&path) else {
                continue;
            };
            let modified = metadata_modified_nanos(&meta);
            let size = meta.len() as i64;
            let key = format!("{CURSOR_PREFIX}{}", path.to_string_lossy());
            if cursors
                .get(&key)
                .is_some_and(|c| c.last_modified == modified && c.last_line_offset == size)
            {
                continue;
            }
            let workspace_index = selected_models.get_or_insert_with(|| {
                fs::read(workspace.join("index.json"))
                    .ok()
                    .and_then(|bytes| serde_json::from_slice(&bytes).ok())
                    .unwrap_or(Value::Null)
            });
            match sync_conversation(db, &conversation, workspace_index, &key, modified, size) {
                Ok(part) => result.merge(part),
                Err(error) => result.errors.push(format!(
                    "CodeBuddy IDE conversation {}: {error}",
                    path.display()
                )),
            }
        }
    }
    Ok(result)
}

/// Token counts of one finished request, `input` excluding cache reads and writes.
/// `None` for unfinished requests and ones without usage.
fn request_usage(request: &Value) -> Option<TokenUsage> {
    if request.get("state").and_then(Value::as_str) != Some("complete") {
        return None;
    }
    let usage = request.get("usage").filter(|usage| usage.is_object())?;
    let number = |key: &str| usage.get(key).and_then(Value::as_u64).unwrap_or(0);
    let cache_read = number("cacheTokens");
    let cache_write = number("cachedWriteTokens");
    let input = number("inputTokens").saturating_sub(cache_read.saturating_add(cache_write));
    let output = number("outputTokens");
    if input == 0 && output == 0 && cache_read == 0 && cache_write == 0 {
        return None;
    }
    let to_u32 = |n: u64| n.min(u32::MAX as u64) as u32;
    Some(TokenUsage {
        input_tokens: to_u32(input),
        output_tokens: to_u32(output),
        cache_read_tokens: to_u32(cache_read),
        cache_creation_tokens: to_u32(cache_write),
        cache_creation_1h_tokens: 0,
        model: None,
        message_id: None,
    })
}

fn model_id(raw: &str) -> Option<String> {
    let model = strip_custom_prefix(raw.trim());
    (!model.is_empty()).then(|| model.to_string())
}

/// The model a request ran on: `extra.modelId` on its newest messages.
fn message_model(conversation: &Path, request: &Value) -> Option<String> {
    request
        .get("messages")
        .and_then(Value::as_array)?
        .iter()
        .rev()
        .filter_map(Value::as_str)
        .take(MODEL_LOOKUP_MESSAGES)
        .find_map(|id| {
            let bytes = fs::read(conversation.join("messages").join(format!("{id}.json"))).ok()?;
            let message: Value = serde_json::from_slice(&bytes).ok()?;
            model_id(message.pointer("/extra/modelId")?.as_str()?)
        })
}

/// The conversation's selected model from the workspace index: `selectedModelId`,
/// or `modelMap[<request type>]` in older stores.
fn selected_model(workspace_index: &Value, conversation_id: &str, kind: &str) -> Option<String> {
    let conversation = workspace_index
        .get("conversations")
        .and_then(Value::as_array)?
        .iter()
        .find(|c| c.get("id").and_then(Value::as_str) == Some(conversation_id))?;
    conversation
        .get("selectedModelId")
        .and_then(Value::as_str)
        .or_else(|| conversation.pointer(&format!("/modelMap/{kind}"))?.as_str())
        .and_then(model_id)
}

struct Entry {
    request_id: String,
    model: String,
    usage: TokenUsage,
    created_ms: i64,
}

fn sync_conversation(
    db: &Database,
    conversation: &Path,
    workspace_index: &Value,
    key: &str,
    modified: i64,
    size: i64,
) -> Result<SessionSyncResult, AppError> {
    let path = conversation.join("index.json");
    let bytes = fs::read(&path).map_err(|error| AppError::io(&path, error))?;
    let mut result = SessionSyncResult {
        files_scanned: 1,
        ..Default::default()
    };
    // The plugin rewrites the file in place; a read that catches it half written is
    // retried next round (the cursor is left untouched).
    let Ok(index) = serde_json::from_slice::<Value>(&bytes) else {
        return Ok(result);
    };
    let conversation_id = conversation
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let candidates: Vec<(String, &Value, TokenUsage)> = index
        .get("requests")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|request| {
            let id = request.get("id").and_then(Value::as_str)?;
            Some((
                format!("codebuddy-ide:{id}"),
                request,
                request_usage(request)?,
            ))
        })
        .collect();

    let known: HashSet<String> = {
        let conn = lock_conn!(db.conn);
        let mut stmt = conn.prepare(
            "SELECT 1 FROM session_usage_dedup WHERE data_source = ?1 AND request_id = ?2",
        )?;
        let mut known = HashSet::new();
        for (request_id, _, _) in &candidates {
            if stmt.exists(rusqlite::params![DATA_SOURCE, request_id])? {
                known.insert(request_id.clone());
            }
        }
        known
    };

    let mut entries = Vec::new();
    for (request_id, request, mut usage) in candidates {
        if known.contains(&request_id) {
            result.skipped += 1;
            continue;
        }
        let Some(created_ms) = request.get("startedAt").and_then(Value::as_i64) else {
            continue;
        };
        let kind = request.get("type").and_then(Value::as_str).unwrap_or("");
        let model = message_model(conversation, request)
            .or_else(|| selected_model(workspace_index, &conversation_id, kind))
            .unwrap_or_else(|| "unknown".into());
        usage.model = Some(model.clone());
        entries.push(Entry {
            request_id,
            model,
            usage,
            created_ms,
        });
    }

    let mut conn = lock_conn!(db.conn);
    let tx = conn.transaction()?;
    for entry in entries {
        // Permanent receipts prevent re-import after rewrites or detail pruning.
        if tx.execute(
            "INSERT OR IGNORE INTO session_usage_dedup (data_source, request_id, semantic_id, has_entry_id) VALUES (?1, ?2, ?2, 1)",
            rusqlite::params![DATA_SOURCE, entry.request_id],
        )? == 0
        {
            result.skipped += 1;
            continue;
        }
        let usage = &entry.usage;
        let amounts = costs(&tx, &entry.model, usage);
        tx.execute(
            "INSERT OR IGNORE INTO proxy_request_logs (
                request_id, provider_id, app_type, model, request_model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
                input_cost_usd, output_cost_usd, 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, '_codebuddy_session', 'codebuddy', ?2, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 0, NULL, 200, ?12, ?13, 1, '1', ?14, ?13, ?15)",
            rusqlite::params![
                entry.request_id,
                entry.model,
                usage.input_tokens,
                usage.output_tokens,
                usage.cache_read_tokens,
                usage.cache_creation_tokens,
                amounts[0],
                amounts[1],
                amounts[2],
                amounts[3],
                amounts[4],
                conversation_id,
                DATA_SOURCE,
                entry.created_ms / 1000,
                INPUT_TOKEN_SEMANTICS_FRESH,
            ],
        )?;
        result.imported += 1;
    }
    update_sync_state_on_conn(&tx, key, modified, size)?;
    tx.commit()?;
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn request(id: &str, state: &str, messages: &[&str], usage: Value) -> Value {
        json!({"id": id, "type": "craft", "state": state, "startedAt": 1795657325993_i64,
            "messages": messages, "usage": usage})
    }

    fn usage(input: u64, cache: u64, write: u64, output: u64) -> Value {
        json!({"inputTokens": input, "outputTokens": output, "totalTokens": input + output,
            "lastTokens": 10, "cacheTokens": cache, "cachedWriteTokens": write,
            "cachedMissTokens": input - cache - write, "credit": 1.5})
    }

    /// `<root>/<account>/<ide>/<account>/history/<workspace>/<conversation>`
    fn conversation(root: &Path, ide: &str, id: &str) -> PathBuf {
        let dir = root
            .join("acct")
            .join(ide)
            .join("acct")
            .join("history")
            .join("ws1")
            .join(id);
        fs::create_dir_all(dir.join("messages")).unwrap();
        dir
    }

    /// Every rewrite in these tests changes the file size, so the cursor sees it.
    fn write_index(dir: &Path, requests: Vec<Value>) {
        fs::write(
            dir.join("index.json"),
            json!({"messages": [], "requests": requests}).to_string(),
        )
        .unwrap();
    }

    fn write_message(dir: &Path, id: &str, model: &str) {
        fs::write(
            dir.join("messages").join(format!("{id}.json")),
            json!({"id": id, "role": "assistant", "extra": {"modelId": model}}).to_string(),
        )
        .unwrap();
    }

    fn rows(db: &Database) -> Vec<(String, String, String, i64, i64, i64, i64)> {
        let conn = db.conn.lock().unwrap();
        let mut stmt = conn
            .prepare("SELECT request_id, model, session_id, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens FROM proxy_request_logs WHERE data_source = 'codebuddy_ide_session' ORDER BY request_id")
            .unwrap();
        stmt.query_map([], |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get(2)?,
                row.get(3)?,
                row.get(4)?,
                row.get(5)?,
                row.get(6)?,
            ))
        })
        .unwrap()
        .map(Result::unwrap)
        .collect()
    }

    #[test]
    fn data_root_follows_the_plugin_per_platform() {
        let home = Path::new("/h");
        assert_eq!(
            data_root_for(home, "macos"),
            Path::new("/h/Library/Application Support/CodeBuddyExtension/Data")
        );
        assert_eq!(
            data_root_for(home, "windows"),
            Path::new("/h/AppData/Local/CodeBuddyExtension/Data")
        );
        assert_eq!(
            data_root_for(home, "linux"),
            Path::new("/h/.local/share/CodeBuddyExtension/Data")
        );
    }

    #[test]
    fn imports_finished_requests_once_with_fresh_input_and_message_model() {
        let root = tempfile::tempdir().unwrap();
        let conv = conversation(root.path(), "JetBrains", "c1");
        write_message(&conv, "m2", "custom-local:kimi-k3.1-pro");
        write_index(
            &conv,
            vec![
                request("r1", "complete", &["m1", "m2"], usage(1000, 600, 100, 50)),
                // Still running: its usage is not final yet.
                request("r2", "running", &["m3"], usage(10, 0, 0, 1)),
                // Finished without usage (e.g. failed before any model call).
                json!({"id": "r3", "type": "craft", "state": "complete", "startedAt": 1, "messages": []}),
            ],
        );
        let db = Database::memory().unwrap();
        assert_eq!(sync_root(&db, root.path()).unwrap().imported, 1);
        assert_eq!(
            rows(&db),
            vec![(
                "codebuddy-ide:r1".into(),
                "kimi-k3.1-pro".into(),
                "c1".into(),
                300,
                50,
                600,
                100
            )]
        );
        // Unchanged file is skipped outright.
        assert_eq!(sync_root(&db, root.path()).unwrap().files_scanned, 0);

        // The running request finishes; the file is rewritten whole.
        write_index(
            &conv,
            vec![
                request("r1", "complete", &["m1", "m2"], usage(1000, 600, 100, 50)),
                request("r2", "complete", &["m3"], usage(400, 0, 0, 9)),
            ],
        );
        let again = sync_root(&db, root.path()).unwrap();
        assert_eq!((again.imported, again.skipped), (1, 1));
        assert_eq!(rows(&db).len(), 2);
    }

    #[test]
    fn falls_back_to_the_selected_model_and_reads_every_ide() {
        let root = tempfile::tempdir().unwrap();
        let ide = conversation(root.path(), "CodeBuddyIDE", "c1");
        write_index(
            &ide,
            vec![request("a", "complete", &["gone"], usage(5, 0, 0, 1))],
        );
        fs::write(
            ide.parent().unwrap().join("index.json"),
            json!({"conversations": [{"id": "c1", "selectedModelId": "custom-local:glm-5.3"}]})
                .to_string(),
        )
        .unwrap();
        let vscode = root
            .path()
            .join("default")
            .join("VSCode")
            .join("L1VzZXJz")
            .join("history")
            .join("ws2")
            .join("c2");
        fs::create_dir_all(&vscode).unwrap();
        write_index(
            &vscode,
            vec![request("b", "complete", &[], usage(7, 0, 0, 2))],
        );
        fs::write(
            vscode.parent().unwrap().join("index.json"),
            json!({"conversations": [{"id": "c2", "modelMap": {"craft": "hy3"}}]}).to_string(),
        )
        .unwrap();

        let db = Database::memory().unwrap();
        assert_eq!(sync_root(&db, root.path()).unwrap().imported, 2);
        let models: Vec<String> = rows(&db).into_iter().map(|row| row.1).collect();
        assert_eq!(models, vec!["glm-5.3".to_string(), "hy3".to_string()]);
    }

    #[test]
    fn a_half_written_index_is_retried_later() {
        let root = tempfile::tempdir().unwrap();
        let conv = conversation(root.path(), "JetBrains", "c1");
        fs::write(conv.join("index.json"), "{\"requests\": [").unwrap();
        let db = Database::memory().unwrap();
        assert_eq!(sync_root(&db, root.path()).unwrap().imported, 0);
        write_index(
            &conv,
            vec![request("r1", "complete", &[], usage(5, 0, 0, 1))],
        );
        assert_eq!(sync_root(&db, root.path()).unwrap().imported, 1);
    }
}