refactor: remove Anthropic API integration, CLI agent only (ADR-0028)

Remove AIChatPanel, useAIChat hook, Rust ai_chat command, and
anthropic_key from settings. AI is now exclusively via Claude CLI
subprocess (AiPanel). Simplifies codebase and eliminates API key
management for users. ADR-0027 superseded.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Test
2026-03-29 15:05:56 +02:00
parent 85b545a0bc
commit d9254ffaf5
25 changed files with 67 additions and 1275 deletions

View File

@@ -1,386 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct AiChatRequest {
pub model: Option<String>,
pub messages: Vec<AiMessage>,
pub system: Option<String>,
pub max_tokens: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AiMessage {
pub role: String,
pub content: String,
}
#[derive(Debug, Serialize)]
pub struct AiChatResponse {
pub content: String,
pub model: String,
pub stop_reason: Option<String>,
}
#[derive(Debug, Deserialize)]
struct AnthropicResponse {
content: Vec<ContentBlock>,
model: String,
stop_reason: Option<String>,
}
#[derive(Debug, Deserialize)]
struct ContentBlock {
text: Option<String>,
}
#[derive(Debug, Serialize)]
struct AnthropicRequest {
model: String,
max_tokens: u32,
messages: Vec<AiMessage>,
#[serde(skip_serializing_if = "Option::is_none")]
system: Option<String>,
}
fn get_api_key() -> Result<String, String> {
std::env::var("ANTHROPIC_API_KEY")
.map_err(|_| "ANTHROPIC_API_KEY environment variable not set".to_string())
}
fn build_request(req: &AiChatRequest) -> AnthropicRequest {
AnthropicRequest {
model: req
.model
.clone()
.unwrap_or_else(|| "claude-3-5-haiku-20241022".to_string()),
max_tokens: req.max_tokens.unwrap_or(4096),
messages: req.messages.clone(),
system: req.system.clone(),
}
}
fn extract_response_text(resp: &AnthropicResponse) -> String {
resp.content
.iter()
.filter_map(|block| block.text.as_ref())
.cloned()
.collect::<Vec<_>>()
.join("")
}
pub async fn send_chat(req: AiChatRequest) -> Result<AiChatResponse, String> {
let api_key = get_api_key()?;
send_chat_with_base(req, "https://api.anthropic.com", &api_key).await
}
async fn send_chat_with_base(
req: AiChatRequest,
api_base: &str,
api_key: &str,
) -> Result<AiChatResponse, String> {
let anthropic_req = build_request(&req);
let client = reqwest::Client::new();
let response = client
.post(format!("{}/v1/messages", api_base))
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.header("content-type", "application/json")
.json(&anthropic_req)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(format!("Anthropic API error ({}): {}", status, body));
}
let anthropic_resp: AnthropicResponse = response
.json()
.await
.map_err(|e| format!("Failed to parse response: {}", e))?;
Ok(AiChatResponse {
content: extract_response_text(&anthropic_resp),
model: anthropic_resp.model,
stop_reason: anthropic_resp.stop_reason,
})
}
#[cfg(test)]
mod tests {
use super::*;
// ── Pure logic tests ─────────────────────────────────────────────────────
#[test]
fn test_build_request_defaults() {
let req = AiChatRequest {
model: None,
messages: vec![AiMessage {
role: "user".to_string(),
content: "Hello".to_string(),
}],
system: None,
max_tokens: None,
};
let built = build_request(&req);
assert_eq!(built.model, "claude-3-5-haiku-20241022");
assert_eq!(built.max_tokens, 4096);
assert!(built.system.is_none());
}
#[test]
fn test_build_request_custom() {
let req = AiChatRequest {
model: Some("claude-sonnet-4-20250514".to_string()),
messages: vec![],
system: Some("You are helpful".to_string()),
max_tokens: Some(1024),
};
let built = build_request(&req);
assert_eq!(built.model, "claude-sonnet-4-20250514");
assert_eq!(built.max_tokens, 1024);
assert_eq!(built.system.unwrap(), "You are helpful");
}
#[test]
fn test_extract_response_text() {
let resp = AnthropicResponse {
content: vec![
ContentBlock {
text: Some("Hello ".to_string()),
},
ContentBlock {
text: Some("world".to_string()),
},
ContentBlock { text: None },
],
model: "test".to_string(),
stop_reason: Some("end_turn".to_string()),
};
assert_eq!(extract_response_text(&resp), "Hello world");
}
#[test]
fn test_extract_response_text_empty() {
let resp = AnthropicResponse {
content: vec![],
model: "test".to_string(),
stop_reason: None,
};
assert_eq!(extract_response_text(&resp), "");
}
#[test]
fn test_extract_response_text_all_none() {
let resp = AnthropicResponse {
content: vec![ContentBlock { text: None }, ContentBlock { text: None }],
model: "test".to_string(),
stop_reason: None,
};
assert_eq!(extract_response_text(&resp), "");
}
// Mutex to serialize env-var tests and avoid race conditions in parallel test runs
static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn test_get_api_key_missing() {
let _guard = ENV_MUTEX.lock().unwrap();
// Temporarily clear the env var
let prev = std::env::var("ANTHROPIC_API_KEY").ok();
unsafe {
std::env::remove_var("ANTHROPIC_API_KEY");
}
let result = get_api_key();
// Restore
if let Some(val) = prev {
unsafe {
std::env::set_var("ANTHROPIC_API_KEY", val);
}
}
assert!(result.is_err());
assert!(result
.unwrap_err()
.contains("ANTHROPIC_API_KEY environment variable not set"));
}
#[test]
fn test_get_api_key_present() {
let _guard = ENV_MUTEX.lock().unwrap();
let prev = std::env::var("ANTHROPIC_API_KEY").ok();
unsafe {
std::env::set_var("ANTHROPIC_API_KEY", "sk-test-key-123");
}
let result = get_api_key();
if let Some(val) = prev {
unsafe {
std::env::set_var("ANTHROPIC_API_KEY", val);
}
} else {
unsafe {
std::env::remove_var("ANTHROPIC_API_KEY");
}
}
assert!(result.is_ok());
assert_eq!(result.unwrap(), "sk-test-key-123");
}
// ── HTTP mock tests ──────────────────────────────────────────────────────
#[tokio::test]
async fn test_send_chat_success() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v1/messages")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"id":"msg_01","type":"message","role":"assistant","content":[{"type":"text","text":"Hello there!"}],"model":"claude-3-5-haiku-20241022","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":5}}"#,
)
.create_async()
.await;
let req = AiChatRequest {
model: None,
messages: vec![AiMessage {
role: "user".to_string(),
content: "Say hello".to_string(),
}],
system: None,
max_tokens: None,
};
let result = send_chat_with_base(req, &server.url(), "sk-test-key").await;
mock.assert_async().await;
assert!(result.is_ok());
let resp = result.unwrap();
assert_eq!(resp.content, "Hello there!");
assert_eq!(resp.model, "claude-3-5-haiku-20241022");
assert_eq!(resp.stop_reason, Some("end_turn".to_string()));
}
#[tokio::test]
async fn test_send_chat_with_system_prompt() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v1/messages")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"id":"msg_02","type":"message","role":"assistant","content":[{"type":"text","text":"I am a helpful assistant."}],"model":"claude-sonnet-4-20250514","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":20,"output_tokens":8}}"#,
)
.create_async()
.await;
let req = AiChatRequest {
model: Some("claude-sonnet-4-20250514".to_string()),
messages: vec![AiMessage {
role: "user".to_string(),
content: "Who are you?".to_string(),
}],
system: Some("You are a helpful assistant.".to_string()),
max_tokens: Some(512),
};
let result = send_chat_with_base(req, &server.url(), "sk-key").await;
mock.assert_async().await;
assert!(result.is_ok());
let resp = result.unwrap();
assert_eq!(resp.model, "claude-sonnet-4-20250514");
assert_eq!(resp.content, "I am a helpful assistant.");
}
#[tokio::test]
async fn test_send_chat_api_error() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v1/messages")
.with_status(401)
.with_header("content-type", "application/json")
.with_body(r#"{"type":"error","error":{"type":"authentication_error","message":"Invalid API key"}}"#)
.create_async()
.await;
let req = AiChatRequest {
model: None,
messages: vec![AiMessage {
role: "user".to_string(),
content: "Hello".to_string(),
}],
system: None,
max_tokens: None,
};
let result = send_chat_with_base(req, &server.url(), "bad-key").await;
mock.assert_async().await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("Anthropic API error") && err.contains("401"),
"unexpected error: {}",
err
);
}
#[tokio::test]
async fn test_send_chat_rate_limit() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v1/messages")
.with_status(429)
.with_header("content-type", "application/json")
.with_body(r#"{"type":"error","error":{"type":"rate_limit_error","message":"Rate limit exceeded"}}"#)
.create_async()
.await;
let req = AiChatRequest {
model: None,
messages: vec![],
system: None,
max_tokens: None,
};
let result = send_chat_with_base(req, &server.url(), "sk-key").await;
mock.assert_async().await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("Anthropic API error") && err.contains("429"),
"unexpected error: {}",
err
);
}
#[tokio::test]
async fn test_send_chat_multiple_content_blocks() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v1/messages")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"id":"msg_03","type":"message","role":"assistant","content":[{"type":"text","text":"Part one. "},{"type":"text","text":"Part two."}],"model":"claude-3-5-haiku-20241022","stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":5,"output_tokens":10}}"#,
)
.create_async()
.await;
let req = AiChatRequest {
model: None,
messages: vec![AiMessage {
role: "user".to_string(),
content: "Give me two parts".to_string(),
}],
system: None,
max_tokens: None,
};
let result = send_chat_with_base(req, &server.url(), "sk-key").await;
mock.assert_async().await;
assert!(result.is_ok());
assert_eq!(result.unwrap().content, "Part one. Part two.");
}
}

View File

@@ -1,14 +1,8 @@
use crate::ai_chat::{AiChatRequest, AiChatResponse};
#[cfg(desktop)]
use crate::claude_cli::ClaudeStreamEvent;
use crate::claude_cli::{AgentStreamRequest, ChatStreamRequest, ClaudeCliStatus};
// ── AI / Claude commands (desktop) ──────────────────────────────────────────
#[tauri::command]
pub async fn ai_chat(request: AiChatRequest) -> Result<AiChatResponse, String> {
crate::ai_chat::send_chat(request).await
}
// ── Claude CLI commands (desktop) ──────────────────────────────────────────
#[cfg(desktop)]
#[tauri::command]

View File

@@ -1,4 +1,3 @@
pub mod ai_chat;
pub mod claude_cli;
mod commands;
pub mod frontmatter;
@@ -138,7 +137,6 @@ pub fn run() {
commands::get_conflict_mode,
commands::git_resolve_conflict,
commands::git_commit_conflict_resolution,
commands::ai_chat,
commands::check_claude_cli,
commands::stream_claude_chat,
commands::stream_claude_agent,

View File

@@ -293,7 +293,7 @@ fn build_note_menu(app: &App) -> MenuResult {
.id(EDIT_TOGGLE_RAW_EDITOR)
.accelerator("CmdOrCtrl+\\")
.build(app)?;
let toggle_ai_chat = MenuItemBuilder::new("Toggle AI Chat")
let toggle_ai_chat = MenuItemBuilder::new("Toggle AI Panel")
.id(VIEW_TOGGLE_AI_CHAT)
.accelerator("CmdOrCtrl+I")
.build(app)?;

View File

@@ -4,7 +4,6 @@ use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Settings {
pub anthropic_key: Option<String>,
pub openai_key: Option<String>,
pub google_key: Option<String>,
pub github_token: Option<String>,
@@ -40,10 +39,6 @@ fn save_settings_at(path: &PathBuf, settings: Settings) -> Result<(), String> {
// Trim whitespace and convert empty strings to None
let cleaned = Settings {
anthropic_key: settings
.anthropic_key
.map(|k| k.trim().to_string())
.filter(|k| !k.is_empty()),
openai_key: settings
.openai_key
.map(|k| k.trim().to_string())
@@ -132,7 +127,6 @@ mod tests {
#[test]
fn test_default_settings_all_none() {
let s = Settings::default();
assert!(s.anthropic_key.is_none());
assert!(s.openai_key.is_none());
assert!(s.google_key.is_none());
assert!(s.github_token.is_none());
@@ -148,7 +142,6 @@ mod tests {
#[test]
fn test_settings_json_roundtrip() {
let settings = Settings {
anthropic_key: Some("sk-ant-test123".to_string()),
openai_key: None,
google_key: Some("AIza-test".to_string()),
github_token: Some("gho_xyz789".to_string()),
@@ -161,7 +154,6 @@ mod tests {
};
let json = serde_json::to_string(&settings).unwrap();
let parsed: Settings = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.anthropic_key, settings.anthropic_key);
assert_eq!(parsed.google_key, settings.google_key);
assert_eq!(parsed.github_token, settings.github_token);
assert_eq!(parsed.github_username, settings.github_username);
@@ -176,13 +168,12 @@ mod tests {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("nonexistent.json");
let result = get_settings_at(&path).unwrap();
assert!(result.anthropic_key.is_none());
assert!(result.openai_key.is_none());
}
#[test]
fn test_save_and_load_preserves_values() {
let loaded = save_and_reload(Settings {
anthropic_key: Some("sk-ant-key".to_string()),
openai_key: Some("sk-openai".to_string()),
google_key: None,
github_token: Some("gho_token123".to_string()),
@@ -190,7 +181,6 @@ mod tests {
auto_pull_interval_minutes: Some(10),
..Default::default()
});
assert_eq!(loaded.anthropic_key.as_deref(), Some("sk-ant-key"));
assert_eq!(loaded.openai_key.as_deref(), Some("sk-openai"));
assert_eq!(loaded.github_token.as_deref(), Some("gho_token123"));
assert_eq!(loaded.github_username.as_deref(), Some("lucaong"));
@@ -200,12 +190,10 @@ mod tests {
#[test]
fn test_save_trims_whitespace() {
let loaded = save_and_reload(Settings {
anthropic_key: Some(" sk-ant-test ".to_string()),
github_token: Some(" gho_abc ".to_string()),
github_username: Some(" lucaong ".to_string()),
..Default::default()
});
assert_eq!(loaded.anthropic_key.as_deref(), Some("sk-ant-test"));
assert_eq!(loaded.github_token.as_deref(), Some("gho_abc"));
assert_eq!(loaded.github_username.as_deref(), Some("lucaong"));
}
@@ -213,12 +201,10 @@ mod tests {
#[test]
fn test_save_filters_empty_and_whitespace_only() {
let loaded = save_and_reload(Settings {
anthropic_key: Some("".to_string()),
openai_key: Some(" ".to_string()),
github_username: Some("".to_string()),
..Default::default()
});
assert!(loaded.anthropic_key.is_none());
assert!(loaded.openai_key.is_none());
assert!(loaded.github_username.is_none());
}
@@ -231,14 +217,14 @@ mod tests {
save_settings_at(
&path,
Settings {
anthropic_key: Some("key".to_string()),
openai_key: Some("key".to_string()),
..Default::default()
},
)
.unwrap();
assert!(path.exists());
assert_eq!(
get_settings_at(&path).unwrap().anthropic_key.as_deref(),
get_settings_at(&path).unwrap().openai_key.as_deref(),
Some("key")
);
}
@@ -273,9 +259,9 @@ mod tests {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("settings.json");
// Simulate old settings.json without telemetry fields
fs::write(&path, r#"{"anthropic_key":"sk-test"}"#).unwrap();
fs::write(&path, r#"{"openai_key":"sk-test"}"#).unwrap();
let loaded = get_settings_at(&path).unwrap();
assert_eq!(loaded.anthropic_key.as_deref(), Some("sk-test"));
assert_eq!(loaded.openai_key.as_deref(), Some("sk-test"));
assert!(loaded.telemetry_consent.is_none());
assert!(loaded.crash_reporting_enabled.is_none());
assert!(loaded.analytics_enabled.is_none());