### Installation and Setup Commands Source: https://github.com/stevensu1977/voltcode/blob/main/README.md Commands to clone, install dependencies, and configure the development environment. ```bash git clone https://github.com/stevensu1977/voltcode.git cd voltcode ``` ```bash pnpm install ``` ```bash cp .env.local.example .env.local ``` ```text GEMINI_API_KEY=your_api_key_here ``` ```bash pnpm run tauri:dev ``` ```bash pnpm run tauri:build ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Run this command to install all necessary project dependencies before starting development. ```bash npm install ``` -------------------------------- ### Start Development Server Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Starts the development server, typically accessible at http://localhost:3000. This command is used for local development and testing. ```bash npm run dev ``` -------------------------------- ### Start Development Environment Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Command to launch the development environment. ```bash pnpm tauri:dev ``` -------------------------------- ### Setup Resource Directories Source: https://github.com/stevensu1977/voltcode/blob/main/docs/RESOURCE_MIGRATION.md Bash commands to initialize the directory structure and populate resources. ```bash # Create directories mkdir -p ~/.opencode/{node,cli} # Copy Node.js cp -r ./Resources/bundled-node/darwin-arm64 ~/.opencode/node/ # Extract Claude Code cd ~/.opencode/cli && tar -xzf /path/to/Resources/bundled-agents/darwin-arm64/claude-code-darwin-arm64.tgz ``` -------------------------------- ### Context Usage Workflow Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Example of checking and clearing context. ```text /context # See how much context is used /clear # Clear context if running low ``` -------------------------------- ### Cost Management Workflow Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Example of monitoring and resetting session costs. ```text /cost # Check current spending /clear # Reset if needed /model haiku # Switch to cheaper model ``` -------------------------------- ### Model Switching Workflow Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Example of switching models to match task complexity. ```text /model haiku Write a simple hello world function /model opus Design a complex authentication system with JWT, OAuth, and multi-factor auth ``` -------------------------------- ### Get OpenCode Directory Helper Source: https://github.com/stevensu1977/voltcode/blob/main/docs/RESOURCE_MIGRATION.md Rust function to resolve the ~/.opencode path using environment variables. ```rust fn get_opencode_dir() -> Result { let home = std::env::var("HOME") .or_else(|_| std::env::var("USERPROFILE")) .map_err(|e| format!("Failed to get home directory: {}", e))?; Ok(PathBuf::from(home).join(".opencode")) } ``` -------------------------------- ### Start API Proxy Server via Tauri Command Source: https://github.com/stevensu1977/voltcode/blob/main/docs/API_PROXY_SUMMARY.md Initiates the API proxy server using a Tauri command, allowing configuration of port and model providers. This is useful for integrating the proxy into a Tauri application. ```typescript await invoke('start_api_proxy', { port: 8082, preferredProvider: 'openai', bigModel: 'gpt-4.1', smallModel: 'gpt-4.1-mini' }); ``` -------------------------------- ### Manual Claude CLI Test Source: https://github.com/stevensu1977/voltcode/blob/main/docs/INTEGRATION_STATUS.md A command-line example to manually test the Claude CLI with specific arguments. Useful for isolating issues outside the Tauri application. ```bash ~/.opencode/node/darwin-arm64/bin/node \ ~/.opencode/cli/node_modules/.bin/claude \ --print --output-format json --model sonnet \ "who are you" ``` -------------------------------- ### Tauri Capabilities Configuration Source: https://github.com/stevensu1977/voltcode/blob/main/docs/INTEGRATION_STATUS.md Defines shell permissions for executing the Node.js binary as a sidecar. Ensure the 'cmd' path matches your Node.js installation. ```json { "permissions": [ "core:default", "shell:default", { "identifier": "shell:allow-execute", "allow": [ { "name": "node", "cmd": "/Users/wsuam/.opencode/node/darwin-arm64/bin/node", "args": true, "sidecar": false } ] } ] } ``` -------------------------------- ### Execute Claude CLI Command Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Example of the command executed by the CLI router to interact with the Claude CLI. ```bash node ~/.opencode/cli/node_modules/.bin/claude \ --print \ --output-format json \ --model sonnet \ --dangerously-skip-permissions \ --add-dir /path/to/selected/project \ "创建一个 HTML 文件" ``` -------------------------------- ### Message Flow Example Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Illustrates the core message flow: User message triggers a call to the Gemini API with conversation history. The response is parsed, code is extracted, and the state is updated, automatically switching to the Preview tab. ```typescript const handleMessage = async (content: string) => { const message: Message = { id: Date.now().toString(), text: content, sender: USER, timestamp: new Date(), }; setMessages((prev) => [...prev, message]); try { const response = await chat(messages); const codeBlockRegex = /```(\w*)\n([\s\S]*?)```/g; let match; let extractedCode = ""; while ((match = codeBlockRegex.exec(response)) !== null) { const [, lang, code] = match; if (lang === "html" || lang === "") { extractedCode = code; break; } } if (extractedCode) { setCode(extractedCode); setTab(Tab.PREVIEW); } else { const agentMessage: Message = { id: Date.now().toString(), text: response, sender: AGENT, timestamp: new Date(), }; setMessages((prev) => [...prev, agentMessage]); } } catch (error) { console.error("Error sending message:", error); const errorMessage: Message = { id: Date.now().toString(), text: "An error occurred. Please try again.", sender: AGENT, timestamp: new Date(), isError: true, }; setMessages((prev) => [...prev, errorMessage]); } }; ``` -------------------------------- ### Rust to TypeScript Type Definition Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Example of using `ts-rs` to automatically generate TypeScript interfaces from Rust structs. Ensures type consistency between backend and frontend. ```rust // Rust 定义 #[derive(Debug, Clone, Serialize, Deserialize, TS)] #[ts(export])] pub struct Task { pub id: Uuid, pub title: String, pub status: TaskStatus, } ``` -------------------------------- ### Create a Custom Sidecar Hook Source: https://github.com/stevensu1977/voltcode/blob/main/docs/TAURI_SIDECAR.md A React hook to manage the lifecycle of a Tauri sidecar process, including starting, stopping, and event handling. ```typescript // hooks/useSidecar.ts import { useState, useEffect, useCallback } from 'react'; import { Command, Child } from '@tauri-apps/plugin-shell'; interface SidecarOptions { name: string; args?: string[]; onStdout?: (data: string) => void; onStderr?: (data: string) => void; onClose?: (code: number) => void; autoStart?: boolean; } export function useSidecar({ name, args = [], onStdout, onStderr, onClose, autoStart = false }: SidecarOptions) { const [process, setProcess] = useState(null); const [isRunning, setIsRunning] = useState(false); const [error, setError] = useState(null); const start = useCallback(async () => { try { setError(null); const command = Command.create(name, args); if (onStdout) { command.stdout.on('data', onStdout); } if (onStderr) { command.stderr.on('data', onStderr); } command.on('close', (data) => { setIsRunning(false); setProcess(null); onClose?.(data.code); }); command.on('error', (err) => { setError(err); setIsRunning(false); }); const child = await command.spawn(); setProcess(child); setIsRunning(true); return child; } catch (err) { const errorMsg = err instanceof Error ? err.message : String(err); setError(errorMsg); setIsRunning(false); throw err; } }, [name, args, onStdout, onStderr, onClose]); const stop = useCallback(async () => { if (process) { try { await process.kill(); setIsRunning(false); setProcess(null); } catch (err) { console.error('Failed to kill process:', err); } } }, [process]); useEffect(() => { if (autoStart) { start(); } return () => { if (process) { process.kill().catch(console.error); } }; }, [autoStart]); return { start, stop, isRunning, error, process }; } ``` -------------------------------- ### Rust Workspace Status Enum Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Defines the lifecycle statuses for a workspace, indicating environment setup and agent execution states. Essential for managing workspace operations. ```rust pub enum WorkspaceStatus { SetupRunning, // 环境设置中 SetupComplete, // 环境就绪 SetupFailed, // 环境设置失败 ExecutorRunning, // Agent 执行中 ExecutorComplete, // Agent 完成 ExecutorFailed, // Agent 失败 } ``` -------------------------------- ### Send Message Directly via Tauri Command Source: https://github.com/stevensu1977/voltcode/blob/main/docs/API_PROXY_SUMMARY.md Sends a message directly through the API proxy using a Tauri command, without needing to start a separate server. This allows for quick testing and integration. ```typescript const response = await invoke('api_proxy_send_message', { model: 'claude-3-sonnet', messages: [{ role: 'user', content: 'Hello!' }], maxTokens: 1024, system: 'You are a helpful assistant.', preferredProvider: 'openai' }); ``` -------------------------------- ### Preview Production Build Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Allows you to preview the production build locally before deploying. This command helps in testing the final build. ```bash npm run preview ``` -------------------------------- ### Run API Proxy Server from Environment Variables Source: https://github.com/stevensu1977/voltcode/blob/main/docs/API_PROXY_SUMMARY.md Use this to run the API proxy server, configuring it via environment variables. Ensure necessary API keys and base URLs are set. ```rust use open_code_studio_lib::api_proxy::{server, types::ProxyConfig}; #[tokio::main] async fn main() { // 使用环境变量配置 server::run_server_from_env(8082).await.unwrap(); } ``` -------------------------------- ### Use Sidecar Hook in Component Source: https://github.com/stevensu1977/voltcode/blob/main/docs/TAURI_SIDECAR.md Example implementation of the useSidecar hook within a React component to manage a Node.js process. ```typescript // components/NodeProcess.tsx import React from 'react'; import { useSidecar } from '../hooks/useSidecar'; export function NodeProcessManager() { const { start, stop, isRunning, error } = useSidecar({ name: 'node-sidecar', args: ['server.js'], onStdout: (data) => console.log('Node:', data), onStderr: (data) => console.error('Node error:', data), onClose: (code) => console.log('Node exited with code:', code) }); return (

Node.js Process

Status: {isRunning ? '🟢 Running' : '⚫ Stopped'}

{error &&

Error: {error}

}
); } ``` -------------------------------- ### Build for Production Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Generates a production-ready build of the application. This is used before deploying the application. ```bash npm run build ``` -------------------------------- ### Configure Environment Variable Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md Set the GEMINI_API_KEY in a .env.local file. This key is required for the application to interact with the Gemini API. ```bash GEMINI_API_KEY=your_api_key ``` -------------------------------- ### Tool Registry Implementation Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Manages tool registration with support for both exact name matching and prioritized regex pattern matching. ```typescript // lib/toolRegistry.ts class ToolRegistryClass { private renderers: Map = new Map(); private patternRenderers: ToolRenderer[] = []; register(renderer: ToolRenderer): void { // 精确名称注册 this.renderers.set(renderer.name.toLowerCase(), renderer); // 正则模式注册(支持 MCP 工具等动态工具) if (renderer.pattern) { this.patternRenderers.push(renderer); // 按优先级排序 this.patternRenderers.sort((a, b) => (b.priority || 0) - (a.priority || 0)); } } getRenderer(toolName: string): ToolRenderer | null { // 1. 精确匹配 // 2. 正则模式匹配(按优先级) } } ``` -------------------------------- ### Send Message Using Rust API Client Source: https://github.com/stevensu1977/voltcode/blob/main/docs/API_PROXY_SUMMARY.md Demonstrates sending a message using the Rust API client library. This requires initializing the client, typically from environment variables, and constructing a MessagesRequest. ```rust use open_code_studio_lib::api_proxy::{ApiClient, MessagesRequest, Message, MessageContent}; let client = ApiClient::from_env(); let request = MessagesRequest { model: "claude-3-sonnet".to_string(), max_tokens: 1024, messages: vec![Message { role: "user".to_string(), content: MessageContent::Text("Hello!".to_string()), }], ..Default::default() }; let response = client.send_message(&request).await?; ``` -------------------------------- ### Directory Structure Source: https://github.com/stevensu1977/voltcode/blob/main/docs/RESOURCE_MIGRATION.md The layout of the ~/.opencode directory for CLI and Node resources. ```text ~/.opencode/ ├── node/ │ └── darwin-arm64/ │ └── bin/ │ └── node # Bundled Node.js binary └── cli/ └── node_modules/ └── .bin/ └── claude # Claude Code CLI symlink ``` -------------------------------- ### Open Directory Selection Dialog Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Uses the Tauri dialog plugin to prompt the user to select a directory. ```typescript import { open } from '@tauri-apps/plugin-dialog'; const selected = await open({ directory: true, // 只选择目录 multiple: false, // 单选 title: 'Select Project Directory' }); ``` -------------------------------- ### Project Directory Structure Source: https://github.com/stevensu1977/voltcode/blob/main/README.md Overview of the VoltCode project file organization. ```text voltcode/ ├── App.tsx # Main application orchestrator ├── components/ │ ├── ChatPanel.tsx # Chat interface with AI │ ├── WorkspacePanel.tsx # Preview/Code/Terminal tabs │ ├── Sidebar.tsx # Tool selector │ ├── XTerminal.tsx # Terminal component (xterm.js) │ ├── ProjectSelector.tsx # Project folder selection │ └── ConfigPanel.tsx # Settings modal ├── services/ │ ├── gemini.ts # Gemini AI integration │ ├── cliRouter.ts # CLI routing for AI tools │ ├── sidecar.ts # Sidecar process management │ └── slashCommands.ts # Slash command parser ├── src-tauri/ │ ├── src/lib.rs # Rust backend (PTY, process management) │ └── tauri.conf.json # Tauri configuration └── Resources/ ├── bundled-node/ # Bundled Node.js runtime ├── bundled-agents/ # AI agent configurations └── codex-acp/ # Codex CLI integration ``` -------------------------------- ### Get Mapped Model Name via Tauri Command Source: https://github.com/stevensu1977/voltcode/blob/main/docs/API_PROXY_SUMMARY.md Retrieves the mapped model name for a given Anthropic model and preferred provider using a Tauri command. This helps in understanding how model names are translated. ```typescript const mapped = await invoke('get_mapped_model', { model: 'claude-3-haiku', preferredProvider: 'openai' }); // 返回: { original: 'claude-3-haiku', provider: 'openai', model: 'gpt-4.1-mini', full_name: 'openai/gpt-4.1-mini' } ``` -------------------------------- ### Configure Tauri Resources Source: https://github.com/stevensu1977/voltcode/blob/main/docs/TAURI_SIDECAR.md Platform-specific resource configuration for sidecar binaries in tauri.conf.json. ```json { "bundle": { "resources": { "darwin-arm64": [ "Resources/bundled-node/darwin-arm64/bin/node", "Resources/bundled-agents/darwin-arm64/*.tgz" ], "darwin-x64": [ "Resources/bundled-node/darwin-x64/bin/node", "Resources/bundled-agents/darwin-x64/*.tgz" ], "windows-x64": [ "Resources/bundled-node/windows-x64/node.exe", "Resources/bundled-agents/windows-x64/*.zip" ], "linux-x64": [ "Resources/bundled-node/linux-x64/bin/node", "Resources/bundled-agents/linux-x64/*.tar.gz" ] } } } ``` -------------------------------- ### Configure and Use CLI Router for AI Backends Source: https://context7.com/stevensu1977/voltcode/llms.txt Configure the CLI router with project directory, AI model, permission mode, and provider. Set up a progress callback for streaming updates and send messages to AI backends. Retrieve extracted code and session statistics. ```typescript import { cliRouter } from './services/cliRouter'; // Configure the CLI router cliRouter.setProjectDir('/path/to/project'); cliRouter.setModel('sonnet'); // 'opus', 'sonnet', or 'haiku' cliRouter.setPermissionMode('bypassPermissions'); // 'bypassPermissions', 'acceptEdits', 'default' cliRouter.setProvider('anthropic'); // 'anthropic' or 'bedrock' // For AWS Bedrock provider cliRouter.setProvider('bedrock'); cliRouter.setBedrockRegion('us-west-2'); cliRouter.setBedrockProfile('my-aws-profile'); // Set up progress callback for streaming updates cliRouter.setProgressCallback((update) => { console.log('Progress:', update); }); // Send message to AI backend const response = await cliRouter.sendMessage( 'claude', // 'claude', 'gemini', 'codex', or 'kiro' 'Create a React todo app with TypeScript', [ { role: 'user', content: 'Previous message' }, { role: 'assistant', content: 'Previous response' } ] ); console.log(response.content); // AI response text console.log(response.code); // Extracted code if present // Get session statistics const stats = cliRouter.getSessionStats(); console.log(`Cost: $${stats.totalCost}, Tokens: ${stats.totalTokens}, Turns: ${stats.totalTurns}`); ``` -------------------------------- ### Model Selection Commands Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Commands to switch between Claude models or display current configuration. ```text /model opus # Switch to Claude Opus 4.5 (most capable) /model sonnet # Switch to Claude Sonnet 4.5 (default, balanced) /model haiku # Switch to Claude Haiku 4 (fastest) /model # Show current model and available options ``` -------------------------------- ### Pricing and Usage Tracking Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Structures for tracking model pricing and detailed usage statistics across various dimensions. ```typescript // lib/pricing.ts const MODEL_PRICING: Record = { 'claude-opus-4.5': { input: 5.0, output: 25.0, cacheWrite: 6.25, cacheRead: 0.50 }, 'claude-sonnet-4.5': { input: 3.0, output: 15.0, cacheWrite: 3.75, cacheRead: 0.30 }, 'gpt-5.1-codex': { input: 1.25, output: 10.00, cacheWrite: 0, cacheRead: 0.125 }, // ... 更多模型 }; // 用量统计结构 interface UsageStats { total_cost: number; total_tokens: number; by_model: ModelUsage[]; by_date: DailyUsage[]; by_project: ProjectUsage[]; by_api_base_url?: ApiBaseUrlUsage[]; } ``` -------------------------------- ### Define Shell Permissions in Capabilities Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SHELL_PERMISSIONS.md Create or update the capabilities file to explicitly allow shell command execution. ```json { "$schema": "https://schema.tauri.app/config/2", "identifier": "default", "description": "Default capabilities for the application", "windows": ["main"], "permissions": [ "core:default", "shell:default", { "identifier": "shell:allow-execute", "allow": [ { "name": "exec", "cmd": "", "args": true, "sidecar": false } ] } ] } ``` -------------------------------- ### Rust Build Configuration for Cargo.toml Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Defines two build profiles: 'dev-release' for faster development builds with incremental compilation and 'release' for optimized production builds with minimal size. Adjust 'opt-level', 'lto', and 'codegen-units' for performance tuning. ```toml # Cargo.toml 构建配置 # 开发构建(快速) [profile.dev-release] inherits = "release" opt-level = 2 lto = "thin" codegen-units = 16 incremental = true debug = true # 生产构建(最小体积) [profile.release] opt-level = "z" lto = true codegen-units = 1 panic = "abort" strip = true ``` -------------------------------- ### Verify Node.js and Claude CLI Paths Source: https://github.com/stevensu1977/voltcode/blob/main/docs/INTEGRATION_STATUS.md Shell commands to verify the existence and accessibility of the Node.js binary and the Claude CLI executable. Use these for debugging path issues. ```bash # Node binary ls -la ~/.opencode/node/darwin-arm64/bin/node ``` ```bash # Claude CLI ls -la ~/.opencode/cli/node_modules/.bin/claude ``` -------------------------------- ### Manage Tasks with Task Store Source: https://context7.com/stevensu1977/voltcode/llms.txt Handles task lifecycle, time tracking, and synchronization with TODO.md files. Requires importing task management functions from the taskStore service. ```typescript import { createTaskSession, updateTaskStatus, addTaskItem, toggleTaskItem, getTaskStats, syncTaskToFile } from './services/taskStore'; import { TaskStatus } from './types'; // Create a new task const session = await createTaskSession('claude', 'Implement dark mode', '/project'); // Update task status (automatically handles time tracking) let updatedSession = updateTaskStatus(session, TaskStatus.PAUSED); // Time since last resume is accumulated to totalTimeSpent updatedSession = updateTaskStatus(updatedSession, TaskStatus.IN_PROGRESS); // Resume - records lastResumedAt timestamp updatedSession = updateTaskStatus(updatedSession, TaskStatus.COMPLETED); // Complete - finalizes time tracking // Add TODO items updatedSession = addTaskItem(updatedSession, 'Create theme context'); updatedSession = addTaskItem(updatedSession, 'Update CSS variables'); // Toggle item completion updatedSession = toggleTaskItem(updatedSession, 'item-123456789'); // Get task statistics const stats = getTaskStats(updatedSession); // { totalItems: 2, completedItems: 1, elapsedTime: 3600000, progress: 50 } // Sync to TODO.md file (debounced) await syncTaskToFile(updatedSession); ``` -------------------------------- ### Implement CLIRouter for Directory Management Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Manages the project directory path and constructs CLI commands with appropriate security flags. ```typescript export class CLIRouter { private projectDir: string | null = null; setProjectDir(dir: string) { this.projectDir = dir; console.log('[CLIRouter] Project directory set to:', dir); } getProjectDir(): string | null { return this.projectDir; } } ``` ```typescript const command = Command.create('node', [ claudePath, '--print', '--output-format', 'json', '--model', 'sonnet', '--dangerously-skip-permissions', '--add-dir', this.projectDir!, // 添加项目目录 fullPrompt ]); ``` ```typescript async sendMessage(tool: CLITool, message: string, history: CLIMessage[]) { if (!this.projectDir) { throw new Error('Project directory not set. Please select a project directory first.'); } // ... 路由到相应的 CLI } ``` -------------------------------- ### Initialize Tauri Dialog Plugin Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Registers the dialog plugin within the Rust backend initialization. ```rust .plugin(tauri_plugin_dialog::init()) ``` -------------------------------- ### Configure Tauri Dialog Permissions Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Defines the necessary permissions in the default capabilities file to allow the application to open system dialogs. ```json { "permissions": [ "dialog:default", "dialog:allow-open" ] } ``` -------------------------------- ### Custom Command Implementation Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Structure for adding new commands to the services/slashCommands.ts file. ```typescript export const slashCommands: Record = { // ... existing commands ... mycommand: { name: 'mycommand', description: 'Description of what this command does', aliases: ['mc', 'mycmd'], // Optional short versions execute: (args, context) => { // Command logic here return { success: true, message: 'Command executed successfully', preventSend: true // Don't send to Claude }; } } }; ``` -------------------------------- ### Internationalization Configuration Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Configures i18next with automatic language detection and local storage persistence. ```typescript // i18n 配置 const resources = { en: { translation: en }, zh: { translation: zh }, 'zh-TW': { translation: zhTW } }; // 使用 i18next-browser-languagedetector 自动检测语言 i18n .use(LanguageDetector) .use(initReactI18next) .init({ resources, fallbackLng: 'zh', detection: { order: ['localStorage', 'navigator', 'htmlTag'], caches: ['localStorage'], }, }); ``` -------------------------------- ### Manage Project Directory State Source: https://github.com/stevensu1977/voltcode/blob/main/docs/PROJECT_SELECTOR.md Handles the project directory state and conditional rendering in the main application component. ```typescript const [projectDir, setProjectDir] = useState(null); ``` ```typescript // 如果没有选择项目,显示 ProjectSelector if (!projectDir) { return ; } // 否则显示主界面 return ; ``` ```typescript useEffect(() => { if (projectDir) { cliRouter.setProjectDir(projectDir); // 添加欢迎消息显示项目路径 setMessages(prev => [...prev, { text: `Project directory set to: ${projectDir} All generated files will be saved in this directory.` }]); } }, [projectDir]); ``` -------------------------------- ### Permission Mode Commands Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Commands to configure file operation approval settings. ```text /permission bypass # Auto-approve all operations (default) /permission accept # Auto-approve edits only /permission default # Ask for confirmation (not recommended with --print mode) /permission # Show current permission mode ``` -------------------------------- ### Import Main App Component Source: https://context7.com/stevensu1977/voltcode/llms.txt Imports the main App component which orchestrates state and component composition. ```tsx // Main App orchestrates all state and component composition import App from './App'; ``` -------------------------------- ### Configure Claude Code with Amazon Bedrock Source: https://github.com/stevensu1977/voltcode/blob/main/README.md Environment variables required to integrate Claude Code with AWS Bedrock. ```bash # Set Claude to use Amazon Bedrock export CLAUDE_CODE_USE_BEDROCK=1 # Configure AWS region export AWS_REGION=us-west-2 # Optional: Specify Bedrock model (defaults to Claude Sonnet) export ANTHROPIC_MODEL=us.anthropic.claude-sonnet-4-20250514-v1:0 # Ensure AWS credentials are configured # Option 1: Use AWS CLI profile export AWS_PROFILE=your-profile # Option 2: Use access keys directly export AWS_ACCESS_KEY_ID=your-access-key export AWS_SECRET_ACCESS_KEY=your-secret-key ``` -------------------------------- ### ConfigPanel Component Usage Source: https://context7.com/stevensu1977/voltcode/llms.txt Displays and manages settings, specifically for MCP configuration. Requires modal open state, active tool, parallel configuration, and a handler for configuration changes. ```tsx // ConfigPanel - Settings modal with MCP configuration updateConfig(config)} /> ``` -------------------------------- ### Proposed Slash Commands for Task Management Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md A conceptual set of slash commands to automate the Git worktree workflow within the application. ```text /parallel-task create "修复登录 Bug" --agent claude /parallel-task list /parallel-task start task-123 /parallel-task diff task-123 /parallel-task merge task-123 ``` -------------------------------- ### Sidebar Component Usage Source: https://context7.com/stevensu1977/voltcode/llms.txt Provides tool selection and navigation. Requires the currently active tool, tool selection handler, agent switch request handler, and the project directory. ```tsx // Sidebar - Tool selection and navigation setActiveTool(toolId)} onRequestAgentSwitch={(targetTool) => openSwitchDialog(targetTool)} projectDir="/project" /> ``` -------------------------------- ### Detect Platform in Rust Source: https://github.com/stevensu1977/voltcode/blob/main/docs/TAURI_SIDECAR.md A Tauri command to resolve the correct binary path based on the current operating system and architecture. ```rust #[tauri::command] fn get_platform_specific_path(app_handle: tauri::AppHandle, binary: String) -> Result { let resource_path = app_handle.path().resource_dir().map_err(|e| e.to_string())?; let platform = if cfg!(target_os = "macos") { if cfg!(target_arch = "aarch64") { "darwin-arm64" } else { "darwin-x64" } } else if cfg!(target_os = "windows") { "windows-x64" } else { "linux-x64" }; let binary_path = resource_path .join(format!("Resources/bundled-node/{}/bin/{}", platform, binary)); Ok(binary_path.to_string_lossy().to_string()) } ``` -------------------------------- ### Rust Worktree Cleanup Implementation Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Implements a comprehensive cleanup process for worktree paths and metadata. It involves removing Git worktree registration, cleaning metadata directories, removing the physical worktree, and pruning other management entries. ```rust impl WorktreeManager { /// 综合清理 worktree 路径和元数据 fn comprehensive_worktree_cleanup( repo: &Repository, worktree_path: &Path, ) -> Result<(), WorktreeError> { // Step 1: 使用 GitService 移除 worktree 注册 git_service.remove_worktree(&git_repo_path, worktree_path, true)?; // Step 2: 强制清理元数据目录 Self::force_cleanup_worktree_metadata(&git_repo_path, worktree_path)?; // Step 3: 清理物理 worktree 目录 if worktree_path.exists() { std::fs::remove_dir_all(worktree_path)?; } // Step 4: 清理其他过期的管理条目 git_service.prune_worktrees(&git_repo_path)?; } } ``` -------------------------------- ### Context Provider Nesting Pattern Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Organizes global state by splitting it into multiple specialized providers to avoid a single monolithic state object. ```tsx // App.tsx - 清晰的 Provider 层次结构 ``` -------------------------------- ### Rust Workspace Context Model Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Provides the full context for a workspace, including the workspace itself, its associated task, project details, and related repositories. ```rust pub struct WorkspaceContext { pub workspace: Workspace, pub task: Task, pub project: Project, pub workspace_repos: Vec, } ``` -------------------------------- ### Rust Coding Agent MCP Configuration Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Defines how to retrieve MCP (Multi-Cloud Platform) configuration for different coding agents. It specifies configuration paths, default JSON values, and whether merging is required. ```rust impl CodingAgent { pub fn get_mcp_config(&self) -> McpConfig { match self { Self::Codex(_) => McpConfig::new( vec!["mcp_servers".to_string()], serde_json::json!({ "mcp_servers": {} }), self.preconfigured_mcp(), true, // 需要合并 ), Self::ClaudeCode(_) => McpConfig::new( vec!["mcpServers".to_string()], serde_json::json!({ "mcpServers": {} }), self.preconfigured_mcp(), false, ), // ... 其他 Agent } } } ``` -------------------------------- ### Hooks System Management Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Manages hook configurations with a three-tier priority merge system and event validation. ```typescript // lib/hooksManager.ts class HooksManager { // 支持三级配置合并:user < project < local static mergeConfigs( user: HooksConfiguration, project: HooksConfiguration, local: HooksConfiguration ): HooksConfiguration { // 按优先级合并 } // 支持的 Hook 事件 const allEvents = [ 'PreToolUse', 'PostToolUse', 'Notification', 'UserPromptSubmit', 'Stop', 'SubagentStop', 'PreCompact', 'SessionStart', 'SessionEnd' ]; } ``` -------------------------------- ### Rust Workspace Model Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Represents a workspace, linking a task to a Git branch and agent execution details. Includes fields for container reference and agent working directory. ```rust pub struct Workspace { pub id: Uuid, pub task_id: Uuid, pub container_ref: Option, pub branch: String, // Git 分支名 pub agent_working_dir: Option, // Agent 工作目录 pub setup_completed_at: Option>, } ``` -------------------------------- ### Session Management Commands Source: https://github.com/stevensu1977/voltcode/blob/main/docs/SLASH_COMMANDS.md Commands for clearing history, opening settings, and checking status. ```text /clear # Clears all messages and resets session statistics ``` ```text /config # Opens the settings panel ``` ```text /cost ``` ```text /context ``` ```text /skills ``` ```text /help # Display this help message ``` -------------------------------- ### Manage Chat Sessions with Session Store Source: https://context7.com/stevensu1977/voltcode/llms.txt Manage chat sessions using Tauri's plugin-store for persistence. Supports creating new chat or task sessions, loading, saving, searching, and exporting sessions. Retrieves session statistics. ```typescript import { createNewSession, createNewTaskSession, loadSessions, saveSessions, searchSessions, getSessionStats, exportSessionToMarkdown } from './services/sessionStore'; // Create a new chat session const session = createNewSession('claude'); // session: { id, title: 'New Chat', messages: [...], createdAt, updatedAt } // Create a task session with time tracking const taskSession = await createNewTaskSession('claude', 'Fix login bug', '/project/path'); // Creates TODO.md at /project/path/.voltcode/TODO.md // Load saved sessions on app startup const savedHistory = await loadSessions(); // Returns Record or null // Search across all sessions const results = searchSessions(history, 'authentication'); // results: [{ toolId, session, matches: ['Title: "Auth fix"', 'Message: "...auth..."'] }] // Get statistics const stats = getSessionStats(history); console.log(`Total: ${stats.totalSessions} sessions, ${stats.totalMessages} messages`); console.log(`Tasks: ${stats.totalTasks} total, ${stats.activeTasks} active`); // Export session to Markdown const markdown = exportSessionToMarkdown(session, 'claude'); ``` -------------------------------- ### Rust Task Model Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md Represents a single task within the project. Includes fields for ID, project association, title, description, status, and relationships for nesting or sharing. ```rust pub struct Task { pub id: Uuid, pub project_id: Uuid, pub title: String, pub description: Option, pub status: TaskStatus, pub parent_workspace_id: Option, // 支持任务嵌套 pub shared_task_id: Option, // 支持共享任务 } ``` -------------------------------- ### Parse and Execute Slash Commands Source: https://context7.com/stevensu1977/voltcode/llms.txt Parses user input for slash commands and executes them within a provided context. Commands allow for model switching, configuration, and task management. ```typescript import { parseSlashCommand, executeSlashCommand, slashCommands } from './services/slashCommands'; // Parse user input const parsed = parseSlashCommand('/model opus'); // { isCommand: true, command: 'model', args: ['opus'] } // Execute command with context const result = await executeSlashCommand('model', ['opus'], { setModel: (model) => cliRouter.setModel(model), currentModel: 'sonnet', sessionCost: { cost: 0.05, tokens: 5000, turns: 3 } }); // { success: true, message: '✓ Switched to Claude Opus', preventSend: true } // Available commands: // /model [opus|sonnet|haiku] - Change AI model // /permission [bypass|accept|default] - Set permission mode // /clear - Clear conversation // /cost - Show session cost and usage // /context - Show context usage // /config - Open configuration panel // /skills - List available Claude skills // /plugin - List MCP servers // /agents [explore|plan|default] - Switch agent mode // /task create|status|pause|resume|done|add|check|list - Task management // /help - Show all commands ``` -------------------------------- ### Session Context Memoization Source: https://github.com/stevensu1977/voltcode/blob/main/docs/ANYCODE_SUMMARY.md Optimizes context values using useMemo to prevent unnecessary re-renders. ```tsx // 使用 useMemo 缓存 context 值,只有依赖真正变化时才重新创建 const contextValue = React.useMemo( () => ({ session, projectPath, sessionId, ... }), [session, projectPath, sessionId, ...] ); ``` -------------------------------- ### Gemini API Integration Layer Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md This service handles integration with the Gemini API using the @google/genai SDK. It configures the agent as a Frontend React expert and expects HTML responses wrapped in markdown code blocks. ```typescript import { GoogleGenerativeAI } from "@google/genai"; const genAI = new GoogleGenerativeAI(process.env.API_KEY!); const model = genAI.getGenerativeModel({ model: "gemini-3-pro-preview" }); const generationConfig = { temperature: 0.7, top_p: 1, top_k: 1, }; const modelConfig = { ...model, generationConfig, // System instruction configures the agent as a Frontend React expert. systemInstruction: "You are a Frontend React expert. Respond with HTML code wrapped in markdown code blocks. For example: ```html\n

Hello World

\n```", }; export async function chat(history: ChatCompletionMessage[]) { const chat = model.startChat({ history: history.map((message) => ({ role: message.role === "user" ? "user" : "model", parts: [{ text: message.content }], })), ...modelConfig, }); const result = await chat.sendMessage( history[history.length - 1].content ); const response = await result.response; const text = response.text(); return text; } ``` -------------------------------- ### Manual Git Worktree Operations Source: https://github.com/stevensu1977/voltcode/blob/main/docs/VIBE_KANBAN_SUMMARY.md A sequence of shell commands to manually manage Git worktrees and execute tasks, serving as a baseline for the project's automation logic. ```bash # 手动 Git Worktree 操作(无需代码修改) # 1. 创建 worktree git worktree add ../task-fix-bug feature/fix-bug # 2. 在 worktree 中启动 Agent cd ../task-fix-bug claude --dangerously-skip-permissions "修复登录页面的 Bug" # 3. 查看 diff git diff main..feature/fix-bug # 4. 合并 cd ../main-project git merge feature/fix-bug # 5. 清理 git worktree remove ../task-fix-bug git branch -d feature/fix-bug ``` -------------------------------- ### Iframe Sandbox Configuration Source: https://github.com/stevensu1977/voltcode/blob/main/CLAUDE.md The iframe used for previewing generated code is configured with specific sandbox attributes to control security and allowed features. This ensures a safe environment for executing potentially untrusted code. ```html ``` -------------------------------- ### MCP Server Management API Source: https://context7.com/stevensu1977/voltcode/llms.txt Endpoints for configuring and managing Model Context Protocol (MCP) servers. ```APIDOC ## POST add_mcp_server ### Description Registers a new MCP server configuration. ### Method POST ### Endpoint add_mcp_server ### Request Body - **name** (string) - Required - Server name. - **transport** (string) - Required - 'stdio' or 'http'. - **command** (string) - Optional - Command to run. - **args** (string[]) - Optional - Arguments for the command. ``` -------------------------------- ### Node.js Command Execution Source: https://github.com/stevensu1977/voltcode/blob/main/docs/INTEGRATION_STATUS.md Constructs a command to execute the Claude CLI using Node.js. This pattern is used for invoking the CLI with specific flags and prompts. ```typescript const command = Command.create('node', [ claudePath, // ~/.opencode/cli/node_modules/.bin/claude '--print', '--output-format', 'json', '--model', 'sonnet', fullPrompt ]); ``` -------------------------------- ### File Operations API Source: https://context7.com/stevensu1977/voltcode/llms.txt Endpoints for managing files and directories within the project workspace. ```APIDOC ## POST read_directory ### Description Reads the contents of a specified directory. ### Method POST ### Endpoint read_directory ### Request Body - **directory** (string) - Required - The path to the directory to read. ### Response - **FileItem[]** - List of files and directories. ``` ```APIDOC ## POST read_file_content ### Description Reads the content of a specific file. ### Method POST ### Endpoint read_file_content ### Request Body - **filePath** (string) - Required - The path to the file. ### Response - **string** - The file content. ``` ```APIDOC ## POST save_file ### Description Saves content to a file. ### Method POST ### Endpoint save_file ### Request Body - **filePath** (string) - Required - The path to the file. - **content** (string) - Required - The content to write. ```