diff --git a/src-tauri/src/claude.rs b/src-tauri/src/claude.rs new file mode 100644 index 0000000..95e23b3 --- /dev/null +++ b/src-tauri/src/claude.rs @@ -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 = std::result::Result; + +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> } +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, + /// A model alias or id, like "sonnet" or "claude-opus-5-5"; empty for Claude Code's default. + model: Option, +} + +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> { + if !MODES.contains(&options.mode.as_str()) { return Err(format!("Unknown permission mode: {}", options.mode)); } + let mut args: Vec = [ + "-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::(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) -> 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::(); + 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()); + } +} diff --git a/src-tauri/src/cli.rs b/src-tauri/src/cli.rs index 999ff12..a55f17f 100644 --- a/src-tauri/src/cli.rs +++ b/src-tauri/src/cli.rs @@ -30,6 +30,9 @@ fn version_of(path: &Path) -> Option { 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 { claude_candidates().into_iter().find(|path| version_of(path).is_some()) } + #[tauri::command] pub async fn claude_code_status() -> Result { tauri::async_runtime::spawn_blocking(|| { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5e133d3..7e46f1a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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; @@ -591,7 +592,7 @@ fn quit(app: tauri::AppHandle, state: State) { 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()) @@ -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::().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::().dirty.load(Ordering::SeqCst) { api.prevent_exit(); let _ = app.emit("confirm-quit", ()); } } }); diff --git a/src/App.tsx b/src/App.tsx index 6ffe042..27b215a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -47,6 +47,9 @@ import {startAutoRenameTag} from './features/autoRenameTag'; import {startPathIntellisense} from './features/pathIntellisense'; import {startNpmIntellisense} from './features/npmIntellisense'; import {TodoPanel} from './TodoPanel'; +import {ClaudePanel,type ClaudeRequest} from './claude/ClaudePanel'; +import type {EditorContext} from './claude/protocol'; +import {Sparkles} from "lucide-react"; import {ListTodo} from "lucide-react"; import {SettingsPanel} from './SettingsPanel'; import {readPreferences,rulerColumns} from './preferences'; @@ -148,6 +151,13 @@ export default function App() { const sidebarOpen = useRef(true), sidebarStarted = useRef(false), panelStarted = useRef(false); const [sidebarWidth, setSidebarWidth] = useState(258); const [bottom, setBottom] = useState<"terminal"|"problems"|"todo"|"debug"|null>(null); + // Claude Code panel, on the right. Mounted on first open and then kept, so a conversation survives closing it. + const [claudeOpen,setClaudeOpen]=useState(false); + const [claudeMounted,setClaudeMounted]=useState(false); + const [claudeWidth,setClaudeWidth]=useState(()=>{const w=Number(localStorage.getItem("veyra.claude.width"));return w>=300&&w<=760?w:420;}); + const [claudeRequest,setClaudeRequest]=useState(null); + const [claudeContext,setClaudeContext]=useState(); + const claudeTimer=useRef(undefined); const [todoCount, setTodoCount] = useState(null); const [recentProjects, setRecentProjects] = useState(loadRecentProjects); const [terminals, setTerminals] = useState>([]); @@ -516,6 +526,21 @@ export default function App() { /** Auto save only clean saves: skip files that changed on disk, which need a manual decision. */ async function autoSaveAll(){for(const tab of state.current.tabs.filter(tab=>dirty(tab)&&!tab.external))await saveTab(tab.path);} function newTerminal(){if(!root){setStatus("Open a workspace to start a terminal");return;}const id=terminalSequence.current++;setTerminals(all=>[...all,{id,name:`${shellName} ${all.length+1}`}]);setActiveTerminal(id);setBottom("terminal");setStatus("New terminal started");} + /** The open file, its selection and (optionally) the editor's problems there, for Claude. */ + function editorContext(withProblems=false):EditorContext|undefined{ + const instance=editor.current,path=state.current.active,model=instance?.getModel(); + if(!instance||!model||!path||path.startsWith(PAGE_PREFIX))return undefined; + const range=instance.getSelection();const text=range&&!range.isEmpty()?model.getValueInRange(range):""; + const selection=text.trim()&&range?{text:text.slice(0,20000),startLine:range.startLineNumber,endLine:range.endLineNumber}:undefined; + const [first,last]=selection?[selection.startLine,selection.endLine]:[1,model.getLineCount()]; + const problems=withProblems?monaco.editor.getModelMarkers({resource:model.uri}).filter(m=>m.severity>=monaco.MarkerSeverity.Warning&&m.startLineNumber>=first&&m.startLineNumber<=last).map(m=>({line:m.startLineNumber,message:m.message,severity:m.severity===monaco.MarkerSeverity.Error?"error":"warning"})):undefined; + return {path,language:model.getLanguageId(),selection,problems}; + } + function openClaude(){setClaudeMounted(true);setClaudeOpen(true);} + function toggleClaude(){setClaudeMounted(true);setClaudeOpen(open=>!open);} + /** Opens Claude with the selection attached: send=false puts the text in the box to finish, send=true sends it. */ + function askClaude(text:string,send:boolean,withProblems=false){const context=editorContext(withProblems);openClaude();setClaudeRequest({text,context,send,nonce:Date.now()});} + const FIX_PROMPT="Fix the problems the editor reports here. Explain the cause in a sentence, then make the fix."; function showTerminal() {if(!root){setStatus("Open a workspace to start a terminal");return;}if(!terminals.length)newTerminal();else{setActiveTerminal(current=>current??terminals[0].id);setBottom("terminal");}} function closeTerminal(id:number){void invoke("terminal_stop",{sessionId:id});setTerminals(all=>{const index=all.findIndex(item=>item.id===id);const next=all.filter(item=>item.id!==id);if(activeTerminal===id)setActiveTerminal(next[Math.min(index,next.length-1)]?.id??null);if(!next.length)setBottom(null);return next;});} function renameTerminal(id:number){const current=terminals.find(item=>item.id===id);if(!current)return;const name=window.prompt("Terminal name",current.name)?.trim();if(name)setTerminals(all=>all.map(item=>item.id===id?{...item,name}:item));} @@ -548,7 +573,7 @@ export default function App() { {name:"Format document",shortcut:"⇧⌥F",run:()=>editor.current?.getAction("editor.action.formatDocument")?.run()}, {name:"Reload file from disk",shortcut:"",run:reload},{name:"Rename file",shortcut:"",run:rename}, {name:"Move file to Trash",shortcut:"",run:trash},{name:"Open terminal",shortcut:"⌃`",run:showTerminal}, - {name:"Toggle split editor",shortcut:"",run:()=>setSplit(!split)},{name:"Toggle sidebar",shortcut:"⌘B",run:()=>setSidebar(v=>!v)},{name:"New terminal",shortcut:"⌃⇧`",run:newTerminal},{name:"Search in files",shortcut:"⇧⌘F",run:openSearch},{name:"Toggle word wrap",shortcut:"⌥Z",run:()=>setPreferences(p=>({...p,wrap:!p.wrap}))},{name:"Toggle minimap",shortcut:"",run:()=>setPreferences(p=>({...p,minimap:!p.minimap}))},{name:"Toggle light / dark theme",shortcut:"",run:()=>setPreferences(p=>({...p,light:!p.light}))},{name:"Go to line",shortcut:"⌃G",run:()=>setPalette(":")},{name:"Go to symbol in editor",shortcut:"⇧⌘O",run:()=>setPalette("@")},{name:"Show source control",shortcut:"⌃⇧G",run:()=>{setPanel("git");setSidebar(true);void refreshGit();}},{name:"Show health monitor",shortcut:"",run:()=>{setPanel("health");setSidebar(true);void checkHealth();}},{name:"Close folder",shortcut:"",run:closeFolder},{name:"Settings",shortcut:"⌘,",run:()=>{setPanel("settings");setSidebar(true);}},{name:"Check for updates",shortcut:"",run:()=>setUpdateCheck(n=>n+1)},{name:"Start debugging",shortcut:"F5",run:()=>void debugKey(new KeyboardEvent("keydown",{key:"F5"}))},{name:"Toggle breakpoint",shortcut:"F9",run:()=>toggleBreakpointAtCursor(editor.current,state.current.active)},{name:"Stop debugging",shortcut:"⇧F5",run:()=>void stopDebugging()},{name:"Show Run and Debug",shortcut:"",run:()=>{setPanel("debug");setSidebar(true);}},{name:"Live Server: Open with Live Server",shortcut:"Alt+L Alt+O",run:()=>openLive(state.current.active)},{name:"Live Server: Stop Live Server",shortcut:"Alt+L Alt+C",run:stopLive}, + {name:"Toggle split editor",shortcut:"",run:()=>setSplit(!split)},{name:"Claude Code: Open",shortcut:"⌥⌘C",run:openClaude},{name:"Claude Code: Ask about the selection",shortcut:"⌥⌘K",run:()=>askClaude("",false)},{name:"Claude Code: Fix problems in this file",shortcut:"",run:()=>askClaude(FIX_PROMPT,true,true)},{name:"Toggle sidebar",shortcut:"⌘B",run:()=>setSidebar(v=>!v)},{name:"New terminal",shortcut:"⌃⇧`",run:newTerminal},{name:"Search in files",shortcut:"⇧⌘F",run:openSearch},{name:"Toggle word wrap",shortcut:"⌥Z",run:()=>setPreferences(p=>({...p,wrap:!p.wrap}))},{name:"Toggle minimap",shortcut:"",run:()=>setPreferences(p=>({...p,minimap:!p.minimap}))},{name:"Toggle light / dark theme",shortcut:"",run:()=>setPreferences(p=>({...p,light:!p.light}))},{name:"Go to line",shortcut:"⌃G",run:()=>setPalette(":")},{name:"Go to symbol in editor",shortcut:"⇧⌘O",run:()=>setPalette("@")},{name:"Show source control",shortcut:"⌃⇧G",run:()=>{setPanel("git");setSidebar(true);void refreshGit();}},{name:"Show health monitor",shortcut:"",run:()=>{setPanel("health");setSidebar(true);void checkHealth();}},{name:"Close folder",shortcut:"",run:closeFolder},{name:"Settings",shortcut:"⌘,",run:()=>{setPanel("settings");setSidebar(true);}},{name:"Check for updates",shortcut:"",run:()=>setUpdateCheck(n=>n+1)},{name:"Start debugging",shortcut:"F5",run:()=>void debugKey(new KeyboardEvent("keydown",{key:"F5"}))},{name:"Toggle breakpoint",shortcut:"F9",run:()=>toggleBreakpointAtCursor(editor.current,state.current.active)},{name:"Stop debugging",shortcut:"⇧F5",run:()=>void stopDebugging()},{name:"Show Run and Debug",shortcut:"",run:()=>{setPanel("debug");setSidebar(true);}},{name:"Live Server: Open with Live Server",shortcut:"Alt+L Alt+O",run:()=>openLive(state.current.active)},{name:"Live Server: Stop Live Server",shortcut:"Alt+L Alt+C",run:stopLive}, ]; const paletteCommands:PaletteCommand[]=commands.map(command=>({...command,id:command.name})); @@ -733,8 +758,19 @@ export default function App() { instance.addAction({id:'veyra.live.open',label:'Open with Live Server',precondition:'editorLangId == html',contextMenuGroupId:'navigation',contextMenuOrder:2,run:()=>openLive(state.current.active)}); instance.addAction({id:'veyra.live.go',label:'Live Server: Go Live',keybindings:[monaco.KeyMod.chord(monaco.KeyMod.Alt|monaco.KeyCode.KeyL,monaco.KeyMod.Alt|monaco.KeyCode.KeyO)],run:()=>openLive(state.current.active)}); instance.addAction({id:'veyra.live.stop',label:'Live Server: Stop',keybindings:[monaco.KeyMod.chord(monaco.KeyMod.Alt|monaco.KeyCode.KeyL,monaco.KeyMod.Alt|monaco.KeyCode.KeyC)],run:()=>stopLive()}); + // Claude Code: ask about the selection, or fix what the editor reports. + instance.onDidChangeCursorSelection(()=>{clearTimeout(claudeTimer.current);claudeTimer.current=window.setTimeout(()=>setClaudeContext(editorContext()),200);}); + instance.addAction({id:'veyra.claude.ask',label:'Ask Claude About This',contextMenuGroupId:'navigation',contextMenuOrder:0.5,keybindings:[monaco.KeyMod.CtrlCmd|monaco.KeyMod.Alt|monaco.KeyCode.KeyK],run:()=>askClaude("",false)}); + instance.addAction({id:'veyra.claude.fix',label:'Fix with Claude',contextMenuGroupId:'navigation',contextMenuOrder:0.6,run:()=>askClaude(FIX_PROMPT,true,true)}); instance.focus(); }; + // Ctrl+Alt+C (⌥⌘C) shows or hides Claude Code. (Ctrl+Esc, the Claude Code shortcut in VS Code, opens the Start menu on Windows.) + useEffect(()=>{ + const key=(e:KeyboardEvent)=>{if((e.ctrlKey||e.metaKey)&&e.altKey&&!e.shiftKey&&e.code==="KeyC"){e.preventDefault();e.stopPropagation();toggleClaude();}}; + window.addEventListener("keydown",key,true);return()=>window.removeEventListener("keydown",key,true); + },[]); + // The chip in the Claude panel follows the file you switch to. + useEffect(()=>{const timer=window.setTimeout(()=>setClaudeContext(editorContext()),120);return()=>clearTimeout(timer);},[active]); function visibleEntries(parent=""):Entry[]{return (tree[parent]||[]).flatMap(entry=>[entry,...(entry.directory&&expanded.has(entry.path)?visibleEntries(entry.path):[])]);} function selectEntry(entry:Entry,event:React.MouseEvent){ if(event.metaKey||event.ctrlKey){setSelectedPaths(previous=>{const next=new Set(previous);if(next.has(entry.path))next.delete(entry.path);else next.add(entry.path);return next;});setSelectedPath(entry.path);return true;} @@ -815,7 +851,11 @@ export default function App() { {bottom==="todo"&&void openFile(path,line,column)} onCount={setTodoCount}/>} {bottom==="problems"&&
{problems.length?problems.map((p,i)=>):
No diagnostics reported for open files.
}
} - + {claudeMounted&&
+
e.currentTarget.setPointerCapture(e.pointerId)} onPointerMove={e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;const right=e.currentTarget.parentElement!.getBoundingClientRect().right;setClaudeWidth(Math.round(Math.max(300,Math.min(760,right-e.clientX))));}} onPointerUp={e=>{e.currentTarget.releasePointerCapture(e.pointerId);localStorage.setItem("veyra.claude.width",String(claudeWidth));}}/> + setClaudeOpen(false)} onOpenFile={(path,line)=>void openFile(path,line)} onFilesChanged={()=>{void diskCheck.current();void refreshGit();void refresh();}}/> +
} +
{root?<>{projectName}{file&&!activePage&&file.path.split("/").map((part,i)=>{part})}:Veyra Studio}{(branchInfo.ahead>0||branchInfo.behind>0)&&}{busy?"Opening workspace…":status}{root&&}{position.lineNumber}:{position.column}{file&&!activePage&&{file.text.includes("\r\n")?"CRLF":"LF"}}UTF-8{preferences.insertSpaces?`${preferences.tabSize} spaces`:"Tab"}{file?languageFor(file.path):"Veyra"}{countDirty?countDirty+" unsaved":"All saved"}
diff --git a/src/claude/ClaudePanel.tsx b/src/claude/ClaudePanel.tsx new file mode 100644 index 0000000..9514596 --- /dev/null +++ b/src/claude/ClaudePanel.tsx @@ -0,0 +1,297 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Channel, invoke } from "@tauri-apps/api/core"; +import { openUrl } from "@tauri-apps/plugin-opener"; +import { marked } from "marked"; +import DOMPurify from "dompurify"; +import { Bot, Check, ChevronDown, ChevronRight, CircleAlert, Download, FileCode2, FilePen, Globe, History, ListChecks, LoaderCircle, LogIn, Plus, RefreshCw, Search, Send, ShieldAlert, Sparkles, Square, SquareTerminal, X } from "lucide-react"; +import { installTool, onToolsChange, openClaudeCode, refreshTools, toolState } from "../lsp/tools"; +import { + MODES, apply, ask, contextLabel, decide, describeTool, editLines, emptyChat, interruptMessage, modeMessage, permissionAnswer, promptWithContext, + todos, toSaved, upsertSaved, userMessage, type Chat, type EditorContext, type Item, type Mode, type Saved, +} from "./protocol"; +import "./claude.css"; + +/** A prompt sent from elsewhere in Veyra (the editor's "Ask Claude" and "Fix with Claude"). */ +export type ClaudeRequest = { text: string; context?: EditorContext; send: boolean; nonce: number }; + +type Props = { + root: string; + visible: boolean; + /** What's selected in the editor now, offered as a chip on the next prompt. */ + context?: EditorContext; + request: ClaudeRequest | null; + onClose: () => void; + /** Opens a workspace-relative file, optionally at a line. */ + onOpenFile: (path: string, line?: number) => void; + /** Claude changed these files (absolute or relative paths): reload them. */ + onFilesChanged: (paths: string[]) => void; +}; + +const CHAT_ID = 1; +const MODELS = [{ id: "", label: "Default model" }, { id: "opus", label: "Opus" }, { id: "sonnet", label: "Sonnet" }, { id: "haiku", label: "Haiku" }]; +const SUGGESTIONS = ["Explain how this project is organised", "Find bugs in the file I have open", "Write tests for the selected code", "What changed since the last commit?"]; +const storageKey = (root: string) => "veyra.claude.chats:" + root; +const prefsKey = "veyra.claude.prefs"; + +function readSaved(root: string): Saved[] { try { const v = JSON.parse(localStorage.getItem(storageKey(root)) || "[]"); return Array.isArray(v) ? v : []; } catch { return []; } } +function writeSaved(root: string, list: Saved[]) { try { localStorage.setItem(storageKey(root), JSON.stringify(list)); } catch { /* storage full: history is a nicety */ } } +function readPrefs(): { mode: Mode; model: string } { try { const v = JSON.parse(localStorage.getItem(prefsKey) || "{}"); return { mode: MODES.some(m => m.id === v.mode) ? v.mode : "default", model: typeof v.model === "string" ? v.model : "" }; } catch { return { mode: "default", model: "" }; } } + +/** A path inside the workspace, relative, or null for anything outside it. */ +function relative(path: string, root: string): string | null { + const p = path.replace(/\\/g, "/"), r = root.replace(/\\/g, "/").replace(/\/$/, ""); + const rel = p.toLowerCase().startsWith(r.toLowerCase() + "/") ? p.slice(r.length + 1) : /^([a-z]:)?\//i.test(p) ? null : p; + return rel && !rel.split("/").includes("..") ? rel : null; +} + +/** Sanitised Markdown with a Copy button on each code block; links open in the browser. */ +function Markdown({ text }: { text: string }) { + const ref = useRef(null); + const html = useMemo(() => DOMPurify.sanitize(marked.parse(text, { async: false, gfm: true, breaks: false }) as string), [text]); + useEffect(() => { + for (const pre of ref.current?.querySelectorAll("pre") || []) { + if (pre.querySelector(".claude-copy")) continue; + const button = document.createElement("button"); + button.className = "claude-copy"; button.type = "button"; button.textContent = "Copy"; button.setAttribute("aria-label", "Copy code"); + button.onclick = () => { void navigator.clipboard.writeText(pre.querySelector("code")?.textContent ?? pre.textContent ?? "").then(() => { button.textContent = "Copied"; setTimeout(() => { button.textContent = "Copy"; }, 1200); }); }; + pre.appendChild(button); + } + }, [html]); + return
{ + const anchor = (event.target as HTMLElement).closest("a"); if (!anchor) return; + event.preventDefault(); + const href = anchor.getAttribute("href") || ""; + if (/^https?:/i.test(href)) void openUrl(href).catch(() => { }); + }} />; +} + +function Diff({ name, input, open }: { name: string; input: Record; open?: boolean }) { + const diff = editLines(name, input, 200); + const [shown, setShown] = useState(!!open); + if (!diff.lines.length) return null; + return
+ + {shown &&
{diff.lines.map((l, i) => 
{l.sign}{l.text || " "}
)}{diff.truncated &&
…
}
} +
; +} + +const toolIcon = (name: string) => name === "Read" ? FileCode2 : ["Edit", "MultiEdit", "Write", "NotebookEdit"].includes(name) ? FilePen : name === "Bash" ? SquareTerminal : name === "Grep" || name === "Glob" ? Search : name.startsWith("Web") ? Globe : name === "TodoWrite" ? ListChecks : name === "Task" || name === "Agent" ? Bot : Sparkles; + +export function ClaudePanel({ root, visible, context, request, onClose, onOpenFile, onFilesChanged }: Props) { + const [chat, setChat] = useState(emptyChat); + const [draft, setDraft] = useState(""); + const [useContext, setUseContext] = useState(true); + const [{ mode, model }, setPrefs] = useState(readPrefs); + const [installed, setInstalled] = useState(null); + const [starting, setStarting] = useState(false); + const [running, setRunning] = useState(false); + const [historyOpen, setHistoryOpen] = useState(false); + const [saved, setSaved] = useState(() => readSaved(root)); + const [extraContext, setExtraContext] = useState(); + const list = useRef(null); + const input = useRef(null); + const runningRef = useRef(false); + const generation = useRef(0); + const chatRef = useRef(chat); chatRef.current = chat; + + useEffect(() => { try { localStorage.setItem(prefsKey, JSON.stringify({ mode, model })); } catch { /* nicety */ } }, [mode, model]); + + // Is Claude Code installed? Re-checked when the Extensions view installs or removes it. + useEffect(() => { + const update = () => setInstalled(toolState("claude-code").installed); + void refreshTools().then(update, update); + return onToolsChange(update); + }, []); + + const stopProcess = useCallback(() => { generation.current++; runningRef.current = false; setRunning(false); void invoke("claude_chat_stop", { id: CHAT_ID }).catch(() => { }); }, []); + + // A new folder is a new conversation list. + useEffect(() => { stopProcess(); setChat(emptyChat()); setSaved(readSaved(root)); setHistoryOpen(false); }, [root, stopProcess]); + useEffect(() => () => { void invoke("claude_chat_stop", { id: CHAT_ID }).catch(() => { }); }, []); + + // Keep the newest message in view while Claude writes, unless the user scrolled up to read. + const pinned = useRef(true); + useEffect(() => { const el = list.current; if (el && pinned.current) el.scrollTop = el.scrollHeight; }, [chat.items]); + + // After a turn: reload changed files and save the conversation. + const lastResult = chat.items.filter(i => i.kind === "result").length; + useEffect(() => { + if (!lastResult || chat.busy) return; + if (chat.changed.length) onFilesChanged(chat.changed); + const title = (chat.items.find(i => i.kind === "user") as Extract | undefined)?.text || "Conversation"; + const next = upsertSaved(readSaved(root), toSaved(chat, title)); + writeSaved(root, next); setSaved(next); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [lastResult]); + + async function start(): Promise { + if (runningRef.current) return true; + const mine = ++generation.current; + const output = new Channel(); + output.onmessage = line => { + if (generation.current !== mine) return; + if (line.includes('"veyra_exit"')) { runningRef.current = false; setRunning(false); } + setChat(c => apply(c, line)); + }; + setStarting(true); + try { + await invoke("claude_chat_start", { id: CHAT_ID, options: { mode, model: model || null, resume: chatRef.current.sessionId || null }, output }); + runningRef.current = true; setRunning(true); + return true; + } catch (e) { + const text = String(e); + if (/isn't installed/i.test(text)) setInstalled(false); + setChat(c => ({ ...c, busy: false, items: [...c.items, { kind: "notice", id: "start-" + Date.now(), tone: "error", text }] })); + return false; + } finally { setStarting(false); } + } + + async function send(text: string, attached?: EditorContext) { + const body = text.trim(); + if (!body || chatRef.current.busy || !root) return; + const c = attached ?? (useContext ? context : undefined); + setChat(chat => ask(chat, body, c ? [contextLabel(c)] : undefined)); + setDraft(""); setExtraContext(undefined); pinned.current = true; + if (!(await start())) return; + try { await invoke("claude_chat_send", { id: CHAT_ID, message: userMessage(promptWithContext(body, c)) }); } + catch (e) { setChat(chat => ({ ...chat, busy: false, items: [...chat.items, { kind: "notice", id: "send-" + Date.now(), tone: "error", text: String(e) }] })); } + } + + // "Ask Claude" / "Fix with Claude" from the editor. + useEffect(() => { + if (!request) return; + if (request.send) void send(request.text, request.context); + else { setDraft(request.text); setExtraContext(request.context); setTimeout(() => input.current?.focus(), 0); } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [request?.nonce]); + + useEffect(() => { if (visible) setTimeout(() => input.current?.focus(), 0); }, [visible]); + + function answer(item: Extract, decision: "allowed" | "always" | "denied") { + setChat(c => decide(c, item.id, decision)); + if (decision === "always" && item.suggestions?.some(s => (s as { mode?: string }).mode === "acceptEdits")) setPrefs(p => ({ ...p, mode: "acceptEdits" })); + void invoke("claude_chat_send", { id: CHAT_ID, message: permissionAnswer(item, decision) }).catch(() => { }); + } + + function stop() { + if (runningRef.current) void invoke("claude_chat_send", { id: CHAT_ID, message: interruptMessage() }).catch(() => stopProcess()); + // If Claude Code doesn't answer the interrupt, end the process; the conversation continues on the next prompt. + const pending = chatRef.current.items.length; + setTimeout(() => { if (chatRef.current.busy && chatRef.current.items.length === pending) { stopProcess(); setChat(c => apply(c, JSON.stringify({ type: "veyra_exit", code: null, stderr: "" }))); } }, 4000); + } + + function changeMode(next: Mode) { + setPrefs(p => ({ ...p, mode: next })); + if (runningRef.current) void invoke("claude_chat_send", { id: CHAT_ID, message: modeMessage(next) }).catch(() => { }); + } + function changeModel(next: string) { + setPrefs(p => ({ ...p, model: next })); + if (runningRef.current && !chatRef.current.busy) stopProcess(); // the next prompt continues the same conversation on the new model + } + + function newChat() { if (chatRef.current.busy) return; stopProcess(); setChat(emptyChat()); setHistoryOpen(false); setTimeout(() => input.current?.focus(), 0); } + function resume(entry: Saved) { if (chatRef.current.busy) return; stopProcess(); setChat({ ...emptyChat(), sessionId: entry.sessionId, items: entry.items }); setHistoryOpen(false); pinned.current = true; } + function forget(entry: Saved) { const next = saved.filter(s => s.sessionId !== entry.sessionId); writeSaved(root, next); setSaved(next); } + + const askedFirst = new Set(chat.items.flatMap(i => (i.kind === "permission" ? [i.toolUseId] : []))); + const pendingPermission = chat.items.find(i => i.kind === "permission" && !i.decision) as Extract | undefined; + const chip = extraContext ?? (useContext ? context : undefined); + const status = !root ? "No folder" : installed === false ? "Not installed" : starting ? "Starting…" : pendingPermission ? "Waiting for you" : chat.busy ? "Working…" : running ? "Ready" : "Idle"; + + const renderItem = (item: Item, index: number) => { + switch (item.kind) { + case "user": + return
{item.text}
{item.context?.length ? {item.context.map(c => {c})} : null}
; + case "text": + return
; + case "tool": { + if (item.name === "TodoWrite") return
Plan
{todos(item.input).map((t, i) =>
{t.status === "completed" ? : t.status === "in_progress" ? : null}{t.text}
)}
; + const { verb, target } = describeTool(item.name, item.input, root, item.status !== "running"); + const Icon = toolIcon(item.name); + const file = typeof item.input.file_path === "string" ? relative(item.input.file_path, root) : null; + // When Claude asked first, the permission card shows the change: the step doesn't repeat it. + const isEdit = ["Edit", "MultiEdit", "Write"].includes(item.name) && !askedFirst.has(item.id); + return
+
+ {item.status === "running" ? : item.status === "error" ? : } + {verb}{target && (file ? : {target})} +
+ {isEdit && = chat.items.length - 4} />} + {item.status === "error" && item.output ?
{item.output.slice(0, 2000)}
+ : item.name === "Bash" && item.output ?
Output
{item.output.slice(-6000)}
: null} +
; + } + case "permission": { + const { verb, target } = describeTool(item.name, item.input, root, false); + const isEdit = ["Edit", "MultiEdit", "Write"].includes(item.name); + const question = isEdit ? `Claude wants to ${item.name === "Write" ? "write" : "edit"} ${target}` : item.name === "Bash" ? "Claude wants to run a command" : `Claude wants to use ${verb}${target ? " " + target : ""}`; + return
+
{question}
+ {item.name === "Bash" &&
{String(item.input.command ?? "")}
} + {isEdit && } + {item.reason && !item.decision && {item.reason}} + {item.decision ?
{item.decision === "denied" ? <>Denied : <>{item.decision === "always" ? "Allowed, and won't ask again this session" : "Allowed"}}
+ :
+ + {item.suggestions?.length ? : null} + +
} +
; + } + case "result": + return
+ {item.text &&
{item.text}
} + {item.ok ? : }{item.turns ? `${item.turns} step${item.turns === 1 ? "" : "s"}` : ""}{item.ms ? ` · ${(item.ms / 1000).toFixed(1)}s` : ""}{item.cost && chat.keySource && chat.keySource !== "none" ? ` · $${item.cost.toFixed(3)}` : ""} +
; + case "notice": + if (item.tone === "signin") return
Sign in to ClaudeClaude Code opens in a terminal: type /login, sign in in your browser, then come back here.
; + return
{item.tone === "error" ? : }{item.text}
; + } + }; + + return