Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix: add missing Claude Code files referenced by ChatView

PurpleDoubleDe3c96b4425ce
diff --git a/src-tauri/src/commands/claude_code.rs b/src-tauri/src/commands/claude_code.rs
new file mode 100644
index 00000000..9e9d7eb6
--- /dev/null
+++ b/src-tauri/src/commands/claude_code.rs
@@ -0,0 +1,416 @@
+use std::io::{BufRead, BufReader, Write as IoWrite};
+use std::process::{Command, Stdio};
+
+#[cfg(target_os = "windows")]
+use std::os::windows::process::CommandExt;
+
+use tauri::{AppHandle, Emitter, State};
+
+use crate::state::AppState;
+
+/// Windows: hide console windows for spawned processes
+#[cfg(target_os = "windows")]
+const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+// ── Detect Claude Code CLI ────────────────────────────────────────────────
+
+#[tauri::command]
+pub fn detect_claude_code() -> Result<serde_json::Value, String> {
+ let mut cmd = Command::new("claude");
+ cmd.args(["--version"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ match cmd.output() {
+ Ok(output) if output.status.success() => {
+ let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ // Try to find the full path
+ let path = find_claude_path().unwrap_or_default();
+ Ok(serde_json::json!({
+ "installed": true,
+ "version": version,
+ "path": path,
+ }))
+ }
+ _ => Ok(serde_json::json!({
+ "installed": false,
+ "version": null,
+ "path": null,
+ })),
+ }
+}
+
+fn find_claude_path() -> Option<String> {
+ let cmd_name = if cfg!(target_os = "windows") { "where" } else { "which" };
+ let mut cmd = Command::new(cmd_name);
+ cmd.arg("claude")
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ cmd.output().ok().and_then(|o| {
+ if o.status.success() {
+ let output = String::from_utf8_lossy(&o.stdout);
+ // On Windows, `where` returns multiple lines. Prefer .cmd or .exe over bare scripts.
+ if cfg!(target_os = "windows") {
+ let lines: Vec<&str> = output.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();
+ // First try .exe, then .cmd, then first result
+ lines.iter().find(|l| l.ends_with(".exe")).map(|s| s.to_string())
+ .or_else(|| lines.iter().find(|l| l.ends_with(".cmd")).map(|s| s.to_string()))
+ .or_else(|| lines.first().map(|s| s.to_string()))
+ } else {
+ Some(output.lines().next()?.trim().to_string())
+ }
+ } else {
+ None
+ }
+ })
+}
+
+// ── Install Claude Code ───────────────────────────────────────────────────
+
+#[tauri::command]
+pub fn install_claude_code(
+ method: String,
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ let mut install = state.claude_code_install.lock().unwrap();
+ if install.status == "installing" || install.status == "downloading" {
+ return Ok(serde_json::json!({"status": "already_installing"}));
+ }
+
+ install.status = "installing".to_string();
+ install.logs.clear();
+ install.logs.push("Starting Claude Code installation...".to_string());
+ drop(install);
+
+ let install_state = state.claude_code_install.clone();
+
+ std::thread::spawn(move || {
+ let update = |status: &str, msg: &str| {
+ if let Ok(mut s) = install_state.lock() {
+ s.status = status.to_string();
+ s.logs.push(msg.to_string());
+ }
+ };
+
+ match method.as_str() {
+ "npm" => {
+ // Check Node.js
+ update("installing", "Checking Node.js...");
+ let mut node_cmd = Command::new("node");
+ node_cmd.args(["--version"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ node_cmd.creation_flags(CREATE_NO_WINDOW);
+
+ match node_cmd.output() {
+ Ok(output) if output.status.success() => {
+ let ver = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ update("installing", &format!("Node.js {} found.", ver));
+ }
+ _ => {
+ update("error", "Node.js not found. Install Node.js 18+ first, or use the native installer method.");
+ return;
+ }
+ }
+
+ // npm install -g @anthropic-ai/claude-code
+ update("installing", "Installing @anthropic-ai/claude-code via npm...");
+ let mut npm = Command::new("npm");
+ npm.args(["install", "-g", "@anthropic-ai/claude-code"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ npm.creation_flags(CREATE_NO_WINDOW);
+
+ match npm.output() {
+ Ok(output) if output.status.success() => {
+ update("complete", "Claude Code installed successfully!");
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ update("error", &format!("npm install failed: {}", stderr.chars().take(300).collect::<String>()));
+ }
+ Err(e) => {
+ update("error", &format!("npm not found: {}", e));
+ }
+ }
+ }
+ "native" => {
+ // Native installer
+ if cfg!(target_os = "windows") {
+ update("installing", "Running native installer for Windows...");
+ // PowerShell one-liner from Anthropic
+ let mut ps = Command::new("powershell");
+ ps.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",
+ "irm https://claude.ai/install.ps1 | iex"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ #[cfg(target_os = "windows")]
+ ps.creation_flags(CREATE_NO_WINDOW);
+
+ match ps.output() {
+ Ok(output) if output.status.success() => {
+ update("complete", "Claude Code installed successfully!");
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ // Native installer may print to stdout
+ let msg = if stderr.is_empty() { stdout } else { stderr };
+ update("error", &format!("Installation failed: {}", msg.chars().take(300).collect::<String>()));
+ }
+ Err(e) => {
+ update("error", &format!("PowerShell not found: {}", e));
+ }
+ }
+ } else {
+ // macOS/Linux: curl installer
+ update("installing", "Running native installer...");
+ let mut sh = Command::new("sh");
+ sh.args(["-c", "curl -fsSL https://claude.ai/install.sh | bash"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ match sh.output() {
+ Ok(output) if output.status.success() => {
+ update("complete", "Claude Code installed successfully!");
+ }
+ Ok(output) => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ update("error", &format!("Installation failed: {}", stderr.chars().take(300).collect::<String>()));
+ }
+ Err(e) => {
+ update("error", &format!("Shell not available: {}", e));
+ }
+ }
+ }
+ }
+ _ => {
+ update("error", &format!("Unknown install method: {}", method));
+ }
+ }
+ });
+
+ Ok(serde_json::json!({"status": "installing"}))
+}
+
+#[tauri::command]
+pub fn install_claude_code_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
+ let install = state.claude_code_install.lock().unwrap();
+ Ok(serde_json::json!({
+ "status": install.status,
+ "logs": install.logs,
+ }))
+}
+
+// ── Start Claude Code Session ─────────────────────────────────────────────
+
+#[allow(non_snake_case)]
+#[tauri::command]
+pub fn start_claude_code(
+ app: AppHandle,
+ state: State<'_, AppState>,
+ workingDir: String,
+ model: String,
+ prompt: String,
+ ollamaBaseUrl: String,
+ permissionMode: String,
+) -> Result<serde_json::Value, String> {
+ // Check if already running
+ {
+ let proc = state.claude_code_process.lock().unwrap();
+ if proc.is_some() {
+ return Ok(serde_json::json!({"status": "already_running"}));
+ }
+ }
+
+ // Resolve CLI path
+ let claude_bin = find_claude_path().unwrap_or_else(|| "claude".to_string());
+
+ // Build command args
+ let mut args = vec![
+ "--print".to_string(),
+ "--output-format".to_string(),
+ "stream-json".to_string(),
+ "--model".to_string(),
+ model.clone(),
+ "--verbose".to_string(),
+ ];
+
+ // Permission mode
+ match permissionMode.as_str() {
+ "auto-approve" => {
+ args.push("--dangerously-skip-permissions".to_string());
+ }
+ "read-only" => {
+ args.push("--allowedTools".to_string());
+ args.push("Read,Grep,Glob,WebSearch,WebFetch".to_string());
+ }
+ _ => {
+ // Default "ask" mode — Claude Code will prompt for permissions
+ // We handle permission_request events in the frontend
+ }
+ }
+
+ // Add the actual prompt
+ args.push(prompt);
+
+ println!("[ClaudeCode] Starting: {} {:?}", claude_bin, args);
+ println!("[ClaudeCode] Working dir: {}", workingDir);
+ println!("[ClaudeCode] Ollama base URL: {}", ollamaBaseUrl);
+ println!("[ClaudeCode] Model: {}", model);
+
+ // Spawn the process
+ let effective_dir = if workingDir.is_empty() {
+ std::env::var("USERPROFILE")
+ .or_else(|_| std::env::var("HOME"))
+ .unwrap_or_else(|_| ".".to_string())
+ } else {
+ workingDir.clone()
+ };
+
+ let mut cmd = Command::new(&claude_bin);
+ cmd.args(&args)
+ .current_dir(&effective_dir)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .env("ANTHROPIC_BASE_URL", &ollamaBaseUrl)
+ .env("ANTHROPIC_API_KEY", "sk-local-placeholder")
+ .env("DISABLE_PROMPT_CACHING", "1")
+ .env_remove("CLAUDECODE") // Prevent "nested session" detection
+ .env_remove("CLAUDE_CODE_ENTRYPOINT");
+
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let mut child = cmd.spawn().map_err(|e| format!("Failed to start Claude Code (bin: {}, dir: {}): {}", claude_bin, effective_dir, e))?;
+
+ let pid = child.id();
+ println!("[ClaudeCode] Started with PID {}", pid);
+
+ // Take stdout and stderr
+ let stdout = child.stdout.take().ok_or("Failed to capture stdout")?;
+ let stderr = child.stderr.take().ok_or("Failed to capture stderr")?;
+
+ // Store process handle
+ {
+ let mut proc = state.claude_code_process.lock().unwrap();
+ *proc = Some(child);
+ }
+
+ // Spawn thread to read stdout (JSON events)
+ let app_stdout = app.clone();
+ std::thread::spawn(move || {
+ let reader = BufReader::new(stdout);
+ for line in reader.lines() {
+ match line {
+ Ok(text) => {
+ let trimmed = text.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ // Try to parse as JSON, otherwise wrap as text event
+ let event = if trimmed.starts_with('{') {
+ match serde_json::from_str::<serde_json::Value>(trimmed) {
+ Ok(json) => json,
+ Err(_) => serde_json::json!({"type": "text", "content": trimmed}),
+ }
+ } else {
+ serde_json::json!({"type": "text", "content": trimmed})
+ };
+ let _ = app_stdout.emit("claude-code-event", &event);
+ }
+ Err(e) => {
+ let _ = app_stdout.emit("claude-code-event",
+ serde_json::json!({"type": "error", "content": format!("Read error: {}", e)}));
+ break;
+ }
+ }
+ }
+ // Process ended
+ let _ = app_stdout.emit("claude-code-event",
+ serde_json::json!({"type": "done", "content": "Claude Code session ended."}));
+ println!("[ClaudeCode] stdout reader finished");
+ });
+
+ // Spawn thread to read stderr
+ let app_stderr = app.clone();
+ std::thread::spawn(move || {
+ let reader = BufReader::new(stderr);
+ for line in reader.lines() {
+ if let Ok(text) = line {
+ let trimmed = text.trim();
+ if !trimmed.is_empty() {
+ println!("[ClaudeCode stderr] {}", trimmed);
+ let _ = app_stderr.emit("claude-code-event",
+ serde_json::json!({"type": "error", "content": trimmed}));
+ }
+ }
+ }
+ });
+
+ Ok(serde_json::json!({
+ "status": "started",
+ "pid": pid,
+ }))
+}
+
+// ── Stop Claude Code ──────────────────────────────────────────────────────
+
+#[tauri::command]
+pub fn stop_claude_code(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
+ let mut proc = state.claude_code_process.lock().unwrap();
+ if let Some(ref mut child) = *proc {
+ let pid = child.id();
+ println!("[ClaudeCode] Stopping PID {}", pid);
+
+ #[cfg(target_os = "windows")]
+ {
+ let _ = Command::new("taskkill")
+ .args(["/pid", &pid.to_string(), "/T", "/F"])
+ .creation_flags(CREATE_NO_WINDOW)
+ .output();
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let _ = child.kill();
+ }
+
+ *proc = None;
+ Ok(serde_json::json!({"status": "stopped"}))
+ } else {
+ Ok(serde_json::json!({"status": "not_running"}))
+ }
+}
+
+// ── Send input to Claude Code stdin (permission approvals) ────────────────
+
+#[tauri::command]
+pub fn send_claude_code_input(
+ input: String,
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ let mut proc = state.claude_code_process.lock().unwrap();
+ if let Some(ref mut child) = *proc {
+ if let Some(ref mut stdin) = child.stdin {
+ stdin.write_all(input.as_bytes())
+ .map_err(|e| format!("Failed to write to stdin: {}", e))?;
+ stdin.write_all(b"\n")
+ .map_err(|e| format!("Failed to write newline: {}", e))?;
+ stdin.flush()
+ .map_err(|e| format!("Failed to flush stdin: {}", e))?;
+ Ok(serde_json::json!({"status": "sent"}))
+ } else {
+ Err("stdin not available".to_string())
+ }
+ } else {
+ Err("Claude Code is not running".to_string())
+ }
+}
diff --git a/src/components/chat/ClaudeCodeView.tsx b/src/components/chat/ClaudeCodeView.tsx
new file mode 100644
index 00000000..fdfd0a8b
--- /dev/null
+++ b/src/components/chat/ClaudeCodeView.tsx
@@ -0,0 +1,321 @@
+import { useClaudeCode } from '../../hooks/useClaudeCode'
+import { useClaudeCodeStore } from '../../stores/claudeCodeStore'
+import { useChatStore } from '../../stores/chatStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { ChatInput } from './ChatInput'
+import { ToolCallBlock } from './ToolCallBlock'
+import { ThinkingBlock } from './ThinkingBlock'
+import { MarkdownRenderer } from './MarkdownRenderer'
+import { TokenCounter } from './TokenCounter'
+import { RealtimeCounter } from './RealtimeCounter'
+import { FileTree } from './FileTree'
+import { User, Terminal, Shield, ShieldCheck, AlertTriangle, AlertCircle } from 'lucide-react'
+import { useEffect, useRef, useState } from 'react'
+import { backendCall } from '../../api/backend'
+import { CLAUDE_CODE_RECOMMENDED_MODELS } from '../../stores/claudeCodeStore'
+import { useModelStore } from '../../stores/modelStore'
+import { isClaudeCodeCompatible } from '../../lib/model-compatibility'
+
+export function ClaudeCodeView() {
+ const { sendPrompt, stopSession, approvePermission, denyPermission, isRunning } = useClaudeCode()
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const conversations = useChatStore((s) => s.conversations)
+ const session = useClaudeCodeStore((s) => activeConversationId ? s.sessions[activeConversationId] : undefined)
+ const installed = useClaudeCodeStore((s) => s.installed)
+ const version = useClaudeCodeStore((s) => s.version)
+ const workingDirectory = useClaudeCodeStore((s) => s.workingDirectory)
+ const claudeCodeModel = useSettingsStore((s) => s.settings.claudeCodeModel)
+ const scrollRef = useRef<HTMLDivElement>(null)
+
+ const activeModel = useModelStore((s) => s.activeModel)
+ const modelCompatible = isClaudeCodeCompatible(claudeCodeModel || activeModel)
+
+ const conversation = conversations.find(c => c.id === activeConversationId)
+ const messages = conversation?.messages || []
+
+ // Auto-scroll on new messages
+ useEffect(() => {
+ if (scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight
+ }
+ }, [messages, session?.events])
+
+ // Detect Claude Code on mount
+ useEffect(() => {
+ detectClaudeCode()
+ }, [])
+
+ async function detectClaudeCode() {
+ try {
+ const result = await backendCall<{ installed: boolean; version: string; path: string }>('detect_claude_code')
+ useClaudeCodeStore.getState().setInstalled(result.installed, result.version, result.path)
+ } catch {
+ // Not in Tauri mode or detection failed
+ }
+ }
+
+ const isWaitingPermission = session?.status === 'waiting_permission'
+
+ return (
+ <div className="flex-1 flex overflow-hidden">
+ {/* Main panel */}
+ <div className="flex-1 flex flex-col min-w-0 relative">
+ {/* Header */}
+ <div className="flex items-center gap-1.5 px-3 py-1 border-b border-gray-200 dark:border-white/[0.04]">
+ <Terminal size={11} className="text-gray-400" />
+ <span className="text-[0.7rem] text-gray-700 dark:text-gray-300 font-medium">Claude Code</span>
+ {claudeCodeModel && (
+ <span className="text-[0.55rem] text-gray-500">{claudeCodeModel}</span>
+ )}
+ <div className="flex-1" />
+ {installed && version && (
+ <span className="text-[0.55rem] text-gray-500">{version}</span>
+ )}
+ <TokenCounter />
+ </div>
+
+ {/* Model compatibility warning */}
+ {installed && !modelCompatible && (
+ <div className="mx-3 mt-1.5 px-2.5 py-1.5 rounded-md bg-gray-100 dark:bg-white/[0.04] border border-gray-200 dark:border-white/[0.06] flex items-center gap-2">
+ <AlertCircle size={12} className="text-gray-400 shrink-0" />
+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">
+ {claudeCodeModel || activeModel || 'No model selected'} may not support tool calling. Recommended: GLM 5.1, Qwen 3.5 Coder, Hermes 3.
+ </span>
+ </div>
+ )}
+
+ {/* Ollama requirement — subtle, only on empty state */}
+ {installed && messages.length === 0 && (
+ <div className="mx-3 mt-1 px-2.5 py-1 flex items-center gap-1.5">
+ <span className="text-[0.6rem] text-gray-500">
+ Requires Ollama 0.14+ for local Anthropic API compatibility.
+ </span>
+ </div>
+ )}
+
+ {/* Messages */}
+ <div ref={scrollRef} className="flex-1 overflow-y-auto scrollbar-thin">
+ {!installed ? (
+ // Not installed state
+ <ClaudeCodeInstallPrompt onDetect={detectClaudeCode} />
+ ) : messages.length === 0 ? (
+ // Empty state — clean, professional
+ <div className="flex flex-col items-center justify-center h-full text-center px-6">
+ <Terminal size={28} className="text-gray-300 dark:text-gray-600 mb-3" />
+ <p className="text-[0.85rem] text-gray-700 dark:text-gray-300 font-medium">Claude Code</p>
+ <p className="text-[0.7rem] text-gray-500 dark:text-gray-500 mt-1 max-w-[340px] leading-relaxed">
+ Run the official Claude Code agent locally. File editing, shell commands, code search — all on your machine.
+ </p>
+ {!workingDirectory && (
+ <p className="text-[0.65rem] text-gray-400 mt-3">
+ Set a working directory in the file tree panel to get started.
+ </p>
+ )}
+ {!claudeCodeModel && (
+ <div className="mt-4">
+ <p className="text-[0.6rem] text-gray-500 mb-2">Recommended models</p>
+ <div className="flex flex-wrap gap-1.5 justify-center max-w-[320px]">
+ {CLAUDE_CODE_RECOMMENDED_MODELS.slice(0, 4).map(m => (
+ <button
+ key={m.name}
+ onClick={() => useSettingsStore.getState().updateSettings({ claudeCodeModel: m.name })}
+ className="text-[0.6rem] px-2.5 py-1 rounded-md bg-gray-100 dark:bg-white/[0.05] text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.08] border border-gray-200 dark:border-white/[0.06] transition-colors"
+ title={m.reason}
+ >
+ {m.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ // Message list
+ <div className="py-1">
+ {messages.map((msg) => (
+ <div
+ key={msg.id}
+ className={`flex gap-2 px-3 py-1 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}
+ >
+ <div className={`w-5 h-5 rounded flex items-center justify-center shrink-0 ${
+ msg.role === 'user'
+ ? 'bg-gray-100 dark:bg-white/8'
+ : 'bg-purple-500/10'
+ }`}>
+ {msg.role === 'user'
+ ? <User size={9} className="text-gray-400" />
+ : <Terminal size={9} className="text-purple-400" />
+ }
+ </div>
+ <div className="max-w-[85%] space-y-0.5">
+ {/* Thinking */}
+ {msg.role === 'assistant' && msg.thinking && (
+ <ThinkingBlock thinking={msg.thinking} />
+ )}
+ {/* Tool call blocks */}
+ {msg.role === 'assistant' && msg.agentBlocks && msg.agentBlocks.length > 0 && (
+ <div className="space-y-0">
+ {msg.agentBlocks
+ .filter(b => b.phase === 'tool_call' && b.toolCall)
+ .map(block => (
+ <ToolCallBlock key={block.id} toolCall={block.toolCall!} />
+ ))}
+ </div>
+ )}
+ {/* Text content */}
+ {msg.content && (
+ <div className={`rounded-lg px-2.5 py-1.5 ${
+ msg.role === 'user'
+ ? 'bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
+ : 'bg-white dark:bg-white/[0.02] border border-purple-500/10 dark:border-purple-500/10'
+ }`}>
+ <div className="text-[0.75rem] leading-relaxed">
+ {msg.role === 'user' ? (
+ <p className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{msg.content}</p>
+ ) : (
+ <MarkdownRenderer content={msg.content} />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+
+ {/* Permission approval bar */}
+ {isWaitingPermission && (
+ <div className="mx-3 my-2 p-2 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center gap-2">
+ <Shield size={12} className="text-amber-400 shrink-0" />
+ <span className="text-[0.65rem] text-amber-300 flex-1">
+ Claude Code is requesting permission to proceed.
+ </span>
+ <button
+ onClick={approvePermission}
+ className="text-[0.55rem] px-2 py-0.5 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 transition-colors flex items-center gap-0.5"
+ >
+ <ShieldCheck size={9} />
+ Approve
+ </button>
+ <button
+ onClick={denyPermission}
+ className="text-[0.55rem] px-2 py-0.5 rounded bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors"
+ >
+ Deny
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Realtime counter */}
+ <RealtimeCounter isRunning={isRunning} />
+
+ {/* Input */}
+ <ChatInput
+ onSend={(content) => sendPrompt(content)}
+ onStop={stopSession}
+ isGenerating={isRunning}
+ disabled={!installed}
+ />
+ </div>
+
+ {/* Right sidebar: File Tree */}
+ <div className="w-48 shrink-0">
+ <FileTree />
+ </div>
+ </div>
+ )
+}
+
+// ── Install Prompt Component ──────────────────────────────────────────────
+
+function ClaudeCodeInstallPrompt({ onDetect }: { onDetect: () => void }) {
+ const [installing, setInstalling] = useState(false)
+ const [installLog, setInstallLog] = useState<string[]>([])
+ const [error, setError] = useState('')
+
+ async function handleInstall(method: 'npm' | 'native') {
+ setInstalling(true)
+ setError('')
+ setInstallLog(['Starting installation...'])
+
+ try {
+ await backendCall('install_claude_code', { method })
+
+ // Poll status
+ const poll = setInterval(async () => {
+ try {
+ const status = await backendCall<{ status: string; logs: string[] }>('install_claude_code_status')
+ setInstallLog(status.logs)
+
+ if (status.status === 'complete') {
+ clearInterval(poll)
+ setInstalling(false)
+ onDetect() // Re-detect
+ } else if (status.status === 'error') {
+ clearInterval(poll)
+ setInstalling(false)
+ setError(status.logs[status.logs.length - 1] || 'Installation failed')
+ }
+ } catch {
+ clearInterval(poll)
+ setInstalling(false)
+ }
+ }, 1000)
+ } catch (err) {
+ setInstalling(false)
+ setError((err as Error).message)
+ }
+ }
+
+ return (
+ <div className="flex flex-col items-center justify-center h-full text-center px-6">
+ <Terminal size={28} className="text-gray-300 dark:text-gray-600 mb-3" />
+ <p className="text-[0.85rem] text-gray-700 dark:text-gray-300 font-medium mb-1">Claude Code not installed</p>
+ <p className="text-[0.7rem] text-gray-500 max-w-[340px] mb-4 leading-relaxed">
+ Install the Claude Code CLI to use this feature. Runs locally with Ollama 0.14+.
+ </p>
+
+ {!installing ? (
+ <div className="flex gap-2">
+ <button
+ onClick={() => handleInstall('native')}
+ className="text-[0.65rem] px-4 py-1.5 rounded-md bg-gray-800 dark:bg-white/10 text-white dark:text-gray-200 hover:bg-gray-700 dark:hover:bg-white/15 transition-colors border border-gray-700 dark:border-white/10"
+ >
+ Install (Native)
+ </button>
+ <button
+ onClick={() => handleInstall('npm')}
+ className="text-[0.65rem] px-4 py-1.5 rounded-md bg-gray-100 dark:bg-white/[0.04] text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/[0.08] transition-colors border border-gray-200 dark:border-white/[0.06]"
+ >
+ Install via npm
+ </button>
+ </div>
+ ) : (
+ <div className="w-full max-w-[320px]">
+ <div className="text-[0.5rem] text-gray-500 space-y-0.5 text-left bg-black/20 rounded p-2 max-h-[120px] overflow-y-auto">
+ {installLog.map((log, i) => (
+ <p key={i}>{log}</p>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <div className="mt-2 flex items-center gap-1 text-[0.55rem] text-red-400">
+ <AlertTriangle size={10} />
+ <span>{error}</span>
+ </div>
+ )}
+
+ <button
+ onClick={onDetect}
+ className="mt-3 text-[0.5rem] text-gray-600 hover:text-gray-400 transition-colors"
+ >
+ Already installed? Click to re-detect
+ </button>
+ </div>
+ )
+}
+
diff --git a/src/hooks/useClaudeCode.ts b/src/hooks/useClaudeCode.ts
new file mode 100644
index 00000000..67e59f83
--- /dev/null
+++ b/src/hooks/useClaudeCode.ts
@@ -0,0 +1,277 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { v4 as uuid } from 'uuid'
+import { backendCall, isTauri } from '../api/backend'
+import { useClaudeCodeStore } from '../stores/claudeCodeStore'
+import { useChatStore } from '../stores/chatStore'
+import { useSettingsStore } from '../stores/settingsStore'
+import { useProviderStore } from '../stores/providerStore'
+import type { ClaudeCodeEvent } from '../stores/claudeCodeStore'
+import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
+
+/**
+ * Hook for running Claude Code sessions.
+ *
+ * Unlike useCodex (which runs an agentic loop in JS), this hook
+ * spawns the Claude Code CLI as a Tauri subprocess and streams
+ * JSON events back to the frontend. The CLI handles all tool
+ * execution internally.
+ *
+ * Requires: Ollama 0.14+ (native Anthropic API compatibility).
+ */
+export function useClaudeCode() {
+ const [isRunning, setIsRunning] = useState(false)
+ const unlistenRef = useRef<(() => void) | null>(null)
+
+ // Cleanup event listener on unmount
+ useEffect(() => {
+ return () => {
+ if (unlistenRef.current) {
+ unlistenRef.current()
+ unlistenRef.current = null
+ }
+ }
+ }, [])
+
+ const sendPrompt = useCallback(async (prompt: string) => {
+ const claudeStore = useClaudeCodeStore.getState()
+ const { settings } = useSettingsStore.getState()
+ const chatStore = useChatStore.getState()
+ const providerState = useProviderStore.getState()
+
+ // Get Ollama base URL from provider store
+ const ollamaConfig = providerState.providers.ollama
+ const ollamaBaseUrl = ollamaConfig?.baseUrl || 'http://localhost:11434'
+
+ // Get model: settings override → active Ollama model → fallback
+ const { activeModel } = await import('../stores/modelStore').then(m => m.useModelStore.getState())
+ const model = settings.claudeCodeModel || activeModel || 'glm5.1'
+
+ // Get or create conversation
+ let convId = chatStore.activeConversationId
+ if (!convId) {
+ convId = chatStore.createConversation(model, '', 'claude-code')
+ }
+
+ // Init session if needed
+ // Use configured working directory, or user's home directory as fallback
+ const workDir = claudeStore.workingDirectory || (typeof window !== 'undefined' && (window as any).__TAURI_INTERNALS__ ? '' : '.')
+ // If no workDir, let Rust use the app's current directory
+ if (!claudeStore.getSession(convId)) {
+ claudeStore.initSession(convId, workDir)
+ }
+
+ // Add user message
+ chatStore.addMessage(convId, {
+ id: uuid(), role: 'user', content: prompt, timestamp: Date.now(),
+ })
+
+ // Add empty assistant message (will be streamed into)
+ const assistantMsgId = uuid()
+ chatStore.addMessage(convId, {
+ id: assistantMsgId, role: 'assistant', content: '', timestamp: Date.now(), agentBlocks: [],
+ })
+
+ // Add instruction event
+ claudeStore.addEvent(convId, {
+ id: uuid(), type: 'text', content: prompt, timestamp: Date.now(),
+ })
+
+ setIsRunning(true)
+ claudeStore.setSessionStatus(convId, 'running')
+
+ let fullContent = ''
+ const blocks: AgentBlock[] = []
+
+ // In Tauri mode: spawn CLI and listen for events
+ if (isTauri()) {
+ try {
+ // Set up event listener BEFORE starting the process
+ const { listen } = await import('@tauri-apps/api/event')
+ const unlisten = await listen<Record<string, unknown>>('claude-code-event', (event) => {
+ const data = event.payload as any
+ const convIdCurrent = convId!
+
+ // Create store event
+ const storeEvent: ClaudeCodeEvent = {
+ id: uuid(),
+ type: data.type || 'text',
+ content: data.content || '',
+ timestamp: Date.now(),
+ toolName: data.tool_name,
+ toolArgs: data.tool_args,
+ toolResult: data.tool_result,
+ filePath: data.file_path,
+ }
+ claudeStore.addEvent(convIdCurrent, storeEvent)
+
+ // Map to chat UI
+ switch (data.type) {
+ case 'text':
+ case 'assistant': {
+ const text = data.content || data.text || ''
+ if (text) {
+ fullContent += (fullContent ? '\n' : '') + text
+ chatStore.updateMessageContent(convIdCurrent, assistantMsgId, fullContent)
+ }
+ break
+ }
+ case 'tool_use': {
+ const toolCall: AgentToolCall = {
+ id: uuid(),
+ toolName: data.tool_name || data.name || 'unknown',
+ args: data.tool_args || data.input || {},
+ status: 'running',
+ timestamp: Date.now(),
+ }
+ blocks.push({
+ id: uuid(),
+ phase: 'tool_call',
+ content: `Running: ${toolCall.toolName}`,
+ toolCall,
+ timestamp: Date.now(),
+ })
+ chatStore.updateMessageAgentBlocks(convIdCurrent, assistantMsgId, [...blocks])
+ break
+ }
+ case 'tool_result': {
+ // Update the last tool call block with result
+ const lastBlock = blocks[blocks.length - 1]
+ if (lastBlock?.toolCall) {
+ lastBlock.toolCall.status = 'completed'
+ lastBlock.toolCall.result = data.content || data.output || ''
+ lastBlock.toolCall.duration = Date.now() - lastBlock.timestamp
+ lastBlock.content = `Completed: ${lastBlock.toolCall.toolName}`
+ chatStore.updateMessageAgentBlocks(convIdCurrent, assistantMsgId, [...blocks])
+ }
+ break
+ }
+ case 'permission_request': {
+ claudeStore.setSessionStatus(convIdCurrent, 'waiting_permission')
+ blocks.push({
+ id: uuid(),
+ phase: 'tool_call',
+ content: `Permission required: ${data.tool_name || 'action'}`,
+ toolCall: {
+ id: uuid(),
+ toolName: data.tool_name || 'permission',
+ args: data.tool_args || {},
+ status: 'running',
+ timestamp: Date.now(),
+ },
+ timestamp: Date.now(),
+ })
+ chatStore.updateMessageAgentBlocks(convIdCurrent, assistantMsgId, [...blocks])
+ break
+ }
+ case 'error': {
+ const errContent = data.content || 'Unknown error'
+ fullContent += (fullContent ? '\n\n' : '') + `Error: ${errContent}`
+ chatStore.updateMessageContent(convIdCurrent, assistantMsgId, fullContent)
+ claudeStore.addEvent(convIdCurrent, {
+ id: uuid(), type: 'error', content: errContent, timestamp: Date.now(),
+ })
+ break
+ }
+ case 'done': {
+ setIsRunning(false)
+ claudeStore.setSessionStatus(convIdCurrent, 'idle')
+ claudeStore.setSessionPid(convIdCurrent, null)
+ // Cleanup listener
+ if (unlistenRef.current) {
+ unlistenRef.current()
+ unlistenRef.current = null
+ }
+ break
+ }
+ }
+ })
+
+ unlistenRef.current = unlisten
+
+ // Determine permission mode
+ const permissionMode = settings.claudeCodeAutoApprove ? 'auto-approve' : 'ask'
+
+ // Start Claude Code subprocess
+ const result = await backendCall<{ status: string; pid?: number }>('start_claude_code', {
+ workingDir: workDir,
+ model,
+ prompt,
+ ollamaBaseUrl,
+ permissionMode,
+ })
+
+ if (result.pid) {
+ claudeStore.setSessionPid(convId, result.pid)
+ }
+
+ if (result.status === 'already_running') {
+ fullContent = 'A Claude Code session is already running. Stop it first.'
+ chatStore.updateMessageContent(convId, assistantMsgId, fullContent)
+ setIsRunning(false)
+ claudeStore.setSessionStatus(convId, 'idle')
+ }
+ } catch (err) {
+ const msg = typeof err === 'string' ? err : (err as Error).message || 'Failed to start Claude Code'
+ fullContent = `Error: ${msg}`
+ chatStore.updateMessageContent(convId, assistantMsgId, fullContent)
+ setIsRunning(false)
+ claudeStore.setSessionStatus(convId, 'error')
+ }
+ } else {
+ // Dev mode (no Tauri) — show info message
+ fullContent = 'Claude Code requires the Tauri desktop app (Ollama 0.14+). It is not available in browser dev mode.'
+ chatStore.updateMessageContent(convId, assistantMsgId, fullContent)
+ setIsRunning(false)
+ claudeStore.setSessionStatus(convId, 'idle')
+ }
+ }, [])
+
+ const stopSession = useCallback(async () => {
+ try {
+ await backendCall('stop_claude_code')
+ } catch (err) {
+ console.warn('[ClaudeCode] Stop failed:', err)
+ }
+ setIsRunning(false)
+
+ // Cleanup listener
+ if (unlistenRef.current) {
+ unlistenRef.current()
+ unlistenRef.current = null
+ }
+
+ // Update session status
+ const convId = useChatStore.getState().activeConversationId
+ if (convId) {
+ useClaudeCodeStore.getState().setSessionStatus(convId, 'idle')
+ useClaudeCodeStore.getState().setSessionPid(convId, null)
+ }
+ }, [])
+
+ const approvePermission = useCallback(async () => {
+ try {
+ await backendCall('send_claude_code_input', { input: 'yes' })
+ const convId = useChatStore.getState().activeConversationId
+ if (convId) {
+ useClaudeCodeStore.getState().setSessionStatus(convId, 'running')
+ }
+ } catch (err) {
+ console.warn('[ClaudeCode] Approve failed:', err)
+ }
+ }, [])
+
+ const denyPermission = useCallback(async () => {
+ try {
+ await backendCall('send_claude_code_input', { input: 'no' })
+ const convId = useChatStore.getState().activeConversationId
+ if (convId) {
+ useClaudeCodeStore.getState().setSessionStatus(convId, 'running')
+ }
+ } catch (err) {
+ console.warn('[ClaudeCode] Deny failed:', err)
+ }
+ }, [])
+
+ return { sendPrompt, stopSession, approvePermission, denyPermission, isRunning }
+}
+
diff --git a/src/stores/claudeCodeStore.ts b/src/stores/claudeCodeStore.ts
new file mode 100644
index 00000000..7dacdfc2
--- /dev/null
+++ b/src/stores/claudeCodeStore.ts
@@ -0,0 +1,163 @@
+/**
+ * Claude Code Store — manages Claude Code sessions and state.
+ *
+ * Tracks CLI installation status, active sessions, working directory,
+ * and streamed events from the Claude Code subprocess.
+ * Requires Ollama 0.14+ (native Anthropic API compatibility).
+ */
+
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+
+// ── Types ──────────────────────────────────────────────────────
+
+export type ClaudeCodeEventType =
+ | 'text' // assistant text content
+ | 'tool_use' // tool invocation (file read, write, shell)
+ | 'tool_result' // tool execution result
+ | 'permission_request'// needs user approval
+ | 'error' // error occurred
+ | 'done' // task complete
+
+export interface ClaudeCodeEvent {
+ id: string
+ type: ClaudeCodeEventType
+ content: string
+ timestamp: number
+ toolName?: string
+ toolArgs?: Record<string, unknown>
+ toolResult?: string
+ filePath?: string
+ diff?: string
+}
+
+export interface ClaudeCodeSession {
+ id: string
+ conversationId: string
+ events: ClaudeCodeEvent[]
+ status: 'idle' | 'running' | 'waiting_permission' | 'error'
+ workingDirectory: string
+ pid: number | null
+}
+
+// ── Recommended models for Claude Code ─────────────────────────
+
+export const CLAUDE_CODE_RECOMMENDED_MODELS = [
+ { name: 'glm5.1', label: 'GLM 5.1', reason: 'Latest GLM, strong tool calling, 128K context' },
+ { name: 'qwen3.5-coder', label: 'Qwen 3.5 Coder', reason: 'Best open-source coding model, native tool calling' },
+ { name: 'qwen3.5-coder-abliterated', label: 'Qwen 3.5 Coder (Uncensored)', reason: 'Abliterated variant, no refusals' },
+ { name: 'glm4.7', label: 'GLM 4.7 Flash', reason: '128K context, MoE, runs on 16GB RAM' },
+ { name: 'qwen3-coder', label: 'Qwen 3 Coder', reason: 'Strong coding, 128K context' },
+ { name: 'hermes3', label: 'Hermes 3', reason: 'Uncensored, good tool calling' },
+] as const
+
+// ── Store ──────────────────────────────────────────────────────
+
+interface ClaudeCodeState {
+ installed: boolean
+ version: string | null
+ cliPath: string | null
+ sessions: Record<string, ClaudeCodeSession>
+ workingDirectory: string
+
+ setInstalled: (installed: boolean, version?: string, path?: string) => void
+ setWorkingDirectory: (dir: string) => void
+
+ getSession: (conversationId: string) => ClaudeCodeSession | undefined
+ initSession: (conversationId: string, workingDir: string) => string
+ addEvent: (conversationId: string, event: ClaudeCodeEvent) => void
+ setSessionStatus: (conversationId: string, status: ClaudeCodeSession['status']) => void
+ setSessionPid: (conversationId: string, pid: number | null) => void
+ clearSession: (conversationId: string) => void
+}
+
+export const useClaudeCodeStore = create<ClaudeCodeState>()(
+ persist(
+ (set, get) => ({
+ installed: false,
+ version: null,
+ cliPath: null,
+ sessions: {},
+ workingDirectory: '',
+
+ setInstalled: (installed, version, path) =>
+ set({ installed, version: version || null, cliPath: path || null }),
+
+ setWorkingDirectory: (dir) => set({ workingDirectory: dir }),
+
+ getSession: (conversationId) => get().sessions[conversationId],
+
+ initSession: (conversationId, workingDir) => {
+ const id = `claude-code-${Date.now()}`
+ set((state) => ({
+ sessions: {
+ ...state.sessions,
+ [conversationId]: {
+ id,
+ conversationId,
+ events: [],
+ status: 'idle',
+ workingDirectory: workingDir,
+ pid: null,
+ },
+ },
+ }))
+ return id
+ },
+
+ addEvent: (conversationId, event) =>
+ set((state) => {
+ const session = state.sessions[conversationId]
+ if (!session) return state
+ return {
+ sessions: {
+ ...state.sessions,
+ [conversationId]: {
+ ...session,
+ events: [...session.events, event],
+ },
+ },
+ }
+ }),
+
+ setSessionStatus: (conversationId, status) =>
+ set((state) => {
+ const session = state.sessions[conversationId]
+ if (!session) return state
+ return {
+ sessions: {
+ ...state.sessions,
+ [conversationId]: { ...session, status },
+ },
+ }
+ }),
+
+ setSessionPid: (conversationId, pid) =>
+ set((state) => {
+ const session = state.sessions[conversationId]
+ if (!session) return state
+ return {
+ sessions: {
+ ...state.sessions,
+ [conversationId]: { ...session, pid },
+ },
+ }
+ }),
+
+ clearSession: (conversationId) =>
+ set((state) => {
+ const { [conversationId]: _, ...rest } = state.sessions
+ return { sessions: rest }
+ }),
+ }),
+ {
+ name: 'locally-uncensored-claude-code',
+ partialize: (state) => ({
+ installed: state.installed,
+ version: state.version,
+ cliPath: state.cliPath,
+ workingDirectory: state.workingDirectory,
+ }),
+ }
+ )
+)