Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions src-tauri/src/claude.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! The Claude Code panel: runs the user's own `claude` CLI in its documented streaming JSON mode
//! (`-p --input-format stream-json --output-format stream-json`), the same way Anthropic's Agent SDK drives it.
//!
//! Rust only carries lines: every JSON line the CLI prints goes to the panel unchanged, and the panel's messages
//! (prompts, permission answers, stop) are written to the CLI's stdin as one JSON line each. The user signs in to
//! Claude in the CLI itself; Veyra never sees or stores Claude credentials.
use super::{err, plain, quiet, root, Workspace};
use serde::Deserialize;
use std::{
collections::HashMap,
io::{BufRead, BufReader, Write},
process::{Child, ChildStdin, Stdio},
sync::{atomic::{AtomicU64, Ordering}, Arc, Mutex},
};
use tauri::{ipc::Channel, Manager, State};

type Result<T> = std::result::Result<T, String>;

struct Chat { child: Child, stdin: ChildStdin, generation: u64 }
impl Drop for Chat { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } }

#[derive(Default)]
pub struct ClaudeState { chats: Mutex<HashMap<u32, Chat>> }
static GENERATION: AtomicU64 = AtomicU64::new(1);

/// How the panel wants Claude Code started.
#[derive(Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct StartOptions {
/// default (ask before edits and commands), acceptEdits (edit files without asking) or plan (read and plan only).
mode: String,
/// A session id to continue an earlier conversation.
resume: Option<String>,
/// A model alias or id, like "sonnet" or "claude-opus-5-5"; empty for Claude Code's default.
model: Option<String>,
}

const MODES: [&str; 3] = ["default", "acceptEdits", "plan"];

/// The command line for a chat. Values are checked so nothing the panel sends can become another flag.
pub(crate) fn chat_args(options: &StartOptions) -> Result<Vec<String>> {
if !MODES.contains(&options.mode.as_str()) { return Err(format!("Unknown permission mode: {}", options.mode)); }
let mut args: Vec<String> = [
"-p", "--output-format", "stream-json", "--verbose", "--input-format", "stream-json",
"--include-partial-messages", "--permission-prompt-tool=stdio", "--permission-mode",
].iter().map(|s| s.to_string()).collect();
args.push(options.mode.clone());
if let Some(id) = options.resume.as_deref().filter(|id| !id.is_empty()) {
let ok = id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') && !id.starts_with('-');
if !ok { return Err("That conversation id isn't valid.".into()); }
args.push("--resume".into()); args.push(id.into());
}
if let Some(model) = options.model.as_deref().map(str::trim).filter(|m| !m.is_empty()) {
let ok = model.len() <= 80 && !model.starts_with('-') && model.chars().all(|c| c.is_ascii_alphanumeric() || "-._:[]".contains(c));
if !ok { return Err("That model name isn't valid.".into()); }
args.push("--model".into()); args.push(model.into());
}
Ok(args)
}

/// A message for the CLI must be one JSON object on one line.
pub(crate) fn check_line(message: &str) -> Result<()> {
if message.contains('\n') || message.contains('\r') { return Err("A message must be a single line.".into()); }
match serde_json::from_str::<serde_json::Value>(message) {
Ok(serde_json::Value::Object(_)) => Ok(()),
_ => Err("A message must be a JSON object.".into()),
}
}

/// The handshake the Agent SDK sends first; the CLI answers with a control_response.
const INITIALIZE: &str = r#"{"type":"control_request","request_id":"veyra-initialize","request":{"subtype":"initialize"}}"#;

/// Starts Claude Code for chat `id` in the open folder. Every line it prints is sent on `output`; when it stops,
/// a final {"type":"veyra_exit","code":…,"stderr":…} line is sent.
#[tauri::command]
pub async fn claude_chat_start(app: tauri::AppHandle, workspace: State<'_, Workspace>, state: State<'_, ClaudeState>, id: u32, options: StartOptions, output: Channel<String>) -> Result<()> {
let root = root(&workspace)?;
let args = chat_args(&options)?;
let program = tauri::async_runtime::spawn_blocking(super::cli::claude_path).await.map_err(err)?
.ok_or("Claude Code isn't installed. Install it from the Claude panel or the Extensions view.")?;
let mut child = quiet(&program).args(&args).current_dir(plain(&root))
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
.spawn().map_err(|e| format!("Couldn't start Claude Code: {e}"))?;
let mut stdin = child.stdin.take().ok_or("No stdin")?;
let stdout = child.stdout.take().ok_or("No stdout")?;
let stderr = child.stderr.take().ok_or("No stderr")?;
stdin.write_all(INITIALIZE.as_bytes()).and_then(|_| stdin.write_all(b"\n")).and_then(|_| stdin.flush()).map_err(err)?;
let generation = GENERATION.fetch_add(1, Ordering::SeqCst);
// Starting a chat that is already running replaces it (the old process is killed when dropped).
state.chats.lock().map_err(err)?.insert(id, Chat { child, stdin, generation });

// Keep the end of stderr, to explain a failed start.
let log = Arc::new(Mutex::new(String::new()));
let log_writer = log.clone();
std::thread::spawn(move || {
for line in BufReader::new(stderr).lines().map_while(std::result::Result::ok) {
if let Ok(mut text) = log_writer.lock() { text.push_str(&line); text.push('\n'); if text.len() > 4000 { let cut = text.len() - 4000; text.drain(..cut); } }
}
});
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(std::result::Result::ok) {
if !line.trim().is_empty() && output.send(line).is_err() { break; }
}
// Only this run's entry is removed: a newer chat with the same id may have replaced it already.
let state = app.state::<ClaudeState>();
let code = state.chats.lock().ok().and_then(|mut chats| {
if chats.get(&id).map(|c| c.generation) == Some(generation) { chats.remove(&id) } else { None }
}).and_then(|mut chat| chat.child.wait().ok()).and_then(|status| status.code());
let stderr = log.lock().map(|t| t.clone()).unwrap_or_default();
let _ = output.send(serde_json::json!({ "type": "veyra_exit", "code": code, "stderr": stderr }).to_string());
});
Ok(())
}

/// Writes one JSON message (a prompt, a permission answer, an interrupt) to the chat's Claude Code.
#[tauri::command]
pub fn claude_chat_send(state: State<'_, ClaudeState>, id: u32, message: String) -> Result<()> {
check_line(&message)?;
let mut chats = state.chats.lock().map_err(err)?;
let chat = chats.get_mut(&id).ok_or("Claude Code isn't running for this chat.")?;
chat.stdin.write_all(message.as_bytes()).and_then(|_| chat.stdin.write_all(b"\n")).and_then(|_| chat.stdin.flush()).map_err(err)
}

/// Stops the chat's Claude Code. The conversation can be continued later with its session id.
#[tauri::command]
pub fn claude_chat_stop(state: State<'_, ClaudeState>, id: u32) { if let Ok(mut chats) = state.chats.lock() { chats.remove(&id); } }

#[cfg(test)]
mod tests {
use super::*;
fn options(mode: &str, resume: Option<&str>, model: Option<&str>) -> StartOptions {
StartOptions { mode: mode.into(), resume: resume.map(Into::into), model: model.map(Into::into) }
}

#[test] fn args_drive_the_streaming_json_mode_like_the_agent_sdk() {
let args = chat_args(&options("default", None, None)).unwrap();
assert_eq!(args, ["-p", "--output-format", "stream-json", "--verbose", "--input-format", "stream-json", "--include-partial-messages", "--permission-prompt-tool=stdio", "--permission-mode", "default"]);
let args = chat_args(&options("acceptEdits", Some("4f1c9a2e-77b0-4c1d-9d1e-0a1b2c3d4e5f"), Some("claude-opus-5-5"))).unwrap();
assert!(args.ends_with(&["--resume".into(), "4f1c9a2e-77b0-4c1d-9d1e-0a1b2c3d4e5f".into(), "--model".into(), "claude-opus-5-5".into()]));
assert!(chat_args(&options("plan", Some(""), Some(" "))).unwrap().ends_with(&["--permission-mode".into(), "plan".into()]));
}

#[test] fn nothing_from_the_panel_can_become_a_flag() {
assert!(chat_args(&options("bypassPermissions", None, None)).is_err(), "only the three modes the panel offers");
assert!(chat_args(&options("default", Some("--dangerously-skip-permissions"), None)).is_err());
assert!(chat_args(&options("default", Some("a b"), None)).is_err());
assert!(chat_args(&options("default", None, Some("--settings=x"))).is_err());
assert!(chat_args(&options("default", None, Some("opus; rm -rf /"))).is_err());
assert!(chat_args(&options("default", None, Some("claude-sonnet-5-5[1m]"))).is_ok());
}

#[test] fn only_single_json_objects_are_written() {
assert!(check_line(r#"{"type":"user"}"#).is_ok());
assert!(check_line("{\"a\":1}\n{\"b\":2}").is_err());
assert!(check_line("[1,2]").is_err());
assert!(check_line("hello").is_err());
assert!(check_line(INITIALIZE).is_ok());
}
}
3 changes: 3 additions & 0 deletions src-tauri/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ fn version_of(path: &Path) -> Option<String> {
output.status.success().then(|| parse_version(&String::from_utf8_lossy(&output.stdout))).filter(|v| !v.is_empty())
}

/// The first working Claude Code on this computer, for the Claude panel.
pub(crate) fn claude_path() -> Option<PathBuf> { claude_candidates().into_iter().find(|path| version_of(path).is_some()) }

#[tauri::command]
pub async fn claude_code_status() -> Result<CliStatus> {
tauri::async_runtime::spawn_blocking(|| {
Expand Down
5 changes: 3 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use tauri::{Emitter, Manager, State, ipc::Channel};
use tauri::menu::{MenuBuilder, MenuItem, SubmenuBuilder};
use tauri_plugin_dialog::DialogExt;
mod account;
mod claude;
mod cli;
mod dap;
mod health;
Expand Down Expand Up @@ -591,7 +592,7 @@ fn quit(app: tauri::AppHandle, state: State<Workspace>) { state.dirty.store(fals

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default().manage(Workspace::default()).manage(account::AccountState::default()).manage(lsp::LspState::default()).manage(dap::DapState::default()).manage(live::LiveState::default())
tauri::Builder::default().manage(Workspace::default()).manage(account::AccountState::default()).manage(lsp::LspState::default()).manage(claude::ClaudeState::default()).manage(dap::DapState::default()).manage(live::LiveState::default())
// Opens links (sign in, Live Server pages, extension homepages) in the default browser.
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
Expand All @@ -606,7 +607,7 @@ pub fn run() {
Ok(())
})
.on_menu_event(|app,event|{let _=app.emit("menu-command",event.id().as_ref());})
.invoke_handler(tauri::generate_handler![choose_folder, open_folder, platform_info, list_directory, read_file, read_file_base64, save_file, create_entry, rename_file, trash_file, copy_entry, duplicate_entry, reveal_in_finder, project_files, search_workspace, replace_in_files, git_status, git_diff, git_show, git_stage_all, git_unstage_all, git_discard_all, git_branches, git_switch, git_stash, git_file_history, health::health_check, lsp::lsp_status, lsp::lsp_install, lsp::lsp_uninstall, lsp::lsp_start, lsp::lsp_send, lsp::lsp_stop, lsp::prettier_format, cli::claude_code_status, dap::dap_status, dap::dap_install, dap::dap_uninstall, dap::dap_start, dap::dap_send, dap::dap_stop, live::live_start, live::live_stop, live::live_status, git_stage, git_unstage, git_discard, git_commit, git_log, git_graph, github_info, github_login, github_open, git_remote_action, terminal_start, terminal_write, terminal_resize, terminal_stop, set_dirty, quit, account::veyra_sign_in, account::veyra_account, account::veyra_sign_out])
.invoke_handler(tauri::generate_handler![choose_folder, open_folder, platform_info, list_directory, read_file, read_file_base64, save_file, create_entry, rename_file, trash_file, copy_entry, duplicate_entry, reveal_in_finder, project_files, search_workspace, replace_in_files, git_status, git_diff, git_show, git_stage_all, git_unstage_all, git_discard_all, git_branches, git_switch, git_stash, git_file_history, health::health_check, lsp::lsp_status, lsp::lsp_install, lsp::lsp_uninstall, lsp::lsp_start, lsp::lsp_send, lsp::lsp_stop, lsp::prettier_format, cli::claude_code_status, claude::claude_chat_start, claude::claude_chat_send, claude::claude_chat_stop, dap::dap_status, dap::dap_install, dap::dap_uninstall, dap::dap_start, dap::dap_send, dap::dap_stop, live::live_start, live::live_stop, live::live_status, git_stage, git_unstage, git_discard, git_commit, git_log, git_graph, github_info, github_login, github_open, git_remote_action, terminal_start, terminal_write, terminal_resize, terminal_stop, set_dirty, quit, account::veyra_sign_in, account::veyra_account, account::veyra_sign_out])
.on_window_event(|window, event| { if let tauri::WindowEvent::CloseRequested { api, .. } = event { if window.state::<Workspace>().dirty.load(Ordering::SeqCst) { api.prevent_close(); let _ = window.emit("confirm-quit", ()); } } })
.build(tauri::generate_context!()).expect("error while running Veyra")
.run(|app, event| { if let tauri::RunEvent::ExitRequested { api, .. } = event { if app.state::<Workspace>().dirty.load(Ordering::SeqCst) { api.prevent_exit(); let _ = app.emit("confirm-quit", ()); } } });
Expand Down
Loading
Loading